public bool DeleteTransactionGroup(TransactionGroup entity)
 {
     if(entity==null) return false;
        _unitOfWork.TransactionGroupRepository.Delete(entity);
        _unitOfWork.Save();
        return true;
 }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Document doc = uidoc.Document;

              using( TransactionGroup g
            = new TransactionGroup( doc ) )
              {
            g.Start( "Cut Beam with Voids" );

            // Retrieve or load cutting symbol

            FamilySymbol cuttingSymbol
              = RetrieveOrLoadCuttingSymbol( doc );

            // Select beam to cut

            Selection sel = uidoc.Selection;

            FamilyInstance beam = null;

            try
            {
              Reference r = sel.PickObject(
            ObjectType.Element,
            new BeamSelectionFilter(),
            "Pick beam to cut" );

              beam = doc.GetElement( r.ElementId )
            as FamilyInstance;
            }
            catch( Autodesk.Revit.Exceptions
              .OperationCanceledException )
            {
              return Result.Cancelled;
            }

            // Place cutting instances and apply cuts

            CutBeamWithVoid( beam, cuttingSymbol );

            g.Assimilate();

            // Calling Commit after Assimilate throws an
            // exception saying "The Transaction group has
            // not been started (its status is not
            // 'Started').."

            //g.Commit();
              }
              return Result.Succeeded;
        }
示例#3
0
        //[Test]
        //[ExpectedException(typeof(Exception))]
        //public void CannotSaveTransaction()
        //{
        //    TransactionGroup tran = CreateNewTransactionGroup();
        //    Assert.AreEqual(0, tran.ID);

        //    TransactionController controller = new TransactionController();
        //    controller.AddNewTransaction(1,100,"MSZ");
        //    //
        //    UnitOfWork.Current.TransactionalFlush();
        //    UnitOfWork.CurrentSession.Evict(tran);
        //}

        public static TransactionGroup CreateNewTransactionGroup()
        {
            TransactionGroup g = new TransactionGroup();
            g.CompanyId = "MSZ";
            //g.Company = new Company("MSZ");
            g.Closed = false;
            g.Income = 0;

            g = Repository<TransactionGroup>.Save(g);
            
            return g;
        }
示例#4
0
文件: Command.cs 项目: AMEE/revit
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // data verification
             if (null == commandData.Application.ActiveUIDocument)
             {
            return Autodesk.Revit.UI.Result.Failed;
             }

             MyDocument mydocument = new MyDocument(commandData);

             // check whether the mass is kind of parallelepiped
             CurtainSystem.MassChecker checker = new CurtainSystem.MassChecker(mydocument);
             bool validMass = checker.CheckSelectedMass();

             if (!validMass)
             {
            message = Properties.Resources.MSG_InvalidSelection;
            return Result.Cancelled;
             }

             UI.CurtainForm curtainForm = null;
             TransactionGroup transactionGroup = new TransactionGroup(commandData.Application.ActiveUIDocument.Document);
             try
             {
            transactionGroup.Start("CurtainSystemOperation");
            curtainForm = new UI.CurtainForm(mydocument);

            if (null != curtainForm && false == curtainForm.IsDisposed)
            {
               curtainForm.ShowDialog();
            }

            transactionGroup.Commit();
             }
             catch (System.Exception ex)
             {
             	transactionGroup.RollBack();
            message = ex.Message;
            return Result.Failed;
             }
             finally
             {
            if (null != curtainForm && false == curtainForm.IsDisposed)
            {
               curtainForm.Dispose();
            }
             }

             return Autodesk.Revit.UI.Result.Succeeded;
        }
 public void Add(string itemPath, string category, int index, TransactionGroup transactionGroup)
 {
     this.Items[index] = new Item()
     {
         ItemPath = itemPath,
         Category = category,
         Total = transactionGroup.Total,
         Count = transactionGroup.Count,
         TotalPercentage = transactionGroup.TotalPercentage.Count > 0 ? transactionGroup.TotalPercentage[0] : 0,
         CountPercentage = transactionGroup.CountPercentage.Count > 0 ? transactionGroup.CountPercentage[0] : 0,
         TotalPercentageGrandParentRelation = transactionGroup.TotalPercentage.Count > 1 ? transactionGroup.TotalPercentage[1] : 0,
         CountPercentageGrandParentRelation = transactionGroup.CountPercentage.Count > 1 ? transactionGroup.CountPercentage[1] : 0,
     };
 }
示例#6
0
        public TransactionGroup AddNewTransGroup(string companyId, bool closed, decimal income)
        {
            TransactionGroup g = new TransactionGroup();
            g.CompanyId = companyId;
            g.Closed = false;
            g.Income = income;

            try
            {
                Repository<TransactionGroup>.Save(g);
                UnitOfWork.Current.TransactionalFlush();
            }
            catch (Exception ex)
            {
                UnitOfWork.CurrentSession.Clear();
                return null;
            }

            return g;
        }
示例#7
0
        /// <summary>
        /// This method implements the external command within
        /// Revit.
        /// </summary>
        /// <param name="commandData">An ExternalCommandData
        /// object which contains reference to Application and
        /// View needed by external command.</param>
        /// <param name="message">Error message can be returned
        /// by external command. This will be displayed only if
        /// the command status was "Failed". There is a limit
        /// of 1023 characters for this message; strings longer
        /// than this will be truncated.</param>
        /// <param name="elements">Element set indicating
        /// problem elements to display in the failure dialog.
        /// This will be used only if the command status was
        /// "Failed".</param>
        /// <returns>The result indicates if the execution
        /// fails, succeeds, or was canceled by user. If it
        /// does not succeed, Revit will undo any changes made
        /// by the external command.</returns>
        Result IExternalCommand.Execute(
            ExternalCommandData commandData, ref string message
            , ElementSet elements)
        {
            ResourceManager res_mng = new ResourceManager(
                GetType());
            ResourceManager def_res_mng = new ResourceManager(
                typeof(Properties.Resources));

            Result result = Result.Failed;

            try
            {
                UIApplication ui_app = commandData?.Application
                ;
                UIDocument  ui_doc = ui_app?.ActiveUIDocument;
                Application app    = ui_app?.Application;
                Document    doc    = ui_doc?.Document;

                /* Wrap all transactions into the transaction
                 * group. At first we get the transaction group
                 * localized name. */
                var tr_gr_name = UIBuilder.GetResourceString(
                    GetType(), typeof(Properties.Resources),
                    "_transaction_group_name");

                using (var tr_gr = new TransactionGroup(doc,
                                                        tr_gr_name))
                {
                    if (TransactionStatus.Started == tr_gr
                        .Start())
                    {
                        /* Here do your work or the set of
                         * works... */
                        if (DoWork(commandData, ref message,
                                   elements))
                        {
                            if (TransactionStatus.Committed ==
                                tr_gr.Assimilate())
                            {
                                result = Result.Succeeded;
                            }
                        }
                        else
                        {
                            tr_gr.RollBack();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show(def_res_mng.GetString("_Error")
                                , ex.Message);

                result = Result.Failed;
            }
            finally
            {
                res_mng.ReleaseAllResources();
                def_res_mng.ReleaseAllResources();
            }

            return(result);
        }
        /// <summary>
        /// Выполнить процедуру слияния выбранных размеров
        /// </summary>
        public void MergeExecute()
        {
            var          selection   = _application.ActiveUIDocument.Selection;
            var          doc         = _application.ActiveUIDocument.Document;
            var          prompt      = Language.GetItem(new ModPlusConnector().Name, "h1");
            const double tol         = 0.0001;
            var          elementsIds = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                       .WhereElementIsNotElementType()
                                       .Select(e => e.Id.IntegerValue)
                                       .ToList();

            while (true)
            {
                try
                {
                    var dimensions = selection
                                     .PickElementsByRectangle(new DimensionsFilter(), prompt)
                                     .OfType <Dimension>().ToList();

                    var byDimLineDictionary = new Dictionary <Line, List <Dimension> >();
                    foreach (var dimension in dimensions)
                    {
                        if (!(dimension.Curve is Line line))
                        {
                            continue;
                        }

                        var isMatch = false;
                        foreach (var pair in byDimLineDictionary)
                        {
                            if ((Math.Abs(pair.Key.Origin.DistanceTo(line.Origin)) < tol &&
                                 Math.Abs(Math.Abs(pair.Key.Direction.DotProduct(line.Direction)) - 1) < tol) ||
                                Math.Abs(Math.Abs(pair.Key.Direction.DotProduct(Line.CreateBound(pair.Key.Origin, line.Origin).Direction)) - 1) < tol)
                            {
                                isMatch = true;
                                pair.Value.Add(dimension);
                                break;
                            }
                        }

                        if (!isMatch)
                        {
                            byDimLineDictionary.Add(line, new List <Dimension> {
                                dimension
                            });
                        }
                    }

                    var transactionName = Language.GetFunctionLocalName(new ModPlusConnector());
                    if (string.IsNullOrEmpty(transactionName))
                    {
                        transactionName = "Merge dimensions";
                    }

                    using (var t = new TransactionGroup(doc, transactionName))
                    {
                        t.Start();
                        foreach (var pair in byDimLineDictionary)
                        {
                            if (pair.Value.Count < 1)
                            {
                                continue;
                            }
                            try
                            {
                                using (var tr = new Transaction(doc, "Merge dims"))
                                {
                                    tr.Start();

                                    var referenceArray = new ReferenceArray();
                                    var view           = pair.Value.First().View;
                                    var type           = pair.Value.First().DimensionType;
                                    var dimsData       = new List <DimData>();
                                    foreach (var d in pair.Value)
                                    {
                                        if (d.NumberOfSegments > 0)
                                        {
                                            dimsData.AddRange(from DimensionSegment segment in d.Segments select new DimData(segment));
                                        }
                                        else
                                        {
                                            dimsData.Add(new DimData(d));
                                        }

                                        foreach (Reference reference in d.References)
                                        {
                                            if (reference.ElementId != ElementId.InvalidElementId &&
                                                !elementsIds.Contains(reference.ElementId.IntegerValue))
                                            {
                                                continue;
                                            }

                                            if (reference.ElementId != ElementId.InvalidElementId &&
                                                doc.GetElement(reference.ElementId) is Grid grid)
                                            {
                                                referenceArray.Append(new Reference(grid));
                                            }
                                            else if (reference.ElementId != ElementId.InvalidElementId &&
                                                     doc.GetElement(reference.ElementId) is Level level)
                                            {
                                                referenceArray.Append(new Reference(level));
                                            }
                                            else
                                            {
                                                referenceArray.Append(reference);
                                            }
                                        }
                                    }

                                    if (doc.Create.NewDimension(view, pair.Key, referenceArray, type) is Dimension createdDimension)
                                    {
                                        if (ModPlus_Revit.Utils.Dimensions.TryRemoveZeroes(createdDimension, out referenceArray))
                                        {
                                            if (doc.Create.NewDimension(view, pair.Key, referenceArray, type) is Dimension reCreatedDimension)
                                            {
                                                doc.Delete(createdDimension.Id);
                                                RestoreTextFields(reCreatedDimension, dimsData);
                                            }
                                        }
                                        else
                                        {
                                            RestoreTextFields(createdDimension, dimsData);
                                        }

                                        doc.Delete(pair.Value.Select(d => d.Id).ToList());
                                    }

                                    tr.Commit();
                                }
                            }
                            catch (Exception exception)
                            {
                                ExceptionBox.Show(exception);
                            }
                        }

                        t.Assimilate();
                    }
                }
                catch (Autodesk.Revit.Exceptions.OperationCanceledException)
                {
                    break;
                }
            }
        }
示例#9
0
        /// <summary>
        /// add node to tree view control
        /// </summary>
        /// <param name="type">indicate operation type</param>
        /// <param name="info">tree node text</param>
        private void AddNode(OperationType type, string info)
        {
            //add tree node according to operation type
            if (type == OperationType.StartTransactionGroup)
            {
                if (m_transGroupNode == null)
                {
                    m_transGroupNode = new TreeNode(m_transactionGroup.GetName());
                    int index = m_rootNode.Nodes.Add(m_transGroupNode);
                    m_rootNode.Nodes[index].Tag = m_transactionGroup;
                    m_rootNode.Expand();
                    UpdateTreeNode(m_transGroupNode, type);
                }
                else
                {
                    TreeNode newTransGroupNode = new TreeNode(m_transactionGroup.GetName());
                    int      index             = m_transGroupNode.Nodes.Add(newTransGroupNode);
                    m_transGroupNode.Nodes[index].Tag = m_transactionGroup;
                    m_transGroupNode.Expand();
                    m_transGroupNode = newTransGroupNode;
                    m_transGroupNode.Expand();
                    UpdateTreeNode(m_transGroupNode, type);
                }
                m_transNode   = null;
                m_transaction = null;
            }
            else if (type == OperationType.RollbackTransactionGroup)
            {
                UpdateTreeNode(m_transGroupNode, type);
                if (m_transGroupNode.Parent.Equals(m_rootNode))
                {
                    m_rootNode.Expand();
                    m_transactionGroup = null;
                    m_transGroupNode   = null;
                }
                else
                {
                    m_transGroupNode = m_transGroupNode.Parent;
                    m_transGroupNode.Expand();
                    m_transactionGroup = m_transGroupNode.Tag as TransactionGroup;
                }
                m_transNode   = null;
                m_transaction = null;
            }
            else if (type == OperationType.CommitTransactionGroup)
            {
                UpdateTreeNode(m_transGroupNode, type);
                if (m_transGroupNode.Parent.Equals(m_rootNode))
                {
                    m_rootNode.Expand();
                    m_transactionGroup = null;
                    m_transGroupNode   = null;
                }
                else
                {
                    m_transGroupNode.Expand();
                    m_transGroupNode   = m_transGroupNode.Parent;
                    m_transactionGroup = m_transGroupNode.Tag as TransactionGroup;
                }
                m_transNode   = null;
                m_transaction = null;
            }
            else if (type == OperationType.StartTransaction)
            {
                m_transNode           = new TreeNode(m_transaction.GetName());
                m_transNode.ForeColor = m_startedColor;
                TreeNode node = m_transGroupNode == null ? m_rootNode : m_transGroupNode;
                node.Nodes.Add(m_transNode);
                node.Expand();
                UpdateTreeNode(m_transNode, type);
            }
            else if (type == OperationType.CommitTransaction)
            {
                UpdateTreeNode(m_transNode, type);
                TreeNode node = m_transGroupNode == null ? m_rootNode : m_transGroupNode;
                node.Expand();
                m_transNode = null;
            }
            else if (type == OperationType.RollbackTransaction)
            {
                UpdateTreeNode(m_transNode, type);
                TreeNode node = m_transGroupNode == null ? m_rootNode : m_transGroupNode;
                node.Expand();
                m_transNode = null;
            }
            else
            {
                string childNodeText = null;

                if (String.IsNullOrEmpty(info))
                {
                    childNodeText = "Operation";
                }
                else
                {
                    childNodeText = info;
                }

                TreeNode childNode = new TreeNode(childNodeText);
                if (type == OperationType.ObjectDeletion)
                {
                    childNode.ForeColor = m_deletedColor;
                }
                else
                {
                    childNode.ForeColor = m_normalColor;
                }
                m_transNode.Nodes.Add(childNode);
                m_transNode.Expand();
            }
        }
        public static Result Execute
        (
            UIApplication app,
            View view,
            IDictionary <string, string> JournalData,
            string filePath,
            ref string message
        )
        {
            var result = Result.Failed;

            if ((result = ReadFromFile(filePath, out var definition)) == Result.Succeeded)
            {
                using (definition)
                {
                    bool enableSolutions = GH_Document.EnableSolutions;
                    var  currentCulture  = Thread.CurrentThread.CurrentCulture;
                    try
                    {
                        using (var transGroup = new TransactionGroup(app.ActiveUIDocument.Document))
                        {
                            transGroup.Start(Path.GetFileNameWithoutExtension(definition.Properties.ProjectFileName));

                            GH_Document.EnableSolutions = true;
                            definition.Enabled          = true;
                            definition.ExpireSolution();

                            var inputs = GetInputParams(definition);
                            result = PromptForInputs(app.ActiveUIDocument, inputs, out var values);
                            if (result != Result.Succeeded)
                            {
                                return(result);
                            }

                            // Update input volatile data values
                            foreach (var value in values)
                            {
                                value.Key.AddVolatileDataList(new Grasshopper.Kernel.Data.GH_Path(0), value.Value);
                            }

                            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
                            using (var modal = new Rhinoceros.ModalScope())
                            {
                                definition.NewSolution(false, GH_SolutionMode.Silent);

                                do
                                {
                                    if (modal.Run(false, false) == Result.Failed)
                                    {
                                        return(Result.Failed);
                                    }
                                } while (definition.ScheduleDelay >= GH_Document.ScheduleRecursive);
                            }
                            Thread.CurrentThread.CurrentCulture = currentCulture;

                            if (definition.SolutionState == GH_ProcessStep.Aborted)
                            {
                                message = $"Solution aborted by user after ~{ definition.SolutionSpan.TotalSeconds} seconds";
                                return(Result.Cancelled);
                            }

                            transGroup.Assimilate();
                        }
                    }
                    catch (Exception e)
                    {
                        message = e.Message;
                        return(Result.Failed);
                    }
                    finally
                    {
                        Thread.CurrentThread.CurrentCulture = currentCulture;
                        GH_Document.EnableSolutions         = enableSolutions;
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Saves the receipt transaction.
        /// </summary>
        /// <param name="receiveModels">The receive models.</param>
        /// <param name="user">The user.</param>
        public void SaveReceiptTransaction(ReceiveViewModel receiveModels, UserProfile user)
        {
            // Populate more details of the reciept object
            // Save it when you are done.

            Receive receive = receiveModels.GenerateReceive();
            receive.CreatedDate = DateTime.Now;
            receive.HubID = user.DefaultHub.HubID;
            receive.UserProfileID = user.UserProfileID;
            var commType = _unitOfWork.CommodityTypeRepository.FindById(receiveModels.CommodityTypeID);

            // var comms = GenerateReceiveDetail(commodities);

            foreach (ReceiveDetailViewModel c in receiveModels.ReceiveDetails)
            {
                if (commType.CommodityTypeID == 2)//if it's a non food
                {
                    c.ReceivedQuantityInMT = 0;
                    c.SentQuantityInMT = 0;
                }
                TransactionGroup tgroup = new TransactionGroup();

                var receiveDetail = new ReceiveDetail()
                {
                    CommodityID = c.CommodityID,
                    Description = c.Description,
                    SentQuantityInMT = c.SentQuantityInMT.Value,
                    SentQuantityInUnit = c.SentQuantityInUnit.Value,
                    UnitID = c.UnitID,
                    ReceiveID = receive.ReceiveID
                };
                if (c.ReceiveDetailID.HasValue)
                {
                    receiveDetail.ReceiveDetailID = c.ReceiveDetailID.Value;
                }

                // receiveDetail.TransactionGroupID = tgroup.TransactionGroupID;
                receiveDetail.TransactionGroup = tgroup;
                receive.ReceiveDetails.Add(receiveDetail);

                Transaction transaction = new Transaction();
                transaction.TransactionDate = DateTime.Now;
                transaction.ParentCommodityID = _unitOfWork.CommodityRepository.FindById(c.CommodityID).ParentID ?? c.CommodityID;
                transaction.CommodityID = c.CommodityID;
                transaction.LedgerID = Ledger.Constants.GOODS_ON_HAND_UNCOMMITED;
                transaction.HubOwnerID = user.DefaultHub.HubOwnerID;

                transaction.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, receive.HubID);
                transaction.ShippingInstructionID = _shippingInstructionService.GetSINumberIdWithCreate(receiveModels.SINumber).ShippingInstructionID;

                //TODO:After Implementing ProjectCodeService Please Return Here
                //transaction.ProjectCodeID = repository.ProjectCode.GetProjectCodeIdWIthCreate(receiveModels.ProjectNumber).ProjectCodeID;
                transaction.HubID = user.DefaultHub.HubID;
                transaction.UnitID = c.UnitID;
                if (c.ReceivedQuantityInMT != null) transaction.QuantityInMT = c.ReceivedQuantityInMT.Value;
                if (c.ReceivedQuantityInUnit != null) transaction.QuantityInUnit = c.ReceivedQuantityInUnit.Value;
                if (c.CommodityGradeID != null) transaction.CommodityGradeID = c.CommodityGradeID.Value;

                transaction.ProgramID = receiveModels.ProgramID;
                transaction.StoreID = receiveModels.StoreID;
                transaction.Stack = receiveModels.StackNumber;
                transaction.TransactionGroupID = tgroup.TransactionGroupID;
                tgroup.Transactions.Add(transaction);

                // do the second half of the transaction here.

                var transaction2 = new Transaction();
                transaction2.TransactionDate = DateTime.Now;
                //TAKEs the PARENT FROM THE FIRST TRANSACTION
                transaction2.ParentCommodityID = transaction.ParentCommodityID;
                transaction2.CommodityID = c.CommodityID;
                transaction2.HubOwnerID = user.DefaultHub.HubOwnerID;
                //Decide from where the -ve side of the transaction comes from
                //it is either from the allocated stock
                // or it is from goods under care.

                // this means that this receipt is done without having gone through the gift certificate process.

                if (receiveModels.CommoditySourceID == BLL.CommoditySource.Constants.DONATION || receiveModels.CommoditySourceID == BLL.CommoditySource.Constants.LOCALPURCHASE)
                {
                    transaction2.LedgerID = Ledger.Constants.GOODS_UNDER_CARE;
                    transaction2.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.DONOR, receive.ResponsibleDonorID.Value);
                }
                else if (receiveModels.CommoditySourceID == BLL.CommoditySource.Constants.REPAYMENT)
                {
                    transaction2.LedgerID = Ledger.Constants.GOODS_RECIEVABLE;
                    transaction2.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, receiveModels.SourceHubID.Value);
                }
                else
                {
                    transaction2.LedgerID = Ledger.Constants.LIABILITIES;
                    transaction2.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, receiveModels.SourceHubID.Value);
                }

                transaction2.ShippingInstructionID = _shippingInstructionService.GetSINumberIdWithCreate(receiveModels.SINumber).ShippingInstructionID;
                //TODO:After Implementing ProjectCodeService Please return here
                //transaction2.ProjectCodeID = repository.ProjectCode.GetProjectCodeIdWIthCreate(receiveModels.ProjectNumber).ProjectCodeID;
                transaction2.HubID = user.DefaultHub.HubID;
                transaction2.UnitID = c.UnitID;
                // this is the credit part, so make it Negative
                if (c.ReceivedQuantityInMT != null) transaction2.QuantityInMT = -c.ReceivedQuantityInMT.Value;
                if (c.ReceivedQuantityInUnit != null) transaction2.QuantityInUnit = -c.ReceivedQuantityInUnit.Value;
                if (c.CommodityGradeID != null) transaction2.CommodityGradeID = c.CommodityGradeID.Value;

                transaction2.ProgramID = receiveModels.ProgramID;
                transaction2.StoreID = receiveModels.StoreID;
                transaction2.Stack = receiveModels.StackNumber;
                transaction2.TransactionGroupID = tgroup.TransactionGroupID;
                // hack to get past same key object in context error
                //repository.Transaction = new TransactionRepository();
                tgroup.Transactions.Add(transaction2);

            }

            // Try to save this transaction
            //   db.Database.Connection.Open();
            //  DbTransaction dbTransaction = db.Database.Connection.BeginTransaction();
            try
            {
                //repository.Receive.Add(receive);
                _unitOfWork.ReceiveRepository.Add(receive);
                _unitOfWork.Save();
            }
            catch (Exception exp)
            {
                //  dbTransaction.Rollback();
                //TODO: Save the exception somewhere
                throw new Exception("The Receipt Transaction Cannot be saved. <br />Detail Message :" + exp.StackTrace);

            }
        }
        /// <summary>
        /// Saves the starting balance transaction.
        /// </summary>
        /// <param name="startingBalance">The starting balance.</param>
        /// <param name="user">The user.</param>
        /// <exception cref="System.Exception"></exception>
        public void SaveStartingBalanceTransaction(StartingBalanceViewModel startingBalance, UserProfile user)
        {
            int repositoryAccountGetAccountIDWithCreateNegative = _accountService.GetAccountIdWithCreate(Account.Constants.DONOR, startingBalance.DonorID); ;
            //TODO:After Implementing ProjectCodeService please return here
            int repositoryProjectCodeGetProjectCodeIdWIthCreateProjectCodeID = 0;//_projectCodeService.GetProjectCodeIdWIthCreate(startingBalance.ProjectNumber).ProjectCodeID; ;
            int repositoryShippingInstructionGetSINumberIdWithCreateShippingInstructionID =_shippingInstructionService.GetSINumberIdWithCreate(startingBalance.SINumber).ShippingInstructionID; ;
            int repositoryAccountGetAccountIDWithCreatePosetive = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, user.DefaultHub.HubID); ;

            TransactionGroup transactionGroup = new TransactionGroup();

            Transaction transactionOne = new Transaction();

            transactionOne.PartitionID = 0;
            transactionOne.LedgerID = Ledger.Constants.GOODS_UNDER_CARE;
            transactionOne.HubOwnerID = user.DefaultHub.HubOwner.HubOwnerID;
            transactionOne.AccountID = repositoryAccountGetAccountIDWithCreateNegative;
            transactionOne.HubID = user.DefaultHub.HubID;
            transactionOne.StoreID = startingBalance.StoreID;
            transactionOne.Stack = startingBalance.StackNumber;
            transactionOne.ProjectCodeID = repositoryProjectCodeGetProjectCodeIdWIthCreateProjectCodeID;
            transactionOne.ShippingInstructionID = repositoryShippingInstructionGetSINumberIdWithCreateShippingInstructionID;
            transactionOne.ProgramID = startingBalance.ProgramID;
            var comm = _unitOfWork.CommodityRepository.FindById(startingBalance.CommodityID);
            transactionOne.ParentCommodityID = (comm.ParentID != null)
                                                       ? comm.ParentID.Value
                                                       : comm.CommodityID;
            transactionOne.CommodityID = startingBalance.CommodityID;
            transactionOne.CommodityGradeID = null;
            transactionOne.QuantityInMT = 0 - startingBalance.QuantityInMT;
            transactionOne.QuantityInUnit = 0 - startingBalance.QuantityInUnit;
            transactionOne.UnitID = startingBalance.UnitID;
            transactionOne.TransactionDate = DateTime.Now;

            Transaction transactionTwo = new Transaction();

            transactionTwo.PartitionID = 0;
            transactionTwo.LedgerID = Ledger.Constants.GOODS_ON_HAND_UNCOMMITED;
            transactionTwo.HubOwnerID = user.DefaultHub.HubOwnerID;
            transactionTwo.AccountID = repositoryAccountGetAccountIDWithCreatePosetive;
            transactionTwo.HubID = user.DefaultHub.HubID;
            transactionTwo.StoreID = startingBalance.StoreID;
            transactionTwo.Stack = startingBalance.StackNumber;
            transactionTwo.ProjectCodeID = repositoryProjectCodeGetProjectCodeIdWIthCreateProjectCodeID;
            transactionTwo.ShippingInstructionID = repositoryShippingInstructionGetSINumberIdWithCreateShippingInstructionID;
            transactionTwo.ProgramID = startingBalance.ProgramID;
            transactionTwo.ParentCommodityID = (comm.ParentID != null)
                                                       ? comm.ParentID.Value
                                                       : comm.CommodityID;
            transactionTwo.CommodityID = startingBalance.CommodityID;
            transactionTwo.CommodityGradeID = null; // How did I get this value ?
            transactionTwo.QuantityInMT = startingBalance.QuantityInMT;
            transactionTwo.QuantityInUnit = startingBalance.QuantityInUnit;
            transactionTwo.UnitID = startingBalance.UnitID;
            transactionTwo.TransactionDate = DateTime.Now;

            transactionGroup.PartitionID = 0;
            //transactionGroup.Transactions.Add(transactionOne);
            //transactionGroup.Transactions.Add(transactionTwo);
            //db.SaveChanges();
            // Try to save this transaction
            //db.Database.Connection.Open();
            //DbTransaction dbTransaction = db.Database.Connection.BeginTransaction();
            try
            {
                transactionGroup.Transactions.Add(transactionOne);
                transactionGroup.Transactions.Add(transactionTwo);
                _unitOfWork.TransactionGroupRepository.Add(transactionGroup);
                _unitOfWork.Save();
                //repository.TransactionGroup.Add(transactionGroup);
                //dbTransaction.Commit();
            }
            catch (Exception exp)
            {
                //dbTransaction.Rollback();
                //TODO: Save the detail of this exception somewhere
                throw new Exception("The Starting Balance Transaction Cannot be saved. <br />Detail Message :" + exp.Message);
            }
            //throw new NotImplementedException();
        }
    public void TestEndedEventWithSingleTransaction() {
      using(
        TransactionGroup<TestTransaction> testTransactionGroup =
          new TransactionGroup<TestTransaction>(
            new TestTransaction[] { new TestTransaction() }
          )
      ) {
        ITransactionGroupSubscriber mockedSubscriber = mockSubscriber(testTransactionGroup);

        Expect.Once.On(mockedSubscriber).
          Method("ProgressChanged").
          WithAnyArguments();

        Expect.Once.On(mockedSubscriber).
          Method("Ended").
          WithAnyArguments();

        testTransactionGroup.Children[0].Transaction.End();

        this.mockery.VerifyAllExpectationsHaveBeenMet();
      }
    }
示例#14
0
        public bool RunViewAnalysis(ProgressBar progressBar, TextBlock statusLable)
        {
            bool result = true;

            using (TransactionGroup tg = new TransactionGroup(m_doc))
            {
                tg.Start("Run View Analysis");
                try
                {
                    UpdateLableDelegate updateLabelDelegate = new UpdateLableDelegate(statusLable.SetValue);

                    List <int> keys         = roomDictionary.Keys.ToList();
                    int        finishedRoom = 0;
                    foreach (int roomId in keys)
                    {
                        if (AbortFlag.GetAbortFlag())
                        {
                            return(false);
                        }

                        using (Transaction trans = new Transaction(m_doc))
                        {
                            trans.Start("Find Visibility");
                            try
                            {
                                RoomData rData    = roomDictionary[roomId];
                                string   roomInfo = rData.RoomObj.Name + " (" + finishedRoom + " of " + keys.Count + ")";
                                Dispatcher.CurrentDispatcher.Invoke(updateLabelDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { TextBlock.TextProperty, roomInfo });
                                progressBar.Visibility = System.Windows.Visibility.Visible;

                                RoomData updatedData = null;
                                int      index       = dataCollection.AnalysisDataList.FindIndex(o => o.RoomId == rData.RoomId);
                                if (index == -1 || overwriteData)
                                {
                                    updatedData = FindVisibility(rData, progressBar);
                                }
                                else
                                {
                                    AnalysisData aData = dataCollection.AnalysisDataList[index];
                                    updatedData = FindVisibilityByPointData(rData, aData, progressBar);
                                }

                                if (null != updatedData)
                                {
                                    roomDictionary.Remove(roomId);
                                    roomDictionary.Add(roomId, updatedData);
                                }

                                finishedRoom++;
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                trans.RollBack();
                                result = false;
                                string message = ex.Message;
                            }
                        }
                    }

                    tg.Assimilate();
                }
                catch (Exception ex)
                {
                    result = false;
                    MessageBox.Show("Failed to run view analysis.\n" + ex.Message, "Run View Analysis", MessageBoxButton.OK, MessageBoxImage.Warning);
                    tg.RollBack();
                }
            }
            return(result);
        }
示例#15
0
        public static void Calculate(UIApplication uiApp)
        {
            Document   doc   = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            try
            {
                using (TransactionGroup txGp = new TransactionGroup(doc))
                {
                    txGp.Start("Calculate height of hangers");

                    //Collect elements
                    var hangerSupports = fi.GetElements <FamilyInstance, Guid>
                                             (doc, new Guid("e0baa750-22ba-4e60-9466-803137a0cba8"), "Hænger");
                    //Is the following required?
                    HashSet <Element> allHangers = new HashSet <Element>(hangerSupports.Cast <Element>()
                                                                         .Where(x => x.Category.Id.IntegerValue == (int)BuiltInCategory.OST_PipeAccessory));

                    //Prepare common objects for intersection analysis
                    //Create a filter that filters for structural columns and framing
                    //Why columns? Maybe only framing is enough.

                    //Linked IFC files create DirectShapes!
                    ElementClassFilter filter = new ElementClassFilter(typeof(DirectShape));

                    //IList<ElementFilter> filterList = new List<ElementFilter>
                    //                    { new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming),
                    //                      new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns) };
                    //LogicalOrFilter bicFilter = new LogicalOrFilter(filterList);
                    //LogicalAndFilter fiAndBicFilter = new LogicalAndFilter(bicFilter, new ElementClassFilter(typeof(FamilyInstance)));

                    //Get the default 3D view
                    var view3D = Shared.Filter.Get3DView(doc);
                    if (view3D == null)
                    {
                        throw new Exception("No default 3D view named {3D} is found!.");
                    }

                    //Instantiate the Reference Intersector
                    var refIntersect = new ReferenceIntersector(filter, FindReferenceTarget.Face, view3D);
                    refIntersect.FindReferencesInRevitLinks = true;

                    using (Transaction trans1 = new Transaction(doc))
                    {
                        trans1.Start("Calculate height to nearest framing");

                        foreach (Element hanger in allHangers)
                        {
                            //Find the point of the framing above the hanger
                            Transform trf    = ((FamilyInstance)hanger).GetTransform();
                            XYZ       Origin = new XYZ();
                            Origin = trf.OfPoint(Origin);
                            XYZ Direction = trf.BasisZ;
                            //XYZ Origin = ((LocationPoint)hanger.Location).Point;

                            ReferenceWithContext rwc = refIntersect.FindNearest(Origin, Direction);
                            if (rwc == null)
                            {
                                continue;
                            }
                            //throw new Exception($"Hanger {hanger.Id} did not find any steel supports!\n" +
                            //                    $"Check if elements are properly aligned.");
                            Reference reference    = rwc.GetReference();
                            XYZ       intersection = reference.GlobalPoint;

                            //Get the hanger's height above it's reference level
                            Parameter offsetPar     = hanger.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM);
                            double    offsetFromLvl = offsetPar.AsDouble();
                            //Just to make sure that the proper parameter is set
                            hanger.LookupParameter("PipeOffsetFromLevel").Set(offsetFromLvl);

                            //Calculate the height of the intersection above the reference level
                            ElementId refLvlId        = hanger.LevelId;
                            Level     refLvl          = (Level)doc.GetElement(refLvlId);
                            double    refLvlElevation = refLvl.Elevation;
                            double    profileHeight   = intersection.Z - refLvlElevation;

                            //Set the hanger value so it updates
                            hanger.LookupParameter("LevelHeight").Set(profileHeight);
                        }
                        trans1.Commit();
                    }
                    txGp.Assimilate();
                }
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                //return Result.Failed;
            }
        }
 public bool EditTransactionGroup(TransactionGroup entity)
 {
     _unitOfWork.TransactionGroupRepository.Edit(entity);
        _unitOfWork.Save();
        return true;
 }
        /// <summary>Проставить внешние размеры</summary>
        public void DoWork()
        {
            var doc = _uiApplication.ActiveUIDocument.Document;

            _cutPlanZ = GeometryHelpers.GetViewPlanCutPlaneElevation((ViewPlan)doc.ActiveView);

            // select
            var selectedElements = SelectElements();

            if (selectedElements == null)
            {
                return;
            }

            // get list of advanced elements
            foreach (var element in selectedElements)
            {
                switch (element)
                {
                case Wall wall:
                    var advancedWall = new AdvancedWall(wall);
                    if (advancedWall.IsDefined)
                    {
                        _advancedWalls.Add(advancedWall);
                    }
                    break;

                case Grid grid:
                    var advancedGrid = new AdvancedGrid(grid);
                    if (advancedGrid.IsDefined)
                    {
                        _advancedGrids.Add(advancedGrid);
                    }
                    break;
                }
            }

            if (!_advancedWalls.Any())
            {
                MessageBox.Show(Language.GetItem(LangItem, "msg7"), MessageBoxIcon.Close);
                return;
            }

            // Фильтрую стены по толщине
            AdvancedHelpers.FilterByWallWidth(_advancedWalls);
            if (!_advancedWalls.Any())
            {
                MessageBox.Show(Language.GetItem(LangItem, "msg8"), MessageBoxIcon.Close);
                return;
            }

            // Фильтрую стены, оставляя которые пересекаются секущим диапазоном
            AdvancedHelpers.FilterByCutPlan(_advancedWalls, _uiApplication.ActiveUIDocument.Document);

            // Вдруг после этого не осталось стен!
            if (!_advancedWalls.Any())
            {
                MessageBox.Show(Language.GetItem(LangItem, "msg9"), MessageBoxIcon.Close);
                return;
            }

            AdvancedHelpers.FindExtremes(_advancedWalls, doc, out var leftExtreme, out var rightExtreme, out var topextreme, out var bottomExtreme);

            using (var transactionGroup = new TransactionGroup(doc, _transactionName))
            {
                transactionGroup.Start();

                // create dimensions
                if (_exteriorConfiguration.RightDimensions)
                {
                    CreateSideDimensions(rightExtreme, _advancedWalls, ExtremeWallVariant.Right);
                }
                if (_exteriorConfiguration.LeftDimensions)
                {
                    CreateSideDimensions(leftExtreme, _advancedWalls, ExtremeWallVariant.Left);
                }
                if (_exteriorConfiguration.TopDimensions)
                {
                    CreateSideDimensions(topextreme, _advancedWalls, ExtremeWallVariant.Top);
                }
                if (_exteriorConfiguration.BottomDimensions)
                {
                    CreateSideDimensions(bottomExtreme, _advancedWalls, ExtremeWallVariant.Bottom);
                }

                transactionGroup.Assimilate();
            }
        }
示例#18
0
        private OrthogonalCamera GetOrthogonalCamera(Dictionary <int, ElementProperties> elementDictionary, string imagePath)
        {
            OrthogonalCamera orthoCamera = new OrthogonalCamera();

            try
            {
                BoundingBoxXYZ boundingBox = new BoundingBoxXYZ();
                boundingBox.Enabled = true;
                for (int i = 0; i < 3; i++)
                {
                    boundingBox.set_MinEnabled(i, true);
                    boundingBox.set_MaxEnabled(i, true);
                    boundingBox.set_BoundEnabled(0, i, true);
                    boundingBox.set_BoundEnabled(1, i, true);
                }

                BoundingBoxXYZ tempBoundingBox = elementDictionary.First().Value.RevitElement.get_BoundingBox(null);
                tempBoundingBox.Enabled = true;

                double maxX = tempBoundingBox.Max.X;
                double maxY = tempBoundingBox.Max.Y;
                double maxZ = tempBoundingBox.Max.Z;
                double minX = tempBoundingBox.Min.X;
                double minY = tempBoundingBox.Min.Y;
                double minZ = tempBoundingBox.Min.Z;

                List <ElementId>           elementIds = new List <ElementId>();
                Dictionary <int, Category> categories = new Dictionary <int, Category>();
                foreach (ElementProperties ep in elementDictionary.Values)
                {
                    Element element = ep.RevitElement;
                    if (null != element)
                    {
                        try
                        {
                            if (!categories.ContainsKey(element.Category.Id.IntegerValue))
                            {
                                categories.Add(element.Category.Id.IntegerValue, element.Category);
                            }
                            BoundingBoxXYZ bbBox = element.get_BoundingBox(null);
                            bbBox.Enabled = true;
                            elementIds.Add(element.Id);
                            if (null != boundingBox)
                            {
                                if (bbBox.Max.X > maxX)
                                {
                                    maxX = bbBox.Max.X;
                                }
                                if (bbBox.Max.Y > maxY)
                                {
                                    maxY = bbBox.Max.Y;
                                }
                                if (bbBox.Max.Z > maxZ)
                                {
                                    maxZ = bbBox.Max.Z;
                                }
                                if (bbBox.Min.X < minX)
                                {
                                    minX = bbBox.Min.X;
                                }
                                if (bbBox.Min.Y < minY)
                                {
                                    minY = bbBox.Min.Y;
                                }
                                if (bbBox.Min.Z < minZ)
                                {
                                    minZ = bbBox.Min.Z;
                                }
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }

                XYZ xyzMax = new XYZ(maxX, maxY, maxZ);
                XYZ xyzMin = new XYZ(minX, minY, minZ);

                boundingBox.set_Bounds(0, xyzMin);
                boundingBox.set_Bounds(1, xyzMax);


                ViewFamilyType           view3dFamilyType = null;
                FilteredElementCollector collector        = new FilteredElementCollector(m_doc);
                List <Element>           elements         = collector.OfClass(typeof(ViewFamilyType)).ToElements().ToList();
                foreach (Element element in elements)
                {
                    ViewFamilyType viewfamilytype = element as ViewFamilyType;
                    if (viewfamilytype.ViewFamily == ViewFamily.ThreeDimensional)
                    {
                        view3dFamilyType = viewfamilytype; break;
                    }
                }

                if (null != view3dFamilyType)
                {
                    using (TransactionGroup transGroup = new TransactionGroup(m_doc))
                    {
                        transGroup.Start("Start Creating View 3D");
                        using (Transaction trans = new Transaction(m_doc))
                        {
                            trans.Start("Create View");

                            View3D view3d = View3D.CreateIsometric(m_doc, view3dFamilyType.Id);
                            view3d.SetSectionBox(boundingBox);
                            view3d.GetSectionBox().Enabled = true;
                            view3d.DetailLevel = ViewDetailLevel.Fine;

                            foreach (Category category in categories.Values)
                            {
                                if (category.get_AllowsVisibilityControl(view3d))
                                {
#if RELEASE2017 || RELEASE2018
                                    view3d.SetCategoryHidden(category.Id, false);
#else
                                    view3d.SetVisibility(category, true);
#endif
                                }
                            }

                            view3d.get_Parameter(BuiltInParameter.MODEL_GRAPHICS_STYLE).Set(4);

                            //m_app.ActiveUIDocument.ActiveView = view3d;
                            //m_app.ActiveUIDocument.RefreshActiveView();

                            XYZ   eyePostion = view3d.GetOrientation().EyePosition;
                            Point viewPoint  = new Point();
                            viewPoint.X = eyePostion.X; viewPoint.Y = eyePostion.Y; viewPoint.Z = eyePostion.Z;
                            orthoCamera.CameraViewPoint = viewPoint;

                            XYZ       forwardDirection = view3d.GetOrientation().ForwardDirection;
                            Direction fDirection       = new Direction();
                            fDirection.X = forwardDirection.X; fDirection.Y = forwardDirection.Y; fDirection.Z = forwardDirection.Z;
                            orthoCamera.CameraDirection = fDirection;

                            XYZ       upDirection = view3d.GetOrientation().UpDirection;
                            Direction uDirection  = new Direction();
                            uDirection.X = upDirection.X; uDirection.Y = upDirection.Y; uDirection.Z = upDirection.Z;
                            orthoCamera.CameraUpVector = uDirection;

                            orthoCamera.ViewToWorldScale = view3d.Scale;
                            m_app.ActiveUIDocument.RefreshActiveView();
                            trans.Commit();

                            trans.Start("Export Image");
                            //create snapshot.png
                            ImageExportOptions option = new ImageExportOptions();
                            option.HLRandWFViewsFileType = ImageFileType.PNG;
                            option.ImageResolution       = ImageResolution.DPI_300;
                            option.ShouldCreateWebSite   = false;
                            option.ExportRange           = ExportRange.SetOfViews;
                            option.FilePath = imagePath;
                            List <ElementId> viewIds = new List <ElementId>();
                            viewIds.Add(view3d.Id);
                            option.SetViewsAndSheets(viewIds);

                            if (ImageExportOptions.IsValidFileName(option.FilePath))
                            {
                                m_doc.ExportImage(option);
                            }
                            trans.Commit();
                        }
                        transGroup.RollBack();
                    }

                    if (File.Exists(imagePath))
                    {
                        File.Delete(imagePath);
                    }
                    string[] fileNames = Directory.GetFiles(Path.GetDirectoryName(imagePath), "snapshot*");
                    foreach (string fName in fileNames)
                    {
                        if (Path.GetExtension(fName) == ".png" || Path.GetExtension(fName) == ".jpg")
                        {
                            File.Move(fName, imagePath);
                            if (File.Exists(fName))
                            {
                                File.Delete(fName);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get the orthogonal camera.\n" + ex.Message, "Get Orthogonal Camera", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(orthoCamera);
        }
示例#19
0
        public void Execute(UIApplication uiapp)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                FamilyInstance myFamilyInstance_Departure = doc.GetElement(new ElementId(myWindow1.myToolKit_IntUpDown.Value.Value)) as FamilyInstance;

                IList <ElementId> placePointIds_1338      = AdaptiveComponentInstanceUtils.GetInstancePointElementRefIds(myFamilyInstance_Departure);
                ReferencePoint    myReferencePoint_Centre = doc.GetElement(placePointIds_1338.First()) as ReferencePoint;

                Transform myTransform = myReferencePoint_Centre.GetCoordinateSystem();

                int    myIntTimeOut            = 0;
                int    myInt_ChangeCount       = 0;
                double myDouble_ChangePosition = -1;

                using (TransactionGroup transGroup = new TransactionGroup(doc))
                {
                    transGroup.Start("EE05_Move");

                    if (!myReferencePoint_Centre.get_Parameter(BuiltInParameter.POINT_ELEMENT_DRIVEN).IsReadOnly)
                    {
                        using (Transaction y = new Transaction(doc, "Remove Hosting"))
                        {
                            y.Start();
                            myReferencePoint_Centre.get_Parameter(BuiltInParameter.POINT_ELEMENT_DRIVEN).Set(0);
                            y.Commit();
                        }
                    }

                    while (myWindow1.mySlideInProgress)
                    {
                        wait(100); myIntTimeOut++;

                        if (myDouble_ChangePosition != myWindow1.mySlider.Value)
                        {
                            myDouble_ChangePosition = myWindow1.mySlider.Value;
                            myWindow1.myLabel_ChangeCount.Content = myInt_ChangeCount++.ToString();
                            using (Transaction y = new Transaction(doc, "a Transform"))
                            {
                                y.Start();

                                double myDoubleRotateAngle = myDouble_ChangePosition;

                                Transform myTransform_Temp = Transform.Identity;

                                myTransform_Temp.BasisX = myTransform.BasisX;
                                myTransform_Temp.BasisY = myTransform.BasisY;
                                myTransform_Temp.BasisZ = myTransform.BasisZ;

                                switch (myWindow1.mySlider.Name)
                                {
                                case "mySlider_Move_X":
                                    myTransform_Temp.Origin = myTransform.Origin + new XYZ(myDoubleRotateAngle, 0, 0);
                                    break;

                                case "mySlider_Move_Y":
                                    myTransform_Temp.Origin = myTransform.Origin + new XYZ(0, myDoubleRotateAngle, 0);
                                    break;

                                case "mySlider_Move_Z":
                                    myTransform_Temp.Origin = myTransform.Origin + new XYZ(0, 0, myDoubleRotateAngle);
                                    break;
                                }

                                myReferencePoint_Centre.SetCoordinateSystem(myTransform_Temp);

                                myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisZ, false);
                                myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisX, false);
                                myWindow1.setSlider(myWindow1.myIntUpDown_Middle2, myWindow1.mySlider_Rotate_BasisY, true);

                                y.Commit();
                            }
                        }

                        myWindow1.myLabel_Setting.Content = myWindow1.mySlider.Value.ToString();

                        if (myIntTimeOut == 400)
                        {
                            MessageBox.Show("Timeout");
                            break;
                        }
                    }

                    transGroup.Assimilate();
                }

                myWindow1.mySlider.Value = 0;
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("EE05_Move" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
示例#20
0
        public static Result Execute2(
            ExternalCommandData commandData,
            bool exportToSatFormat)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Application app = uiapp.Application;
              Document doc = uidoc.Document;

              if( null == doc )
              {
            ErrorMsg( "Please run this command in a valid"
              + " Revit project document." );
            return Result.Failed;
              }

              View view = doc.ActiveView;

              if( null == view || !( view is View3D ) )
              {
            ErrorMsg( "Please run this command in a valid"
              + " 3D view." );
            return Result.Failed;
              }

              if( PartsVisibility.ShowPartsOnly
            != view.PartsVisibility )
              {
            ErrorMsg( "Please run this command in a view"
              + " displaying parts and not source elements." );
            return Result.Failed;
              }

              // Define the list of views to export,
              // including only the current 3D view

              List<ElementId> viewIds = new List<ElementId>( 1 );

              viewIds.Add( view.Id );

              // Iterate over all pre-selected parts

              List<ElementId> ids = null;

              Selection sel = uidoc.Selection;
              ICollection<ElementId> selIds = sel.GetElementIds(); // 2015

              //if( 0 < sel.Elements.Size ) // 2014

              if( 0 < selIds.Count ) // 2015
              {
            //foreach( Element e in sel.Elements ) // 2014

            foreach( ElementId id in selIds ) // 2015
            {
              Element e = doc.GetElement( id );

              if( !( e is Part ) )
              {
            ErrorMsg( "Please pre-select only gyp wallboard"
              + " parts before running this command." );
            return Result.Failed;
              }

              Part part = e as Part;

              ICollection<LinkElementId> lids
            = part.GetSourceElementIds();

              if( 1 != lids.Count )
              {
            ErrorMsg( "Gyp wallboard part has multiple"
              + " source elements." );
            return Result.Failed;
              }

              LinkElementId lid = lids.First<LinkElementId>();
              ElementId hostId = lid.HostElementId;
              ElementId linkedId = lid.LinkedElementId;
              ElementId parentId = hostId;
              ElementId partId = e.Id;

              // Determine parent category

              Element parent = doc.GetElement( parentId );
              Category cat = parent.Category;

              ICollection<ElementId> cids
            = part.GetSourceElementOriginalCategoryIds();

              if( 1 != cids.Count )
              {
            ErrorMsg( "Gyp wallboard part has multiple"
              + " source element categories." );
            return Result.Failed;
              }

              ElementId cid = cids.First<ElementId>();

              //cat = doc.GetElement( id ) as Category;

              // Expected parent category is OST_Walls

              BuiltInCategory bic
            = (BuiltInCategory) cid.IntegerValue;

              if( BuiltInCategory.OST_Walls != bic )
              {
            ErrorMsg( "Please pre-select only "
              + " gyp wallboard parts." );

            return Result.Failed;
              }

              if( null == ids )
              {
            ids = new List<ElementId>( 1 );
              }

              ids.Add( partId );
            }

            if( null == ids )
            {
              ErrorMsg( "Please pre-select only gyp wallboard"
            + " parts before running this command." );
              return Result.Failed;
            }
              }

              // If no parts were pre-selected,
              // prompt for post-selection

              if( null == ids )
              {
            IList<Reference> refs = null;

            try
            {
              refs = sel.PickObjects( ObjectType.Element,
            new WallPartSelectionFilter(),
            "Please select wall parts." );
            }
            catch( Autodesk.Revit.Exceptions
              .OperationCanceledException )
            {
              return Result.Cancelled;
            }
            ids = new List<ElementId>(
              refs.Select<Reference, ElementId>(
            r => r.ElementId ) );
              }

              if( 0 == ids.Count )
              {
            ErrorMsg( "No valid parts selected." );

            return Result.Failed;
              }

              // Check for shared parameters
              // to record export history

              ExportParameters exportParameters
            = new ExportParameters(
              doc.GetElement( ids[0] ) );

              if( !exportParameters.IsValid )
              {
            ErrorMsg( "Please initialise the CNC fabrication "
              + "export history shared parameters before "
              + "launching this command." );

            return Result.Failed;
              }

              if( !Util.BrowseDirectory( ref _folder, true ) )
              {
            return Result.Cancelled;
              }

              try
              {
            // Register event handler for
            // "TaskDialog_Really_Print_Or_Export_Temp_View_Modes"
            // dialogue

            uiapp.DialogBoxShowing
              += new EventHandler<DialogBoxShowingEventArgs>(
            OnDialogBoxShowing );

            object opt = exportToSatFormat
              ? (object) new SATExportOptions()
              : (object) new DXFExportOptions();

            //opt.FileVersion = ACADVersion.R2000;

            string filename;

            using( TransactionGroup txg = new TransactionGroup( doc ) )
            {
              txg.Start( "Export Wall Parts" );

              foreach( ElementId id in ids )
              {
            Element e = doc.GetElement( id );

            Debug.Assert( e is Part,
              "expected parts only" );

            Part part = e as Part;

            ICollection<LinkElementId> lids
              = part.GetSourceElementIds();

            Debug.Assert( 1 == lids.Count,
              "unexpected multiple part source elements." );

            LinkElementId lid = lids.First<LinkElementId>();
            ElementId hostId = lid.HostElementId;
            ElementId linkedId = lid.LinkedElementId;
            ElementId parentId = hostId;
            ElementId partId = e.Id;

            filename = string.Format( "{0}_{1}",
              parentId, partId );

            Element host = doc.GetElement( hostId );

            Debug.Assert( null != host, "expected to be able to access host element" );
            //Debug.Assert( ( host is Wall ), "expected host element to be a wall" );
            Debug.Assert( ( host is Wall ) || ( host is Part ), "expected host element to be a wall or part" );
            Debug.Assert( null != host.Category, "expected host element to have a valid category" );
            //Debug.Assert( host.Category.Id.IntegerValue.Equals( (int) BuiltInCategory.OST_Walls ), "expected host element to have wall category" );
            Debug.Assert( host.Category.Id.IntegerValue.Equals( (int) BuiltInCategory.OST_Walls ) || host.Category.Id.IntegerValue.Equals( (int) BuiltInCategory.OST_Parts ), "expected host element to have wall or part category" );
            Debug.Assert( ElementId.InvalidElementId != host.LevelId, "expected host element to have a valid level id" );

            if( ElementId.InvalidElementId != host.LevelId )
            {
              Element level = doc.GetElement( host.LevelId );

              filename = level.Name.Replace( ' ', '_' )
                + "_" + filename;
            }

            if( view.IsTemporaryHideIsolateActive() )
            {
              using( Transaction tx = new Transaction( doc ) )
              {
                tx.Start( "Disable Temporary Isolate" );

                view.DisableTemporaryViewMode(
                  TemporaryViewMode.TemporaryHideIsolate );

                tx.Commit();
              }

              Debug.Assert( !view.IsTemporaryHideIsolateActive(),
                "expected to turn off temporary hide/isolate" );
            }

            using( Transaction tx = new Transaction( doc ) )
            {
              tx.Start( "Export Wall Part "
                + partId.ToString() );

              // This call requires a transaction.

              view.IsolateElementTemporary( partId );

              //List<ElementId> unhideIds = new List<ElementId>( 1 );
              //unhideIds.Add( partId );
              //view.UnhideElements( unhideIds );

              //doc.Regenerate(); // this is insufficient

              tx.Commit();
            }

            if( exportToSatFormat )
            {
              //ViewSet viewSet = new ViewSet();
              //
              //foreach( ElementId vid in viewIds )
              //{
              //  viewSet.Insert( doc.GetElement( vid )
              //    as View );
              //}
              //
              //doc.Export( _folder, filename, viewSet,
              //  (SATExportOptions) opt ); // 2013

              doc.Export( _folder, filename, viewIds,
                (SATExportOptions) opt ); // 2014
            }
            else
            {
              doc.Export( _folder, filename, viewIds,
                (DXFExportOptions) opt );
            }

            // Update CNC fabrication
            // export shared parameters -- oops,
            // cannot do this immediately, since
            // this transaction group will be
            // rolled back ... just save the
            // element id and do it later
            // searately.

            //exportParameters.UpdateExportHistory( e );
            exportParameters.Add( e.Id );
              }

              // We do not commit the transaction group,
              // because no modifications should be saved.
              // The transaction group is only created and
              // started to encapsulate the transactions
              // required by the IsolateElementTemporary
              // method. Since the transaction group is not
              // committed, the changes are automatically
              // discarded.

              //txg.Commit();
            }
              }
              finally
              {
            uiapp.DialogBoxShowing
              -= new EventHandler<DialogBoxShowingEventArgs>(
            OnDialogBoxShowing );
              }

              using( Transaction tx = new Transaction( doc ) )
              {
            tx.Start( "Update CNC Fabrication Export "
              + "History Shared Parameters" );

            exportParameters.UpdateExportHistory();

            tx.Commit();
              }
              return Result.Succeeded;
        }
示例#21
0
        private bool CreateMaterials(List <MaterialFromExcel> materialstoCreate, out List <ElementId> createdMaterialIds)
        {
            createdMaterialIds = new List <ElementId>();
            bool created = false;

            try{
                using (TransactionGroup tg = new TransactionGroup(m_doc))
                {
                    tg.Start("Create Materials");
                    foreach (MaterialFromExcel mExcel in materialstoCreate)
                    {
                        if (Material.IsNameUnique(m_doc, mExcel.ReferenceValue))
                        {
                            using (Transaction trans = new Transaction(m_doc))
                            {
                                trans.Start("Create Material");
                                try{
                                    //ElementId materialId = Material.Create(m_doc, mExcel.NameValue);
                                    ElementId materialId      = Material.Create(m_doc, mExcel.ReferenceValue);
                                    Material  createdMaterial = m_doc.GetElement(materialId) as Material;
                                    if (null != createdMaterial)
                                    {
                                        Parameter param = createdMaterial.LookupParameter("Mark");
                                        if (null != param)
                                        {
                                            param.Set(mExcel.ReferenceValue);
                                        }

                                        param = createdMaterial.LookupParameter("Description");
                                        if (null != param)
                                        {
                                            param.Set(mExcel.NameValue);
                                        }

                                        param = createdMaterial.LookupParameter("Keynote");
                                        if (null != param)
                                        {
                                            param.Set(mExcel.SubGroup);
                                        }
                                    }

                                    createdMaterialIds.Add(materialId);
                                    trans.Commit();
                                }
                                catch (Exception ex)
                                {
                                    string message = ex.Message;
                                    trans.RollBack();
                                }
                            }
                        }
                    }

                    tg.Assimilate();
                }
                created = true;
            }
            catch (Exception ex)
            {
                created = false;
                MessageBox.Show("Failed to create materials.\n" + ex.Message, "Create Materials", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return(created);
        }
 public void TestAlreadyEndedTransactionAsFirstTransaction() {
   using(
     TransactionGroup<Transaction> testTransactionGroup =
       new TransactionGroup<Transaction>(
         new Transaction[] { Transaction.EndedDummy, new TestTransaction() }
       )
   ) {
     Assert.IsFalse(testTransactionGroup.Ended);
   }
 }
示例#23
0
        private bool UpdateMaterials(List <RevitMaterial> materialsToUpdate, out List <ElementId> updatedMaterialIds)
        {
            bool updated;

            updatedMaterialIds = new List <ElementId>();
            try{
                using (TransactionGroup tg = new TransactionGroup(m_doc))
                {
                    tg.Start("Update Materials");
                    foreach (RevitMaterial rm in materialsToUpdate)
                    {
                        using (Transaction trans = new Transaction(m_doc))
                        {
                            trans.Start("Update Material");
                            try{
                                Material material = m_doc.GetElement(rm.MaterialId) as Material;
                                if (null != material)
                                {
                                    MaterialFromExcel mExcel = rm.MatchedMaterial;
                                    //update name
                                    if (rm.MaterialName != mExcel.ReferenceValue)
                                    {
                                        if (Material.IsNameUnique(m_doc, mExcel.ReferenceValue))
                                        {
                                            //material.Name = mExcel.NameValue;
                                            material.Name = mExcel.ReferenceValue;
                                        }
                                    }
                                    //update description
                                    if (rm.Description != mExcel.NameValue)
                                    {
                                        Parameter param = material.LookupParameter("Description");
                                        if (null != param)
                                        {
                                            param.Set(mExcel.NameValue);
                                        }
                                    }
                                    //update keynote
                                    if (rm.KeynoteValue != mExcel.SubGroup)
                                    {
                                        Parameter param = material.LookupParameter("Keynote");
                                        if (null != param)
                                        {
                                            param.Set(mExcel.SubGroup);
                                        }
                                    }
                                    updatedMaterialIds.Add(material.Id);
                                }
                                trans.Commit();
                            }
                            catch (Exception ex)
                            {
                                string message = ex.Message;
                                trans.RollBack();
                            }
                        }
                    }
                    tg.Assimilate();
                }
                updated = true;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                updated = false;
            }
            return(updated);
        }
        /// <summary>
        /// </summary>
        /// <param name="viewModel"></param>
        /// <param name="user"></param>
        /// <exception cref="System.Exception"></exception>
        public void SaveInternalMovementTrasnsaction(InternalMovementViewModel viewModel, UserProfile user)
        {
            InternalMovement internalMovement = new InternalMovement();
            TransactionGroup transactionGroup = new TransactionGroup();
            Transaction transactionFromStore = new Transaction();

            Commodity commodity = _unitOfWork.CommodityRepository.FindById(viewModel.CommodityId);

            //transaction.TransactionGroupID = transactionGroupId;
            transactionFromStore.LedgerID = 2;
            transactionFromStore.HubOwnerID = user.DefaultHub.HubOwner.HubOwnerID;
            //trasaction.AccountID
            transactionFromStore.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, user.DefaultHub.HubID); //
            transactionFromStore.HubID = user.DefaultHub.HubID;
            transactionFromStore.StoreID = viewModel.FromStoreId;  //
            transactionFromStore.Stack = viewModel.FromStackId; //
            transactionFromStore.ProjectCodeID = viewModel.ProjectCodeId;
            transactionFromStore.ShippingInstructionID = viewModel.ShippingInstructionId;
            transactionFromStore.ProgramID = viewModel.ProgramId;
            transactionFromStore.ParentCommodityID = (commodity.ParentID == null)
                                                       ? commodity.CommodityID
                                                       : commodity.ParentID.Value;
            transactionFromStore.CommodityID = viewModel.CommodityId;
            transactionFromStore.CommodityGradeID = null; // How did I get this value ?
            transactionFromStore.QuantityInMT = 0 - viewModel.QuantityInMt;
            transactionFromStore.QuantityInUnit = 0 - viewModel.QuantityInUnit;
            transactionFromStore.UnitID = viewModel.UnitId;
            transactionFromStore.TransactionDate = DateTime.Now;

            Transaction transactionToStore = new Transaction();

            //transactionToStore.TransactionGroupID = transactionGroupId;
            transactionToStore.LedgerID = 2;
            transactionToStore.HubOwnerID = user.DefaultHub.HubOwner.HubOwnerID;
            //transactionToStore.AccountID
            transactionToStore.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, user.DefaultHub.HubID); //
            transactionToStore.HubID = user.DefaultHub.HubID;
            transactionToStore.StoreID = viewModel.ToStoreId;  //
            transactionToStore.Stack = viewModel.ToStackId; //
            transactionToStore.ProjectCodeID = viewModel.ProjectCodeId;
            transactionToStore.ShippingInstructionID = viewModel.ShippingInstructionId;
            transactionToStore.ProgramID = viewModel.ProgramId;

            transactionToStore.ParentCommodityID = (commodity.ParentID == null)
                                                       ? commodity.CommodityID
                                                       : commodity.ParentID.Value;
            transactionToStore.CommodityID = viewModel.CommodityId;
            transactionToStore.CommodityGradeID = null; // How did I get this value ?
            transactionToStore.QuantityInMT = viewModel.QuantityInMt;
            transactionToStore.QuantityInUnit = viewModel.QuantityInUnit;
            transactionToStore.UnitID = viewModel.UnitId;
            transactionToStore.TransactionDate = DateTime.Now;

            transactionGroup.Transactions.Add(transactionFromStore);
            transactionGroup.Transactions.Add(transactionToStore);
            transactionGroup.PartitionID = 0;

            internalMovement.PartitionID = 0;
            internalMovement.TransactionGroup = transactionGroup;
            internalMovement.TransferDate = viewModel.SelectedDate;
            internalMovement.DReason = viewModel.ReasonId;
            internalMovement.Notes = viewModel.Note;
            internalMovement.ApprovedBy = viewModel.ApprovedBy;
            internalMovement.ReferenceNumber = viewModel.ReferenceNumber;

            // Try to save this transaction
            //db.Database.Connection.Open();
            //DbTransaction dbTransaction = db.Database.Connection.BeginTransaction();
            try
            {
                _unitOfWork.InternalMovementRepository.Add(internalMovement);
                _unitOfWork.Save();
             //   repository.InternalMovement.Add(internalMovement);
               // dbTransaction.Commit();
            }
            catch (Exception exp)
            {
                //dbTransaction.Rollback();
                //TODO: Save the detail of this exception somewhere
                throw new Exception("The Internal Movement Transaction Cannot be saved. <br />Detail Message :" + exp.Message);
            }
        }
示例#25
0
        /// <summary>
        /// Moves a subregion and the associated topography to a new user-selected location.
        /// </summary>
        /// <param name="uiDoc">The document.</param>
        private void MoveSubregionAndPoints(UIDocument uiDoc)
        {
            Document doc = uiDoc.Document;

            // Pick subregion
            TopographySurface subregion   = SiteUIUtils.PickSubregion(uiDoc);
            TopographySurface toposurface = SiteEditingUtils.GetTopographySurfaceHost(subregion);
            IList <XYZ>       points      = SiteEditingUtils.GetPointsFromSubregionExact(subregion);
            XYZ sourceLocation            = SiteEditingUtils.GetCenterOf(subregion);

            // Pick target location
            XYZ targetPoint = SiteUIUtils.PickPointNearToposurface(uiDoc, toposurface, "Pick point to move to");

            // Delta for the move
            XYZ delta = targetPoint - sourceLocation;

            // All changes are added to one transaction group - will create one undo item
            using (TransactionGroup moveGroup = new TransactionGroup(doc, "Move subregion and points"))
            {
                moveGroup.Start();

                // Get elevation of region in current location
                IList <XYZ> existingPointsInCurrentLocation = subregion.GetPoints();

                double existingElevation = SiteEditingUtils.GetAverageElevation(existingPointsInCurrentLocation);

                // Move subregion first - allows the command delete existing points and adjust elevation to surroundings
                using (Transaction t2 = new Transaction(doc, "Move subregion"))
                {
                    t2.Start();
                    ElementTransformUtils.MoveElement(doc, subregion.Id, delta);
                    t2.Commit();
                }

                // The boundary points for the subregion cannot be deleted, since they are generated
                // to represent the subregion boundary rather than representing real points in the host.
                // Get non-boundary points only to be deleted.
                IList <XYZ> existingPointsInNewLocation = SiteEditingUtils.GetNonBoundaryPoints(subregion);

                // Average elevation of all points in the subregion.
                double newElevation = SiteEditingUtils.GetAverageElevation(subregion.GetPoints());

                // Adjust delta for elevation based on calculated values
                delta = SiteEditingUtils.MoveXYZToElevation(delta, newElevation - existingElevation);

                // Edit scope for points changes
                using (TopographyEditScope editScope = new TopographyEditScope(doc, "Edit TS"))
                {
                    editScope.Start(toposurface.Id);

                    using (Transaction t = new Transaction(doc, "Move points"))
                    {
                        t.Start();
                        // Delete existing points from target region
                        if (existingPointsInNewLocation.Count > 0)
                        {
                            toposurface.DeletePoints(existingPointsInNewLocation);
                        }

                        // Move points from source region
                        toposurface.MovePoints(points, delta);
                        t.Commit();
                    }

                    editScope.Commit(new TopographyEditFailuresPreprocessor());
                }

                moveGroup.Assimilate();
            }
        }
示例#26
0
        private void buttonUpdateParameters_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (massConfig.UpdateType != ParameterUpdateType.None && massConfig.MassParameters.Count > 0)
                {
                    List <RoomProperties> roomList = (List <RoomProperties>)dataGridRoom.ItemsSource;
                    var selectedRooms = from room in roomList where room.IsSelected select room;

                    if (selectedRooms.Count() > 0)
                    {
                        statusLable.Text       = "Updating Parameters ...";
                        progressBar.Visibility = System.Windows.Visibility.Visible;
                        progressBar.Value      = 0;
                        progressBar.Maximum    = selectedRooms.Count();

                        UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);
                        using (TransactionGroup tg = new TransactionGroup(m_doc))
                        {
                            tg.Start("Update Parameters");
                            try
                            {
                                double count = 0;
                                foreach (RoomProperties rp in selectedRooms)
                                {
                                    using (Transaction trans = new Transaction(m_doc))
                                    {
                                        trans.Start("Update Parameter");
                                        var options = trans.GetFailureHandlingOptions();
                                        options.SetFailuresPreprocessor(new DuplicateWarningSwallower());
                                        trans.SetFailureHandlingOptions(options);

                                        try
                                        {
                                            bool updated = false;
                                            if (null != rp.Linked2dMass)
                                            {
                                                updated = UpdateParameter(rp.RoomElement, rp.Linked2dMass.MassElement);
                                            }
                                            if (null != rp.Linked3dMass)
                                            {
                                                updated = UpdateParameter(rp.RoomElement, rp.Linked3dMass.MassElement);
                                            }

                                            if (updated)
                                            {
                                                RoomProperties updatedRoom = new RoomProperties(rp);
                                                updatedRoom.IsSelected = false;
                                                roomDictionary.Remove(rp.RoomUniqueId);
                                                roomDictionary.Add(rp.RoomUniqueId, updatedRoom);
                                            }
                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            trans.RollBack();
                                            string message = ex.Message;
                                        }
                                    }

                                    count++;
                                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, count });
                                }

                                DisplayRoomInfo();
                                tg.Assimilate();
                            }
                            catch (Exception ex)
                            {
                                tg.RollBack();
                                MessageBox.Show("Failed to update parameters of linked masses.\n" + ex.Message, "Update Parameters", MessageBoxButton.OK, MessageBoxImage.Warning);
                            }
                        }

                        progressBar.Visibility = System.Windows.Visibility.Hidden;
                        statusLable.Text       = "Ready";
                    }
                }
                else
                {
                    MessageBox.Show("Please set the configuration for the parameter mappings.\nGo to the Parameters Settings button for more detail.", "Parameters Settings Missing", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to update parameter values.\n" + ex.Message, "Update Parameters", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
示例#27
0
        public KeyValuePair <List <ElementId>, List <double> > TravelDis(Document doc, ICollection <ElementId> selectedIds, List <ElementId> RoomsForbid) //distances of all rooms on current level to nearest exit
        {
            View currentView = doc.ActiveView;

            //door location
            var doors = new List <ElementId>();

            doors = GetExits(doc);
            var doors_loc = new List <XYZ>();

            foreach (ElementId id in doors)
            {
                Element       door = doc.GetElement(id);
                LocationPoint loc  = door.Location as LocationPoint;
                XYZ           xyz  = loc.Point;
                doors_loc.Add(xyz);
            }
            //room location
            var levelid   = ViewLevel(doc);
            var rooms     = GetRoomsOnLevel(doc, levelid);
            var final_rel = new List <double>();
            var rooms_loc = CenterOfRoom(doc, rooms);

            //TaskDialog.Show("Revit", doors_loc.Count.ToString());
            //TaskDialog.Show("Revit", rooms_loc.Count.ToString());
            var Exit2Door = new List <XYZ>();

            using (TransactionGroup transGroup = new TransactionGroup(doc))
            {
                transGroup.Start("group start");
                using (Transaction trans_del = new Transaction(doc))
                {
                    trans_del.Start("Del");
                    foreach (ElementId id in RoomsForbid)
                    {
                        Element temp = doc.GetElement(id);
                        DeleteDoorsOfRoom(doc, id);
                    }
                    trans_del.Commit();
                }
                using (Transaction trans = new Transaction(doc))
                {
                    if (trans.Start("Path") == TransactionStatus.Started)
                    {
                        //PathOfTravel.CreateMapped(currentView, rooms_loc, doors_loc);

                        //try to find the shortest path to the exits(one of)
                        //var ig = new List<ElementId>();
                        var settings = RouteAnalysisSettings.GetRouteAnalysisSettings(doc);
                        //foreach (ElementId id in selectedIds)
                        //{
                        //    Element temp = doc.GetElement(id);
                        //    ig.Add(temp.Category.Id);
                        //}
                        settings.SetIgnoredCategoryIds(selectedIds);
                        foreach (XYZ r in rooms_loc)
                        {
                            double temp_len = 10000000;
                            XYZ    temp_loc = null;
                            int    cnt      = 0;
                            foreach (XYZ d in doors_loc)
                            {
                                PathOfTravel path = PathOfTravel.Create(currentView, r, d);
                                if (path == null)
                                {
                                    continue;
                                }
                                IList <Curve> p = path.GetCurves();
                                if (temp_len >= calDis(p))
                                {
                                    temp_loc = d;
                                    temp_len = calDis(p);
                                }
                            }
                            Exit2Door.Add(temp_loc);
                        }
                        trans.RollBack();

                        //TaskDialog taskdialog = new TaskDialog("Revit");
                        //taskdialog.MainContent = "Click [OK] to commot and click [cancel] to roll back";
                        //TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel;
                        //taskdialog.CommonButtons = buttons;
                        //if (TaskDialogResult.Ok == taskdialog.Show())
                        //{
                        //    if (TransactionStatus.Committed != trans.Commit()) {
                        //        TaskDialog.Show("Fail", "Trans can not be committed");
                        //    }
                        //}
                        //else {
                        //    trans.RollBack();
                        //}
                    }
                }

                var RoomsPoint = rooms_loc;

                using (Transaction trans2 = new Transaction(doc))
                {
                    if (trans2.Start("Path_final") == TransactionStatus.Started)
                    {
                        var settings = RouteAnalysisSettings.GetRouteAnalysisSettings(doc);

                        settings.SetIgnoredCategoryIds(selectedIds);
                        for (int i = 0; i < RoomsPoint.Count; i++)
                        {
                            XYZ    d         = Exit2Door[i];
                            XYZ    r         = RoomsPoint[i];
                            Room   temp_room = doc.GetRoomAtPoint(r);
                            double halfDia   = calHalfDia(temp_room);
                            if (r == null || d == null)
                            {
                                final_rel.Add(MAX_NUM);
                                continue;
                            }
                            ;
                            IList <Curve> path = PathOfTravel.Create(currentView, r, d).GetCurves();
                            final_rel.Add(calDis(path));
                        }
                        trans2.Commit();
                    }
                }
                transGroup.Assimilate();
            }
            var allRoomName = new List <ElementId>();

            foreach (Room r in rooms)
            {
                allRoomName.Add(r.Id);
            }
            return(new KeyValuePair <List <ElementId>, List <double> >(allRoomName, final_rel));
        }
示例#28
0
        private List <MonitorMessage> VerifyDoorParameters(MonitorProjectSetup projectSetup)
        {
            List <MonitorMessage> warningMessages = new List <MonitorMessage>();

            try
            {
                using (TransactionGroup transGroup = new TransactionGroup(m_doc))
                {
                    transGroup.Start("Verify Doors");
                    ElementFilter            catFilter     = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
                    FilteredElementCollector collector     = new FilteredElementCollector(m_doc);
                    List <FamilyInstance>    doorInstances = collector.WherePasses(catFilter).WhereElementIsNotElementType().Cast <FamilyInstance>().ToList();

                    foreach (FamilyInstance doorInstance in doorInstances)
                    {
#if RELEASE2013 || RELEASE2014
                        Parameter pullParam = doorInstance.get_Parameter(pullParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter pullParam = doorInstance.LookupParameter(pullParamName);
#endif
                        if (null != pullParam)
                        {
                            string pullValue = pullParam.AsValueString();
                            if (!pullValue.Contains("Approach"))
                            {
                                MonitorMessage message = new MonitorMessage(doorInstance, pullParamName, "Incorrect parameter value has been set.");
                                warningMessages.Add(message);
                            }
                        }


#if RELEASE2013 || RELEASE2014
                        Parameter pushParam = doorInstance.get_Parameter(pushParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter pushParam = doorInstance.LookupParameter(pushParamName);
#endif
                        if (null != pushParam)
                        {
                            string pushValue = pushParam.AsValueString();
                            if (!pushValue.Contains("Approach"))
                            {
                                MonitorMessage message = new MonitorMessage(doorInstance, pushParamName, "Incorrect parameter value has been set.");
                                warningMessages.Add(message);
                            }
                        }

#if RELEASE2013 || RELEASE2014
                        Parameter caParam = doorInstance.get_Parameter(stateCAParamName);
#elif RELEASE2015 || RELEASE2016 || RELEASE2017
                        Parameter caParam = doorInstance.LookupParameter(stateCAParamName);
#endif
                        if (null != caParam)
                        {
                            int caVal      = caParam.AsInteger();
                            int projectVal = Convert.ToInt32(projectSetup.IsStateCA);
                            if (caVal != projectVal)
                            {
                                using (Transaction trans = new Transaction(m_doc))
                                {
                                    trans.Start("Set State Param");
                                    try
                                    {
                                        caParam.Set(projectVal);
                                        MonitorMessage message = new MonitorMessage(doorInstance, stateCAParamName, "Parameter Value has been changed. (solved) ");
                                        warningMessages.Add(message);
                                        trans.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        string message = ex.Message;
                                        trans.RollBack();
                                    }
                                }
                            }
                        }
                    }
                    transGroup.Assimilate();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to verify door parameters.\n" + ex.Message, "Verify Door Parameters", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(warningMessages);
        }
        private static void CropView(View view, PickedBox pickedBox, Document doc, string trName)
        {
            var cropRegionShapeManager = view.GetCropRegionShapeManager();

            var pt1   = pickedBox.Min;
            var pt3   = pickedBox.Max;
            var plane = CreatePlane(view.UpDirection, pt3);
            var pt2   = plane.ProjectOnto(pt1);

            plane = CreatePlane(view.UpDirection, pt1);
            var pt4 = plane.ProjectOnto(pt3);

            var line1 = TryCreateLine(pt1, pt2);
            var line2 = TryCreateLine(pt2, pt3);
            var line3 = TryCreateLine(pt3, pt4);
            var line4 = TryCreateLine(pt4, pt1);

            if (line1 == null || line2 == null || line3 == null || line4 == null)
            {
                // Не удалось получить валидную прямоугольную область. Попробуйте еще раз
                MessageBox.Show(Language.GetItem("h6"));
                return;
            }

            var curveLoop = CurveLoop.Create(new List <Curve>
            {
                line1, line2, line3, line4
            });

            if (curveLoop.IsRectangular(CreatePlane(view.ViewDirection, view.Origin)))
            {
                using (var transactionGroup = new TransactionGroup(doc))
                {
                    transactionGroup.Start();

                    using (var tr = new Transaction(doc, trName))
                    {
                        tr.Start();
                        if (!view.CropBoxActive)
                        {
                            view.CropBoxActive  = true;
                            view.CropBoxVisible = false;
                        }

                        cropRegionShapeManager.SetCropShape(curveLoop);

                        tr.Commit();
                    }

                    // reset crop
                    using (var tr = new Transaction(doc, trName))
                    {
                        tr.Start();

                        cropRegionShapeManager.RemoveCropRegionShape();

                        tr.Commit();
                    }

                    transactionGroup.Assimilate();
                }
            }
            else
            {
                // Не удалось получить валидную прямоугольную область. Попробуйте еще раз
                MessageBox.Show(Language.GetItem("h6"));
            }
        }
示例#30
0
 public bool EditTransactionGroup(TransactionGroup entity)
 {
     _unitOfWork.TransactionGroupRepository.Edit(entity);
     _unitOfWork.Save();
     return(true);
 }
        public void QTO_2_PlaceHoldersFromDWFMarkups(
            Document doc,
            string activityId)
        {
            View activeView = doc.ActiveView;

              if( !( activeView is ViewSheet ) )
              {
            TaskDialog.Show( "QTO",
              "The current view must be a Sheet View with DWF markups" );
            return;
              }

              ViewSheet vs = activeView as ViewSheet;

              Viewport vp = doc.GetElement(
            vs.GetAllViewports().First() ) as Viewport;

              View plan = doc.GetElement( vp.ViewId ) as View;

              int scale = vp.Parameters.Cast<Parameter>()
            .First( x => x.Id.IntegerValue.Equals(
              (int) BuiltInParameter.VIEW_SCALE ) )
            .AsInteger();

              IEnumerable<Element> dwfMarkups
            = new FilteredElementCollector( doc )
              .OfClass( typeof( ImportInstance ) )
              .WhereElementIsNotElementType()
              .Where( x => x.Name.StartsWith( "Markup" )
            && x.OwnerViewId.IntegerValue.Equals(
              activeView.Id.IntegerValue ) );

              using( TransactionGroup tg = new TransactionGroup( doc ) )
              {
            tg.Start( "DWF markups placeholders" );

            using( Transaction t = new Transaction( doc ) )
            {
              t.Start( "DWF Transfer" );

              plan.Parameters.Cast<Parameter>()
            .First( x => x.Id.IntegerValue.Equals(
              (int) BuiltInParameter.VIEWER_CROP_REGION ) )
            .Set( 1 );

              XYZ VC = ( plan.CropBox.Min + plan.CropBox.Max ) / 2;

              XYZ BC = vp.GetBoxCenter();

              t.RollBack();

              foreach( Element e in dwfMarkups )
              {
            GeometryElement GeoElem = e.get_Geometry( new Options() );

            GeometryInstance gi = GeoElem.Cast<GeometryInstance>().First();

            GeometryElement gei = gi.GetSymbolGeometry();

            IList<GeometryObject> gos = new List<GeometryObject>();

            if( gei.Cast<GeometryObject>().Count( x => x is Arc ) > 0 )
            {
              continue;
            }

            foreach( GeometryObject go in gei )
            {
              XYZ med = new XYZ();

              if( go is PolyLine )
              {
                PolyLine pl = go as PolyLine;

                XYZ min = new XYZ( pl.GetCoordinates().Min( p => p.X ),
                                pl.GetCoordinates().Min( p => p.Y ),
                                pl.GetCoordinates().Min( p => p.Z ) );

                XYZ max = new XYZ( pl.GetCoordinates().Max( p => p.X ),
                                pl.GetCoordinates().Max( p => p.Y ),
                                pl.GetCoordinates().Max( p => p.Z ) );

                med = ( min + max ) / 2;
              }

              med = med - BC;

              // Convert DWF sheet coordinates into model coordinates

              XYZ a = VC + new XYZ( med.X * scale, med.Y * scale, 0 );
            }
              }

              t.Start( "DWF Transfer" );

              foreach( Element e in dwfMarkups )
              {
            GeometryElement GeoElem = e.get_Geometry( new Options() );

            GeometryInstance gi = GeoElem.Cast<GeometryInstance>().First();

            GeometryElement gei = gi.GetSymbolGeometry();

            IList<GeometryObject> gos = new List<GeometryObject>();

            if( gei.Cast<GeometryObject>().Count( x => x is Arc ) == 0 )
            {
              continue;
            }

            foreach( GeometryObject go in gei )
            {
              if( go is Arc )
              {
                Curve c = go as Curve;

                XYZ med = c.Evaluate( 0.5, true );

                med = med - BC;

                XYZ a = VC + new XYZ( med.X * scale, med.Y * scale, 0 );

                // Warning CS0618:
                // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote(
                //   View, XYZ, XYZ, XYZ, double, TextAlignFlags, string)
                // is obsolete:
                // This method is deprecated in Revit 2016.
                // Please use one of the TextNote.Create methods instead.

                //doc.Create.NewTextNote( plan,
                //                       a,
                //                       XYZ.BasisX,
                //                       XYZ.BasisY,
                //                       MMtoFeet( 5 ),
                //                       TextAlignFlags.TEF_ALIGN_CENTER,
                //                       activityId );

                ElementId textTypeId = new FilteredElementCollector( doc )
                  .OfClass( typeof( TextNoteType ) )
                  .FirstElementId();

                TextNote.Create( doc, plan.Id, a, activityId, textTypeId );
              }
            }

            t.Commit();
              }
            }

            tg.Assimilate();
              }
        }
示例#32
0
        const double labelTextOffset      = 0.005;   // 5mm, defined in paper space
        #endregion

        #region InterfaceImplementation
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                Document document           = commandData.Application.ActiveUIDocument.Document;
                Autodesk.Revit.DB.View view = commandData.View;

                // find major and minor station arrow styles
                FilteredElementCollector fec            = new FilteredElementCollector(document);
                Element majorStationLeaderArrowheadType = fec.OfClass(typeof(ElementType))
                                                          .Cast <ElementType>()
                                                          .FirstOrDefault(x => x.Name.Contains(majorStationLeaderArrowheadName));
                Element minorStationLeaderArrowheadType = fec.OfClass(typeof(ElementType))
                                                          .Cast <ElementType>()
                                                          .FirstOrDefault(x => x.Name.Contains(minorStationLeaderArrowheadName));
                if (majorStationLeaderArrowheadType == null || minorStationLeaderArrowheadType == null)
                {
                    TaskDialog td = new TaskDialog("Missing arrowheads");
                    td.MainContent = "In Manage>Additional Settings>Arrowheads, create two styles of arrowheads, named\r\n" +
                                     "Major Station Arrowhead and Minor Station Arrowhead";
                    td.Show();

                    return(Result.Failed);
                }

                // find major and minor station label types; if not there, create them
                SpotDimensionType majorLabelType = fec.OfClass(typeof(SpotDimensionType))
                                                   .Cast <SpotDimensionType>()
                                                   .FirstOrDefault(sdt => sdt.StyleType == DimensionStyleType.AlignmentStationLabel && sdt.Name.Contains(majorStationSetLabelTypeName));

                SpotDimensionType minorLabelType = fec.OfClass(typeof(SpotDimensionType))
                                                   .Cast <SpotDimensionType>()
                                                   .FirstOrDefault(sdt => sdt.StyleType == DimensionStyleType.AlignmentStationLabel && sdt.Name.Contains(minorStationSetLabelTypeName));

                SpotDimensionType curvatureLabelType = fec.OfClass(typeof(SpotDimensionType))
                                                       .Cast <SpotDimensionType>()
                                                       .FirstOrDefault(sdt => sdt.StyleType == DimensionStyleType.AlignmentStationLabel && sdt.Name.Contains(horizontalCurvatureChangeLabelTypeName));

                using (Transaction t = new Transaction(document, "Create major station labels"))
                {
                    t.Start();
                    if (majorLabelType == null)
                    {
                        // create major station label type with the given arrowhead style
                        majorLabelType = document.GetElement(AlignmentStationLabel.CreateRecommendedTypeForSet(document)) as SpotDimensionType;
                        majorLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_LEADER_ARROWHEAD).Set(majorStationLeaderArrowheadType.Id);
                        majorLabelType.Name = majorStationSetLabelTypeName;
                    }

                    if (minorLabelType == null)
                    {
                        // create minor station label type with the given arrowhead style
                        // exclude the station text, which leave only the arrowheads
                        // make the minor station's color grey
                        // make the text 60% of the original value, in case text is later turned on
                        minorLabelType = document.GetElement(AlignmentStationLabel.CreateRecommendedTypeForSet(document)) as SpotDimensionType;
                        minorLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_LEADER_ARROWHEAD).Set(minorStationLeaderArrowheadType.Id);
                        minorLabelType.get_Parameter(BuiltInParameter.ALIGNMENT_STATION_LABEL_INCLUDE_STATION).Set(0);
                        minorLabelType.get_Parameter(BuiltInParameter.LINE_COLOR).Set(8421504 /* 127*2^0 + 127*2^8 + 127*2^16: grey */);
                        Parameter textSizeParam = minorLabelType.get_Parameter(BuiltInParameter.TEXT_SIZE);
                        textSizeParam.Set(textSizeParam.AsDouble() * 0.6);
                        minorLabelType.Name = minorStationSetLabelTypeName;
                    }

                    if (curvatureLabelType == null)
                    {
                        // create a new label type, based on the default alignment station label type,
                        // but with some adjustments to the label contents, as described below
                        ElementType defaultAlignmentLabelType = document.GetElement(
                            document.GetDefaultElementTypeId(ElementTypeGroup.AlignmentStationLabelType)) as ElementType;

                        curvatureLabelType = defaultAlignmentLabelType.Duplicate(horizontalCurvatureChangeLabelTypeName) as SpotDimensionType;

                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_COORDINATE_BASE).Set(1);              // "Shared" coordinate base

                        // Label position and content
                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_ROTATE_WITH_COMPONENT).Set(0);         // do not rotate with component
                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_TEXT_ORIENTATION).Set(0);              // horizontal text
                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_TEXT_LOCATION).Set(0);                 // text location above leader
                        curvatureLabelType.get_Parameter(BuiltInParameter.ALIGNMENT_STATION_LABEL_INCLUDE_STATION).Set(1); // include station
                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_COORDINATE_INCLUDE_ELEVATION).Set(0);       // do not include elevation
                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_BOT_VALUE).Set(0);                     // do not include bottom value
                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_TOP_VALUE).Set(0);                     // do not include top value
                        curvatureLabelType.get_Parameter(BuiltInParameter.ALIGNMENT_STATION_LABEL_IND_STATION).Set("");    // empty station indicator

                        // Text
                        curvatureLabelType.get_Parameter(BuiltInParameter.DIM_TEXT_BACKGROUND).Set(0);                              // nontransparent text
                        curvatureLabelType.get_Parameter(BuiltInParameter.LINE_COLOR).Set(255 /* 255*2^0 + 0*2^8 + 0*2^16: red */); // text in red color
                        Parameter textSizeParam = curvatureLabelType.get_Parameter(BuiltInParameter.TEXT_SIZE);
                        textSizeParam.Set(textSizeParam.AsDouble() * 0.6);                                                          // text size 60% of default

                        // Leader
                        curvatureLabelType.get_Parameter(BuiltInParameter.SPOT_ELEV_LEADER_ARROWHEAD).Set(ElementId.InvalidElementId); // no leader arrowhead
                    }
                    t.Commit();
                }

                // create major and minor station label sets
                ElementId alignmentId = AlignmentSelectionFilter.SelectAlignment(document);
                Alignment alignment   = Alignment.Get(document.GetElement(alignmentId));

                // start placement from a multiple of the major station interval
                // make sure to compute the multiple in the proper unit system and then convert it back to internal units for further use
                double labelSetsPlacementStartStation = UnitUtils.ConvertFromInternalUnits(alignment.DisplayedStartStation, UnitTypeId.StationingMeters);
                labelSetsPlacementStartStation =
                    Math.Ceiling(labelSetsPlacementStartStation / majorStationInterval) * majorStationInterval;
                labelSetsPlacementStartStation =
                    UnitUtils.ConvertToInternalUnits(labelSetsPlacementStartStation, UnitTypeId.StationingMeters);

                var majorStations = new List <double>();
                using (Transaction t = new Transaction(document, "Create major station labels"))
                {
                    t.Start();
                    AlignmentStationLabelSetOptions options = new AlignmentStationLabelSetOptions();
                    options.Interval     = UnitUtils.ConvertToInternalUnits(majorStationInterval, UnitTypeId.StationingMeters);
                    options.Offset       = UnitUtils.ConvertToInternalUnits(labelTextOffset, UnitTypeId.StationingMeters);
                    options.StartStation = labelSetsPlacementStartStation;
                    options.EndStation   = alignment.DisplayedEndStation;
                    options.TypeId       = majorLabelType.Id;

                    var labels = AlignmentStationLabel.CreateSet(alignment, view, options);
                    foreach (var label in labels)
                    {
                        majorStations.Add(label.Station);
                    }
                    t.Commit();
                }

                using (Transaction t = new Transaction(document, "Create minor station labels"))
                {
                    t.Start();
                    AlignmentStationLabelSetOptions options = new AlignmentStationLabelSetOptions();
                    options.Interval = UnitUtils.ConvertToInternalUnits(minorStationInterval, UnitTypeId.StationingMeters);
                    // setting text offset specification can be skipped,
                    // as in this example the minor station labels do not include any label text, only leader arrowheads
                    options.StartStation = labelSetsPlacementStartStation;
                    options.EndStation   = labelSetsPlacementStartStation + UnitUtils.ConvertToInternalUnits(majorStationInterval, UnitTypeId.StationingMeters);
                    options.TypeId       = minorLabelType.Id;

                    // delete the minor station labels which overlap with the major ones
                    var labels = AlignmentStationLabel.CreateSet(alignment, view, options);
                    foreach (var label in labels)
                    {
                        foreach (var majorStation in majorStations)
                        {
                            if (MathComparisonUtils.IsAlmostEqual(label.Station, majorStation))
                            {
                                label.Element.Pinned = false;
                                document.Delete(label.Element.Id);
                                break;
                            }
                        }
                    }

                    t.Commit();
                }

                if (view.ViewType == ViewType.FloorPlan || view.ViewType == ViewType.CeilingPlan || view.ViewType == ViewType.EngineeringPlan)
                {
                    IList <HorizontalCurveEndpoint> curveEndpoints = alignment.GetDisplayedHorizontalCurveEndpoints();
                    using (TransactionGroup tg = new TransactionGroup(document, "Create horizontal curvature changes labels"))
                    {
                        tg.Start();

                        double previousStation = alignment.DisplayedStartStation;
                        foreach (var curveEndpoint in curveEndpoints)
                        {
                            using (Transaction t = new Transaction(document, "Create one horizontal curvature change label"))
                            {
                                double thisStation = curveEndpoint.Station;
                                // skip placing curvature labels at the start and end points of the alignment
                                if (MathComparisonUtils.IsAlmostEqual((alignment.DisplayedStartStation), thisStation) ||
                                    MathComparisonUtils.IsAlmostEqual((alignment.DisplayedEndStation), thisStation))
                                {
                                    continue;
                                }

                                t.Start();

                                AlignmentStationLabelOptions options = new AlignmentStationLabelOptions(thisStation);
                                options.HasLeader = false;
                                options.TypeId    = curvatureLabelType.Id;

                                AlignmentStationLabel label = AlignmentStationLabel.Create(alignment, view, options);

                                // regeneration is necessary before the label's positional properties (such as Origin)L can be properly evaluated
                                document.Regenerate();

                                // set the shoulder and end to coincide, creating a leader pointing along the view's up direction
                                SpotDimension dim = label.Element as SpotDimension;

                                XYZ leaderDirection = view.UpDirection;
                                // compute the distance to the previous label
                                // if the previous label is too close, flip the placement direction
                                {
                                    var    dimBBox   = dim.get_BoundingBox(view);
                                    double dimOffset = Math.Abs(dimBBox.Max.X - dimBBox.Min.X);
                                    if (MathComparisonUtils.IsGreaterThanOrAlmostEqual(dimOffset, thisStation - previousStation))
                                    {
                                        leaderDirection = leaderDirection.Negate();
                                    }
                                }

                                dim.HasLeader              = true;
                                dim.LeaderHasShoulder      = true;
                                dim.LeaderShoulderPosition = dim.Origin +
                                                             leaderDirection * UnitUtils.ConvertToInternalUnits(labelTextOffset, UnitTypeId.StationingMeters) * view.Scale;
                                dim.LeaderEndPosition = dim.LeaderShoulderPosition;
                                dim.TextPosition      = dim.LeaderShoulderPosition;

                                previousStation = thisStation;
                                t.Commit();
                            }
                        }
                        tg.Assimilate();
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
示例#33
0
        public static Result Do(UIApplication uiapp, Dictionary <ElementId, double> level)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            List <XYZ>   points      = new List <XYZ>();
            List <Curve> SplitCurves = new List <Curve>();

            List <double> _elevations = RevitModel.LevelElevation.GetElevations(doc);

            foreach (ElementId e1 in GlobalVariables.SplitObjects)
            {
                Curve c1 = Elements.GetCurve(doc, level, e1);

                if (null != c1)
                {
                    SplitCurves.Add(c1);

                    foreach (ElementId e2 in GlobalVariables.CutObjects)
                    {
                        Curve c2 = Elements.GetCurve(doc, level, e2);

                        if (null != c2)
                        {
                            XYZ intersection = GetIntersection(c1, c2);

                            if (intersection != null && !PointAlreadyInList.Check(points, intersection))
                            {
                                points.Add(intersection);
                            }
                        }
                    }
                }
            }

            using (TransactionGroup transgroup = new TransactionGroup(doc, "Intersect Geometry"))
            {
                try
                {
                    if (transgroup.Start() != TransactionStatus.Started)
                    {
                        return(Result.Failed);
                    }

                    foreach (ElementId e1 in GlobalVariables.SplitObjects)
                    {
                        Curve          c         = Elements.GetCurve(doc, level, e1);
                        FamilyInstance f         = Elements.GetFamilyInstance(doc, level, e1);
                        List <Curve>   newCurves = ElementSplitter.Do(c, points);

                        ICollection <ElementId> newElements = null;

                        for (int i = 0; i < newCurves.Count; i++)
                        {
                            if (i != 0)     // First Element different - just change endpoint
                                            // All other make copy first
                            {
                                using (Transaction trans = new Transaction(doc, "Copy element."))
                                {
                                    try
                                    {
                                        if (trans.Start() != TransactionStatus.Started)
                                        {
                                            return(Result.Failed);
                                        }

                                        XYZ transform = newCurves[i].GetEndPoint(0) - c.GetEndPoint(0);
                                        newElements = Elements.Transform(doc, e1, transform);

                                        if (TransactionStatus.Committed != trans.Commit())
                                        {
                                            trans.RollBack();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString());
                                        trans.RollBack();
                                    }
                                }

                                foreach (ElementId id in newElements)
                                {
                                    // Change Curve
                                    using (Transaction trans = new Transaction(doc, "Transform element."))
                                    {
                                        try
                                        {
                                            if (trans.Start() != TransactionStatus.Started)
                                            {
                                                return(Result.Failed);
                                            }

                                            FamilyInstance newf = Elements.GetFamilyInstance(doc, level, id);
                                            Elements.ChangeEndPoint(doc, newCurves[i], newf, level, _elevations);

                                            FailureHandlingOptions options = trans.GetFailureHandlingOptions();
                                            options.SetFailuresPreprocessor(new WarningSwallower());

                                            if (TransactionStatus.Committed != trans.Commit(options))
                                            {
                                                trans.RollBack();
                                            }
                                        }
                                        catch
                                        {
                                            trans.RollBack();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                using (Transaction trans = new Transaction(doc, "Transform element."))
                                {
                                    try
                                    {
                                        if (trans.Start() != TransactionStatus.Started)
                                        {
                                            return(Result.Failed);
                                        }

                                        foreach (ElementId eId in JoinGeometryUtils.GetJoinedElements(doc, f))
                                        {
                                            JoinGeometryUtils.UnjoinGeometry(doc, doc.GetElement(e1), doc.GetElement(eId));
                                        }

                                        FailureHandlingOptions options = trans.GetFailureHandlingOptions();
                                        options.SetFailuresPreprocessor(new WarningSwallower());

                                        if (TransactionStatus.Committed != trans.Commit(options))
                                        {
                                            trans.RollBack();
                                        }
                                    }
                                    catch
                                    {
                                        trans.RollBack();
                                    }
                                }
                                using (Transaction trans = new Transaction(doc, "Transform element."))
                                {
                                    try
                                    {
                                        if (trans.Start() != TransactionStatus.Started)
                                        {
                                            return(Result.Failed);
                                        }

                                        LocationCurve orig_location = f.Location as LocationCurve;
                                        double        orig_len      = orig_location.Curve.Length;

                                        double up_len = newCurves[i].Length;

                                        Elements.ChangeEndPoint(doc, newCurves[i], f, level, _elevations);

                                        LocationCurve after_location = f.Location as LocationCurve;
                                        double        after_len      = after_location.Curve.Length;
                                        doc.Regenerate();

                                        LocationCurve regen_location = f.Location as LocationCurve;
                                        double        regen_len      = regen_location.Curve.Length;

                                        uidoc.RefreshActiveView();

                                        FailureHandlingOptions options = trans.GetFailureHandlingOptions();
                                        options.SetFailuresPreprocessor(new WarningSwallower());
                                        options.SetClearAfterRollback(true);

                                        if (TransactionStatus.Committed != trans.Commit(options))
                                        {
                                            trans.RollBack();
                                            return(Result.Failed);
                                        }
                                    }
                                    catch
                                    {
                                        trans.RollBack();
                                        return(Result.Failed);
                                    }
                                }
                            }
                        }
                    }
                    if (transgroup.Assimilate() == TransactionStatus.Committed)
                    {
                        return(Result.Succeeded);
                    }
                    else
                    {
                        return(Result.Failed);
                    }
                }
                catch
                {
                    transgroup.RollBack();
                    return(Result.Failed);
                }
            }
        }
        /// <summary>
        /// Shuffles all parameter values
        /// </summary>
        /// <param name="uiapp">The Revit application object</param>
        /// <param name="text">Caption of the transaction for the operation.</param>
        /// <param name="operation">A delegate to perform the operation on an instance of a door.</param>
        ///
        public static void ExecuteParameterChange(UIApplication uiapp, String text, List <Tuple <string, double> > values)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            if (!doc.IsFamilyDocument)
            {
                Command.global_message = "Please run this command in a family document.";
                TaskDialog.Show("Message", Command.global_message);
            }

            int    counter = 0;
            int    max     = values.Count();
            string current = "";

            if ((uidoc != null))
            {
                using (TransactionGroup tg = new TransactionGroup(doc, "Parameter Change"))
                {
                    tg.Start();

                    string s       = "{0} of " + max.ToString() + String.Format(" elements processed. ", counter.ToString()) + "{1}";
                    string caption = "Processing ..";

                    using (ProgressBarView pbv = new ProgressBarView(caption, s, max))
                    {
                        foreach (var value in values)
                        {
                            current = value.Item1;

                            if (pbv.getAbortFlag())
                            {
                                break;
                            }
                            pbv.Increment(current);    //Increment the ProgressBar
                            using (Transaction trans = new Transaction(uidoc.Document))
                            {
                                FailureHandlingOptions failureHandlingOptions = trans.GetFailureHandlingOptions();
                                FailureHandler         failureHandler         = new FailureHandler();
                                failureHandlingOptions.SetFailuresPreprocessor(failureHandler);
                                failureHandlingOptions.SetClearAfterRollback(true);
                                trans.SetFailureHandlingOptions(failureHandlingOptions);

                                FamilyManager   mgr = doc.FamilyManager;
                                FamilyParameter fp  = mgr.get_Parameter(value.Item1);
                                // Since we'll modify the document, we need a transaction
                                // It's best if a transaction is scoped by a 'using' block
                                // The name of the transaction was given as an argument
                                if (trans.Start(text) == TransactionStatus.Started)
                                {
                                    if (fp.IsDeterminedByFormula)
                                    {
                                        continue;                            //Cannot change parameters driven by formulas
                                    }
                                    if (fp.IsReporting)
                                    {
                                        continue;                    //Cannot change reporting parameters
                                    }
                                    mgr.Set(fp, value.Item2);
                                    doc.Regenerate();
                                    trans.Commit();
                                    uidoc.RefreshActiveView();
                                    if (failureHandler.ErrorMessage != "")
                                    {
                                        RequestError.ErrorLog.Add(new Message(fp.Definition.Name, failureHandler.ErrorMessage));
                                    }
                                    else
                                    {
                                        RequestError.NotifyLog += $"{fp.Definition.Name} was shuffled.{Environment.NewLine}";
                                    }
                                }
                            }
                        }
                    }
                    tg.Assimilate();
                    if (!String.IsNullOrEmpty(RequestError.NotifyLog))
                    {
                        var lines = RequestError.NotifyLog.Split('\n').Length - 1;
                        RequestError.NotifyLog += $"{Environment.NewLine}{lines.ToString()} parameters have been processed sucessfully.";
                    }
                }
            }
        }
示例#35
0
        public Result AlignElements(ExternalCommandData commandData, ref string message, AlignType alignType)
        {
            // Get the handle of current document.
            UIdoc = commandData.Application.ActiveUIDocument;
            Document document = UIdoc.Document;

            using (TransactionGroup txg = new TransactionGroup(document))
            {
                try
                {
                    ICollection <ElementId> selectedIds = UIdoc.Selection.GetElementIds();

                    bool empty = false;

                    if (selectedIds.Count == 0)
                    {
                        empty = true;

                        IList <Reference> selectedReferences = UIdoc.Selection.PickObjects(ObjectType.Element, "Pick elements to be aligned");
                        selectedIds = Tools.RevitReferencesToElementIds(document, selectedReferences);
                        UIdoc.Selection.SetElementIds(selectedIds);
                    }

                    AlignTag(alignType, txg, selectedIds, document);

                    // Disselect if the selection was empty to begin with
                    if (empty)
                    {
                        selectedIds = new List <ElementId> {
                            ElementId.InvalidElementId
                        }
                    }
                    ;

                    UIdoc.Selection.SetElementIds(selectedIds);

                    // Return Success
                    return(Result.Succeeded);
                }

                catch (Autodesk.Revit.Exceptions.OperationCanceledException exceptionCanceled)
                {
                    //message = exceptionCanceled.Message;
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Cancelled);
                }
                catch (ErrorMessageException errorEx)
                {
                    // checked exception need to show in error messagebox
                    message = errorEx.Message;
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Failed);
                }
                catch (Exception ex)
                {
                    // unchecked exception cause command failed
                    message = ex.Message;
                    //Trace.WriteLine(ex.ToString());
                    if (txg.HasStarted())
                    {
                        txg.RollBack();
                    }
                    return(Result.Failed);
                }
            }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            // There is likely an easier way to do this using
            // an exclusion filter but this being my first foray
            // into filtering with Revit, I couldn't get that working.

            FilteredElementCollector filt   = new FilteredElementCollector(doc);
            List <ElementId>         refIDs = filt.OfClass(typeof(ReferencePlane)).ToElementIds().ToList();

            using (TransactionGroup tg = new TransactionGroup(doc))
            {
                tg.Start("Remove Un-Used Reference Planes");
                foreach (ElementId id in refIDs)
                {
                    var filt2 = new ElementClassFilter(typeof(FamilyInstance));

                    var filt3 = new ElementParameterFilter(new FilterElementIdRule(new ParameterValueProvider(new ElementId(BuiltInParameter.HOST_ID_PARAM)), new FilterNumericEquals(), id));
                    var filt4 = new LogicalAndFilter(filt2, filt3);

                    var thing = new FilteredElementCollector(doc);

                    using (Transaction t = new Transaction(doc))
                    {
                        // Check for hosted elements on the plane
                        if (thing.WherePasses(filt4).Count() == 0)
                        {
                            t.Start("Do The Thing");

#if Revit2018
                            if (doc.GetElement(id).GetDependentElements(new ElementClassFilter(typeof(FamilyInstance))).Count == 0)
                            {
                                doc.Delete(id);
                            }

                            t.Commit();
#else
                            // Make sure there is nothing measuring to the plane

                            if (doc.Delete(id).Count() > 1)
                            {
                                t.Dispose();
                                // Skipped
                            }
                            else
                            {
                                // Deleted
                                t.Commit();
                            }
#endif
                        }
                        else
                        {
                            // Skipped
                        }
                    }
                }
                tg.Assimilate();
            }
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            ICollection <ElementId> refplaneids
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ReferencePlane))
                  .ToElementIds();

            using (TransactionGroup tg = new TransactionGroup(doc))
            {
                tg.Start("Remove unused reference planes");

                FilteredElementCollector instances
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(FamilyInstance));

                Dictionary <ElementId, int> toKeep
                    = new Dictionary <ElementId, int>();

                foreach (FamilyInstance i in instances)
                {
                    // Ensure the element is hosted

                    if (null != i.Host)
                    {
                        ElementId hostId = i.Host.Id;

                        // Check list to see if we've already added this plane

                        if (!toKeep.ContainsKey(hostId))
                        {
                            toKeep.Add(hostId, 0);
                        }
                        ++toKeep[hostId];
                    }
                }

                // Loop through reference planes and
                // delete the ones not in the list toKeep.

                foreach (ElementId refid in refplaneids)
                {
                    if (!toKeep.ContainsKey(refid))
                    {
                        using (Transaction t = new Transaction(doc))
                        {
                            t.Start("Removing plane "
                                    + doc.GetElement(refid).Name);

                            // Ensure there are no dimensions measuring to the plane

                            if (doc.Delete(refid).Count > 1)
                            {
                                t.Dispose();
                            }
                            else
                            {
                                t.Commit();
                            }
                        }
                    }
                }
                tg.Assimilate();
            }
            return(Result.Succeeded);
        }
    public void TestWeightedSummedProgress() {
      using(
        TransactionGroup<TestTransaction> testTransactionGroup =
          new TransactionGroup<TestTransaction>(
            new WeightedTransaction<TestTransaction>[] {
              new WeightedTransaction<TestTransaction>(new TestTransaction(), 1.0f),
              new WeightedTransaction<TestTransaction>(new TestTransaction(), 2.0f)
            }
          )
      ) {
        ITransactionGroupSubscriber mockedSubscriber = mockSubscriber(testTransactionGroup);

        Expect.Once.On(mockedSubscriber).
          Method("ProgressChanged").
          With(
            new Matcher[] {
              new NMock2.Matchers.TypeMatcher(typeof(TransactionGroup<TestTransaction>)),
              new ProgressUpdateEventArgsMatcher(new ProgressReportEventArgs(0.5f / 3.0f))
            }
          );

        testTransactionGroup.Children[0].Transaction.ChangeProgress(0.5f);

        Expect.Once.On(mockedSubscriber).
          Method("ProgressChanged").
          With(
            new Matcher[] {
              new NMock2.Matchers.TypeMatcher(typeof(TransactionGroup<TestTransaction>)),
              new ProgressUpdateEventArgsMatcher(new ProgressReportEventArgs(0.5f))
            }
          );

        testTransactionGroup.Children[1].Transaction.ChangeProgress(0.5f);

        this.mockery.VerifyAllExpectationsHaveBeenMet();
      }
    }
示例#39
0
        /// <summary>
        /// Adds a new retaining pond.
        /// </summary>
        /// <param name="uiDoc">The document.</param>
        /// <param name="pondRadius">The radius of the pond.</param>
        private void AddNewRetainingPond(UIDocument uiDoc, double pondRadius)
        {
            Document doc = uiDoc.Document;

            // Find toposurfaces
            FilteredElementCollector tsCollector = new FilteredElementCollector(doc);

            tsCollector.OfClass(typeof(TopographySurface));
            IEnumerable <TopographySurface> tsEnumerable = tsCollector.Cast <TopographySurface>().Where <TopographySurface>(ts => !ts.IsSiteSubRegion);
            int count = tsEnumerable.Count <TopographySurface>();

            // If there is only on surface, use it.  If there is more than one, let the user select the target.
            TopographySurface targetSurface = null;

            if (count > 1) // tmp
            {
                targetSurface = SiteUIUtils.PickTopographySurface(uiDoc);
            }
            else
            {
                targetSurface = tsEnumerable.First <TopographySurface>();
            }

            // Pick point and project to plane at toposurface average elevation
            XYZ    point     = SiteUIUtils.PickPointNearToposurface(uiDoc, targetSurface, "Pick point for center of pond.");
            double elevation = point.Z;

            // Add subregion first, so that any previously existing points can be removed to avoid distorting the new region

            // Find material "Water"
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.OfClass(typeof(Material));
            Material mat = collector.Cast <Material>().FirstOrDefault <Material>(m => m.Name == "Water");

            // Create subregion curves
            List <Curve> curves = new List <Curve>();

            curves.Add(Arc.Create(point, pondRadius, 0, Math.PI, XYZ.BasisX, XYZ.BasisY));
            curves.Add(Arc.Create(point, pondRadius, Math.PI, 2 * Math.PI, XYZ.BasisX, XYZ.BasisY));

            CurveLoop        curveLoop  = CurveLoop.Create(curves);
            List <CurveLoop> curveLoops = new List <CurveLoop>();

            curveLoops.Add(curveLoop);

            // All changes are added to one transaction group - will create one undo item
            using (TransactionGroup addGroup = new TransactionGroup(doc, "Add pond group"))
            {
                addGroup.Start();

                IList <XYZ> existingPoints = null;
                // Transacton for adding subregion.
                using (Transaction t2 = new Transaction(doc, "Add subregion"))
                {
                    t2.Start();
                    SiteSubRegion region = SiteSubRegion.Create(doc, curveLoops, targetSurface.Id);
                    if (mat != null)
                    {
                        region.TopographySurface.MaterialId = mat.Id;
                    }
                    t2.Commit();

                    // The boundary points for the subregion cannot be deleted, since they are generated
                    // to represent the subregion boundary rather than representing real points in the host.
                    // Get non-boundary points only to be deleted.
                    existingPoints = SiteEditingUtils.GetNonBoundaryPoints(region.TopographySurface);

                    // Average elevation of all points in the subregion to use as base elevation for the pond topography
                    elevation = SiteEditingUtils.GetAverageElevation(region.TopographySurface.GetPoints());
                }

                // Add the topography points to the target surface via edit scope.
                using (TopographyEditScope editScope = new TopographyEditScope(doc, "Edit TS"))
                {
                    editScope.Start(targetSurface.Id);

                    // Transaction for points changes
                    using (Transaction t = new Transaction(doc, "Add points"))
                    {
                        t.Start();

                        // Delete existing points first to avoid conflict
                        if (existingPoints.Count > 0)
                        {
                            targetSurface.DeletePoints(existingPoints);
                        }

                        // Generate list of points to add
                        IList <XYZ> points = SiteEditingUtils.GeneratePondPointsSurrounding(new XYZ(point.X, point.Y, elevation - 3), pondRadius);
                        targetSurface.AddPoints(points);
                        t.Commit();
                    }

                    editScope.Commit(new TopographyEditFailuresPreprocessor());
                }
                addGroup.Assimilate();
            }
        }
 public void TestAlreadyEndedTransactions() {
   using(
     TransactionGroup<Transaction> testTransactionGroup =
       new TransactionGroup<Transaction>(
         new Transaction[] { Transaction.EndedDummy, Transaction.EndedDummy }
       )
   ) {
     Assert.IsTrue(testTransactionGroup.Wait(1000));
   }
 }
示例#41
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            using (TransactionGroup transGroup = new TransactionGroup(doc, "TextNoteToDetailRebarCmd"))
            {
                transGroup.Start();
                while (true)
                {
                    try
                    {
                        Reference r1 = uidoc.Selection.PickObject(ObjectType.Element,
                                                                  new TextNoteSelectionFilter(),
                                                                  "Pick Text Notes to copy value");
                        TextNote textNote = doc.GetElement(r1.ElementId) as TextNote;
                        if (textNote == null)
                        {
                            continue;
                        }

                        Reference r2 = uidoc.Selection.PickObject(ObjectType.Element,
                                                                  new DetailRebarSelectionFilter(),
                                                                  "Pick Text Notes to copy value");

                        Element detailRebar = doc.GetElement(r2.ElementId);
                        if (detailRebar == null)
                        {
                            continue;
                        }
                        Parameter barDiameter = detailRebar.LookupParameter("D");
                        Parameter spacing     = detailRebar.LookupParameter("S");
                        Parameter n           = detailRebar.LookupParameter("n");


                        // textNote = T10-150 B2
                        // textNote = 2T10-300 T2
                        string textNoteValue = textNote.Text.Trim();
                        char[] separator     = new[]
                        {
                            Convert.ToChar("T"),
                            Convert.ToChar("-"),
                            Convert.ToChar(" "),
                        };
                        string[] allValues = textNoteValue.Split(separator);

                        // textNote = ["",10,150,B2]
                        // textNote = [2,10,300,"",2]

                        //MessageBox.Show(allValues.Length.ToString());
                        //MessageBox.Show(allValues[0] + "\n" + allValues[1] + "\n" +
                        //                allValues[2] + "\n" +allValues[3] + "\n"+
                        //                allValues[4] + "\n");

                        using (Transaction trans = new Transaction(doc))
                        {
                            trans.Start("TextNoteToDetailRebarCmd");

                            // textNote = ["",10,150,B2] - T10-150 B2
                            if (string.IsNullOrEmpty(allValues[0]))
                            {
                                n.Set(Convert.ToInt16(allValues[1]));
                                barDiameter.Set(Convert.ToInt16(allValues[1]));
                                spacing.Set(Convert.ToInt16(allValues[2]));
                            }
                            else //textNote = [2, 10, 300, "", 2] - 2T10-300 T2
                            {
                                n.Set(Convert.ToInt16(allValues[0]));
                                barDiameter.Set(Convert.ToInt16(allValues[1]));
                                spacing.Set(Convert.ToInt16(allValues[2]));
                            }

                            trans.Commit();
                        }
                    }
                    catch (Exception e)
                    {
                        break;
                    }
                }
                transGroup.Commit();
            }

            return(Result.Succeeded);
        }
 public void TestTransactionEndingDuringConstructor() {
   ChainEndingTransaction chainTransaction = new ChainEndingTransaction();
   using(
     TransactionGroup<Transaction> testTransactionGroup =
       new TransactionGroup<Transaction>(
         new Transaction[] { chainTransaction.ChainedTransaction, chainTransaction }
       )
   ) {
     Assert.IsFalse(testTransactionGroup.Ended);
     chainTransaction.End();
     Assert.IsTrue(testTransactionGroup.Ended);
   }
 }
示例#43
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="commandData">the external command data</param>
        public TransactionForm(ExternalCommandData commandData)
        {
            m_commandData = commandData;
            m_document = m_commandData.Application.ActiveUIDocument.Document;
            if (m_document == null)
            {
               MessageBox.Show("There is no active document.");
            }

            InitializeComponent();

            // created the root node
            m_rootNode = new TreeNode("Command history");
            this.transactionsTreeView.Nodes.Add(m_rootNode);

            // set availability of form buttons
            UpdateButtonsStatus();

            // start the main transaction group (will be hidden to the user)
            m_mainTtransactionGroup = new TransactionGroup(m_document);
            m_mainTtransactionGroup.Start();
        }
        /// <summary>
        /// Saves the dispatch transaction.
        /// </summary>
        /// <param name="dispatchModel">The dispatch model.</param>
        /// <param name="user">The user.</param>
        public void SaveDispatchTransaction(DispatchModel dispatchModel, UserProfile user)
        {
            Dispatch dispatch = dispatchModel.GenerateDipatch(user);

            dispatch.HubID = user.DefaultHub.HubID;
            dispatch.UserProfileID = user.UserProfileID;
            dispatch.DispatchAllocationID = dispatchModel.DispatchAllocationID;
            dispatch.OtherDispatchAllocationID = dispatchModel.OtherDispatchAllocationID;
            CommodityType commType = _unitOfWork.CommodityTypeRepository.FindById(dispatchModel.CommodityTypeID);

            foreach (DispatchDetailModel detail in dispatchModel.DispatchDetails)
            {

                if (commType.CommodityTypeID == 2)//if it's a non food
                {
                    detail.DispatchedQuantityMT = 0;
                    detail.RequestedQuantityMT = 0;
                }

                TransactionGroup group = new TransactionGroup();

                if (dispatchModel.Type == 1)
                {
                    Transaction transaction2 = GetPositiveFDPTransaction(dispatchModel, dispatch, detail);
                    group.Transactions.Add(transaction2);

                    Transaction transaction = GetNegativeFDPTransaction(dispatchModel, dispatch, detail);
                    group.Transactions.Add(transaction);
                }
                else
                {
                    Transaction transaction2 = GetPositiveHUBTransaction(dispatchModel, dispatch, detail);
                    group.Transactions.Add(transaction2);

                    Transaction transaction = GetNegativeHUBTransaction(dispatchModel, dispatch, detail);
                    group.Transactions.Add(transaction);
                }

                DispatchDetail dispatchDetail = GenerateDispatchDetail(detail);
                dispatchDetail.TransactionGroup = group;

                dispatch.DispatchDetails.Add(dispatchDetail);

            }
            // Try to save this transaction
            //    db.Database.Connection.Open();
              //  DbTransaction dbTransaction = db.Database.Connection.BeginTransaction();
            try
            {
                _unitOfWork.DispatchRepository.Add(dispatch);
                _unitOfWork.Save();
                //repository.Dispatch.Add(dispatch);
                //dbTransaction.Commit();
            }
            catch (Exception exp)
            {
               // dbTransaction.Rollback();
                //TODO: Save the detail of this exception somewhere
                throw new Exception("The Dispatch Transaction Cannot be saved. <br />Detail Message :" + exp.Message);
            }

            if (dispatch.Type == 1)
            {
                string sms = dispatch.GetSMSText();
                SMS.SendSMS(dispatch.FDPID.Value, sms);
            }
        }
示例#45
0
        /// <summary>
        /// Start transaction group button click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartTransGroup_Click(object sender, EventArgs e)
        {
            m_transGroupCount++;
               m_transactionGroup = new TransactionGroup(m_document, "Transaction Group " + m_transGroupCount.ToString());
               m_transactionGroup.Start();

               AddNode(OperationType.StartTransactionGroup);

               UpdateButtonsStatus();
        }
        /// <summary>
        /// </summary>
        /// <param name="viewModel"></param>
        /// <param name="user"></param>
        /// <exception cref="System.Exception"></exception>
        public void SaveLossTrasnsaction(LossesAndAdjustmentsViewModel viewModel, UserProfile user)
        {
            Commodity commodity = _unitOfWork.CommodityRepository.FindById(viewModel.CommodityId);

            Adjustment lossAndAdjustment = new Adjustment();
            TransactionGroup transactionGroup = new TransactionGroup();
            Transaction transactionOne = new Transaction();

            //transaction.TransactionGroupID = transactionGroupId;
            transactionOne.LedgerID = 2;
            transactionOne.HubOwnerID = user.DefaultHub.HubOwner.HubOwnerID;
            transactionOne.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, user.DefaultHub.HubID); //
            transactionOne.HubID = user.DefaultHub.HubID;
            transactionOne.StoreID = viewModel.StoreId;  //
            transactionOne.ProjectCodeID = viewModel.ProjectCodeId;
            transactionOne.ShippingInstructionID = viewModel.ShippingInstructionId;

            transactionOne.ParentCommodityID = (commodity.ParentID == null)
                                                       ? commodity.CommodityID
                                                       : commodity.ParentID.Value;
            transactionOne.CommodityID = viewModel.CommodityId;
            transactionOne.ProgramID = viewModel.ProgramId;
            transactionOne.CommodityGradeID = null; // How did I get this value ?
            transactionOne.QuantityInMT = 0 - viewModel.QuantityInMt;
            transactionOne.QuantityInUnit = 0 - viewModel.QuantityInUint;
            transactionOne.UnitID = viewModel.UnitId;
            transactionOne.TransactionDate = DateTime.Now;

            Transaction transactionTwo = new Transaction();

            //transactionToStore.TransactionGroupID = transactionGroupId;
            transactionTwo.LedgerID = 14;
            transactionTwo.HubOwnerID = user.DefaultHub.HubOwnerID;
            transactionTwo.AccountID =_accountService.GetAccountIdWithCreate(Account.Constants.HUB, user.DefaultHub.HubID); //
            transactionTwo.HubID = user.DefaultHub.HubID;
            transactionTwo.StoreID = viewModel.StoreId;  //
            transactionTwo.ProjectCodeID = viewModel.ProjectCodeId;
            transactionTwo.ShippingInstructionID = viewModel.ShippingInstructionId;
            transactionTwo.ParentCommodityID = (commodity.ParentID == null)
                                                       ? commodity.CommodityID
                                                       : commodity.ParentID.Value;
            transactionTwo.CommodityID = viewModel.CommodityId;
            transactionTwo.ProgramID = viewModel.ProgramId;
            transactionTwo.CommodityGradeID = null; // How did I get this value ?
            transactionTwo.QuantityInMT = viewModel.QuantityInMt;
            transactionTwo.QuantityInUnit = viewModel.QuantityInUint;
            transactionTwo.UnitID = viewModel.UnitId;
            transactionTwo.TransactionDate = DateTime.Now;

            transactionGroup.Transactions.Add(transactionOne);
            transactionGroup.Transactions.Add(transactionTwo);

            lossAndAdjustment.PartitionID = 0;
            lossAndAdjustment.TransactionGroup = transactionGroup;
            lossAndAdjustment.HubID = user.DefaultHub.HubID;
            lossAndAdjustment.AdjustmentReasonID = viewModel.ReasonId;
            lossAndAdjustment.AdjustmentDirection = "L";
            lossAndAdjustment.AdjustmentDate = viewModel.SelectedDate;
            lossAndAdjustment.ApprovedBy = viewModel.ApprovedBy;
            lossAndAdjustment.Remarks = viewModel.Description;
            lossAndAdjustment.UserProfileID = user.UserProfileID;
            lossAndAdjustment.ReferenceNumber = viewModel.MemoNumber;
            lossAndAdjustment.StoreManName = viewModel.StoreMan;

            // Try to save this transaction
            //db.Database.Connection.Open();
            //DbTransaction dbTransaction = db.Database.Connection.BeginTransaction();
            try
            {
                _unitOfWork.AdjustmentRepository.Add(lossAndAdjustment);
                _unitOfWork.Save();
                //repository.Adjustment.Add(lossAndAdjustment);
                //dbTransaction.Commit();
            }
            catch (Exception exp)
            {
               // dbTransaction.Rollback();
                //TODO: Save the detail of this exception somewhere
                throw new Exception("The Internal Movement Transaction Cannot be saved. <br />Detail Message :" + exp.Message);
            }
        }
示例#47
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += new ResolveEventHandler(Misc.LoadFromSameFolder);

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            View active_view = doc.ActiveView;

            double tolerance = app.ShortCurveTolerance;

            ///////////////////////
            // Pick Import Instance
            ImportInstance import = null;

            try
            {
                Reference r = uidoc.Selection.PickObject(ObjectType.Element, new Util.ElementsOfClassSelectionFilter <ImportInstance>());
                import = doc.GetElement(r) as ImportInstance;
            }
            catch
            {
                return(Result.Cancelled);
            }
            if (import == null)
            {
                System.Windows.MessageBox.Show("CAD not found", "Tips");
                return(Result.Cancelled);
            }


            // Initiate the progress bar
            Views.ProgressBar pb = new Views.ProgressBar("Modeling entire building", "Initiation...", 100);
            if (pb.ProcessCancelled)
            {
                return(Result.Cancelled);
            }


            //////////////////////////////////
            // Check if the families are ready
            pb.CustomizeStatus("Checking families...", 2);
            if (pb.ProcessCancelled)
            {
                return(Result.Cancelled);
            }
            // Consider to add more customized families (in the Setting Panel)
            if (Properties.Settings.Default.name_door == null ||
                Properties.Settings.Default.name_window == null ||
                Properties.Settings.Default.name_columnRect == null ||
                Properties.Settings.Default.name_columnRound == null)
            {
                System.Windows.MessageBox.Show("Please select the column/door/window type in settings", "Tips");
                return(Result.Cancelled);
            }
            //if (!File.Exists(Properties.Settings.Default.url_door) && File.Exists(Properties.Settings.Default.url_window)
            //    && File.Exists(Properties.Settings.Default.url_column))
            //{
            //    System.Windows.MessageBox.Show("Please check the family path is solid", "Tips");
            //    return Result.Cancelled;
            //}
            //Family fColumn, fDoor, fWindow = null;
            //using (Transaction tx = new Transaction(doc, "Load necessary families"))
            //{
            //    tx.Start();
            //    if (!doc.LoadFamily(Properties.Settings.Default.url_column, out fColumn))
            //    {
            //        System.Windows.MessageBox.Show("Please check the column family path is solid", "Tips");
            //        return Result.Cancelled;
            //    }
            //    if (!doc.LoadFamily(Properties.Settings.Default.url_door, out fDoor) ||
            //        !doc.LoadFamily(Properties.Settings.Default.url_window, out fWindow))
            //    {
            //        System.Windows.MessageBox.Show("Please check the door/window family path is solid", "Tips");
            //        return Result.Cancelled;
            //    }
            //    tx.Commit();
            //}

            // Prepare a family for ViewPlan creation
            // It may be a coincidence that the 1st ViewFamilyType is for the FloorPlan
            // Uplift needed here (doomed if it happends to be a CeilingPlan)
            ViewFamilyType viewType = new FilteredElementCollector(doc)
                                      .OfClass(typeof(ViewFamilyType)).First() as ViewFamilyType;

            RoofType roofType = new FilteredElementCollector(doc)
                                .OfClass(typeof(RoofType)).FirstOrDefault <Element>() as RoofType;

            FloorType floorType = new FilteredElementCollector(doc)
                                  .OfClass(typeof(FloorType)).FirstOrDefault <Element>() as FloorType;


            ////////////////////
            // DATA PREPARATIONS
            pb.CustomizeStatus("Processing geometries...", 3);
            if (pb.ProcessCancelled)
            {
                return(Result.Cancelled);
            }
            // Prepare frames and levels
            // Cluster all geometry elements and texts into datatrees
            // Two procedures are intertwined
            List <GeometryObject> dwg_frames = Util.TeighaGeometry.ExtractElement(uidoc, import,
                                                                                  Properties.Settings.Default.layerFrame, "PolyLine"); // framework is polyline by default
            List <GeometryObject> dwg_geos = Util.TeighaGeometry.ExtractElement(uidoc, import);

            // Terminate if no geometry has been found
            if (dwg_geos == null)
            {
                System.Windows.MessageBox.Show("A drawing frame is mandantory", "Tips");
                return(Result.Failed);
            }

            List <PolyLine> closedPolys = new List <PolyLine>();
            List <PolyLine> parentPolys = new List <PolyLine>();

            Debug.Print("Number of geos acting as the framework is " + dwg_frames.Count().ToString());

            if (dwg_frames.Count > 0)
            {
                foreach (var obj in dwg_frames)
                {
                    PolyLine poly = obj as PolyLine;
                    // Draw shattered lines in case the object is a PolyLine
                    if (null != poly)
                    {
                        var vertices = poly.GetCoordinates();
                        if (vertices[0].IsAlmostEqualTo(vertices.Last()))
                        {
                            closedPolys.Add(poly);
                        }
                    }
                }

                for (int i = 0; i < closedPolys.Count(); i++)
                {
                    int judgement = 0;
                    int counter   = 0;
                    for (int j = 0; j < closedPolys.Count(); j++)
                    {
                        if (i != j)
                        {
                            if (!RegionDetect.PolyInPoly(closedPolys[i], RegionDetect.PolyLineToCurveArray(closedPolys[j], tolerance)))
                            {
                                //Debug.Print("Poly inside poly detected");
                                judgement += 1;
                            }
                            counter += 1;
                        }
                    }
                    if (judgement == counter)
                    {
                        parentPolys.Add(closedPolys[i]);
                    }
                }
            }
            else
            {
                Debug.Print("There is no returning of geometries");
            }
            Debug.Print("Got closedPolys: " + closedPolys.Count().ToString());
            Debug.Print("Got parentPolys: " + parentPolys.Count().ToString());


            string path = Util.TeighaText.GetCADPath(uidoc, import);

            Debug.Print("The path of linked CAD file is: " + path);
            List <Util.TeighaText.CADTextModel> texts = Util.TeighaText.GetCADText(path);


            int    level;
            int    levelCounter = 0;
            double floorHeight  = Misc.MmToFoot(Properties.Settings.Default.floorHeight);
            Dictionary <int, PolyLine> frameDict = new Dictionary <int, PolyLine>(); // cache drawing borders
            Dictionary <int, XYZ>      transDict = new Dictionary <int, XYZ>();
            // cache transform vector from the left-bottom corner of the drawing border to the Origin
            Dictionary <int, List <GeometryObject> > geoDict = new Dictionary <int, List <GeometryObject> >();
            // cache geometries of each floorplan
            Dictionary <int, List <Util.TeighaText.CADTextModel> > textDict = new Dictionary <int, List <Util.TeighaText.CADTextModel> >();

            // cache text info of each floorplan

            if (texts.Count > 0)
            {
                foreach (var textmodel in texts)
                {
                    level = Misc.GetLevel(textmodel.Text, "平面图");
                    Debug.Print("Got target label " + textmodel.Text);
                    if (level != -1)
                    {
                        foreach (PolyLine frame in parentPolys)
                        {
                            if (RegionDetect.PointInPoly(RegionDetect.PolyLineToCurveArray(frame, tolerance), textmodel.Location))
                            {
                                XYZ basePt   = Algorithm.BubbleSort(frame.GetCoordinates().ToList())[0];
                                XYZ transVec = XYZ.Zero - basePt;
                                Debug.Print("Add level " + level.ToString() + " with transaction (" +
                                            transVec.X.ToString() + ", " + transVec.Y.ToString() + ", " + transVec.Z.ToString() + ")");
                                if (!frameDict.Values.ToList().Contains(frame))
                                {
                                    frameDict.Add(level, frame);
                                    transDict.Add(level, transVec);
                                    levelCounter += 1;
                                }
                            }
                        }
                    }
                }
                // Too complicated using 2 iterations... uplift needed
                for (int i = 1; i <= levelCounter; i++)
                {
                    textDict.Add(i, new List <Util.TeighaText.CADTextModel>());
                    geoDict.Add(i, new List <GeometryObject>());
                    CurveArray tempPolyArray = RegionDetect.PolyLineToCurveArray(frameDict[i], tolerance);
                    foreach (var textmodel in texts)
                    {
                        if (RegionDetect.PointInPoly(tempPolyArray, textmodel.Location))
                        {
                            textDict[i].Add(textmodel);
                        }
                    }
                    foreach (GeometryObject go in dwg_geos)
                    {
                        XYZ centPt = XYZ.Zero;
                        if (go is Line)
                        {
                            //get the revit model coordinates.
                            Line go_line = go as Line;
                            centPt = (go_line.GetEndPoint(0) + go_line.GetEndPoint(1)).Divide(2);
                        }
                        else if (go is Arc)
                        {
                            Arc go_arc = go as Arc;
                            centPt = go_arc.Center;
                        }
                        else if (go is PolyLine)
                        {
                            PolyLine go_poly = go as PolyLine;
                            centPt = go_poly.GetCoordinate(0);
                        }
                        // Assignment
                        if (RegionDetect.PointInPoly(tempPolyArray, centPt) && centPt != XYZ.Zero)
                        {
                            geoDict[i].Add(go);
                        }
                    }
                }
            }
            Debug.Print("All levels: " + levelCounter.ToString());
            Debug.Print("frameDict: " + frameDict.Count().ToString());
            Debug.Print("transDict: " + transDict.Count().ToString());
            for (int i = 1; i <= levelCounter; i++)
            {
                Debug.Print("geoDict-{0}: {1}", i, geoDict[i].Count().ToString());
            }
            Debug.Print("textDict: " + textDict.Count().ToString() + " " + textDict[1].Count().ToString());


            ////////////////////
            // MAIN TRANSACTIONS

            // Prepare a family and configurations for TextNote (Put it inside transactions)

            /*
             * TextNoteType tnt = new FilteredElementCollector(doc)
             *  .OfClass(typeof(TextNoteType)).First() as TextNoteType;
             * TextNoteOptions options = new TextNoteOptions();
             * options.HorizontalAlignment = HorizontalTextAlignment.Center;
             * options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
             * BuiltInParameter paraIndex = BuiltInParameter.TEXT_SIZE;
             * Parameter textSize = tnt.get_Parameter(paraIndex);
             * textSize.Set(0.3); // in feet
             *
             * XYZ centPt = RegionDetect.PolyCentPt(frameDict[i]);
             * TextNoteOptions opts = new TextNoteOptions(tnt.Id);
             *
             * // The note may only show in the current view
             * // no matter we still need it anyway
             * TextNote txNote = TextNote.Create(doc, active_view.Id, centPt, floorView.Name, options);
             * txNote.ChangeTypeId(tnt.Id);
             *
             * // Draw model lines of frames as notation
             * Plane Geomplane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero + transDict[i] + XYZ.BasisZ * (i - 1) * floorHeight);
             * SketchPlane sketch = SketchPlane.Create(doc, Geomplane);
             * CurveArray shatters = RegionDetect.PolyLineToCurveArray(frameDict[i], tolerance);
             * Transform alignModelLine = Transform.CreateTranslation(transDict[i] + XYZ.BasisZ * (i - 1) * floorHeight);
             * foreach (Curve shatter in shatters)
             * {
             *  Curve alignedCrv = shatter.CreateTransformed(alignModelLine);
             *  ModelCurve modelline = doc.Create.NewModelCurve(alignedCrv, sketch) as ModelCurve;
             * }
             */


            // ITERATION FLAG
            for (int i = 1; i <= levelCounter; i++)
            {
                pb.CustomizeStatus("On Floor " + i.ToString() + "... with lines", 5);
                if (pb.ProcessCancelled)
                {
                    return(Result.Cancelled);
                }

                TransactionGroup tg = new TransactionGroup(doc, "Generate on floor-" + i.ToString());
                {
                    try
                    {
                        tg.Start();

                        // MILESTONE
                        // Align the labels to the origin
                        Transform alignment = Transform.CreateTranslation(transDict[i]);
                        foreach (Util.TeighaText.CADTextModel label in textDict[i])
                        {
                            label.Location = label.Location + transDict[i];
                        }

                        // MILESTONE
                        // Sort out lines
                        List <Curve> wallCrvs   = new List <Curve>();
                        List <Curve> columnCrvs = new List <Curve>();
                        List <Curve> doorCrvs   = new List <Curve>();
                        List <Curve> windowCrvs = new List <Curve>();
                        foreach (GeometryObject go in geoDict[i])
                        {
                            var gStyle = doc.GetElement(go.GraphicsStyleId) as GraphicsStyle;
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerWall)
                            {
                                if (go.GetType().Name == "Line")
                                {
                                    Curve wallLine = go as Curve;
                                    wallCrvs.Add(wallLine.CreateTransformed(alignment) as Line);
                                }
                                if (go.GetType().Name == "PolyLine")
                                {
                                    CurveArray wallPolyLine_shattered = RegionDetect.PolyLineToCurveArray(go as PolyLine, tolerance);
                                    foreach (Curve crv in wallPolyLine_shattered)
                                    {
                                        wallCrvs.Add(crv.CreateTransformed(alignment) as Line);
                                    }
                                }
                            }
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerColumn)
                            {
                                if (go.GetType().Name == "Line")
                                {
                                    Curve columnLine = go as Curve;
                                    columnCrvs.Add(columnLine.CreateTransformed(alignment));
                                }
                                if (go.GetType().Name == "PolyLine")
                                {
                                    CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(go as PolyLine, tolerance);
                                    foreach (Curve crv in columnPolyLine_shattered)
                                    {
                                        columnCrvs.Add(crv.CreateTransformed(alignment));
                                    }
                                }
                            }
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerDoor)
                            {
                                Curve    doorCrv = go as Curve;
                                PolyLine poly    = go as PolyLine;
                                if (null != doorCrv)
                                {
                                    doorCrvs.Add(doorCrv.CreateTransformed(alignment));
                                }
                                if (null != poly)
                                {
                                    CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(poly, tolerance);
                                    foreach (Curve crv in columnPolyLine_shattered)
                                    {
                                        doorCrvs.Add(crv.CreateTransformed(alignment) as Line);
                                    }
                                }
                            }
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerWindow)
                            {
                                Curve    windowCrv = go as Curve;
                                PolyLine poly      = go as PolyLine;
                                if (null != windowCrv)
                                {
                                    windowCrvs.Add(windowCrv.CreateTransformed(alignment));
                                }
                                if (null != poly)
                                {
                                    CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(poly, tolerance);
                                    foreach (Curve crv in columnPolyLine_shattered)
                                    {
                                        windowCrvs.Add(crv.CreateTransformed(alignment) as Line);
                                    }
                                }
                            }
                        }

                        // MILESTONE
                        // Create additional levels (ignore what's present)
                        // Consider to use sub-transaction here
                        using (var t_level = new Transaction(doc))
                        {
                            t_level.Start("Create levels");
                            Level    floor     = Level.Create(doc, (i - 1) * floorHeight);
                            ViewPlan floorView = ViewPlan.Create(doc, viewType.Id, floor.Id);
                            floorView.Name = "F-" + i.ToString();
                            t_level.Commit();
                        }

                        // Grab the current building level
                        FilteredElementCollector colLevels = new FilteredElementCollector(doc)
                                                             .WhereElementIsNotElementType()
                                                             .OfCategory(BuiltInCategory.INVALID)
                                                             .OfClass(typeof(Level));
                        Level currentLevel = colLevels.LastOrDefault() as Level;
                        // The newly created level will append to the list,
                        // but this is not a safe choice

                        // Sub-transactions are packed within these functions.
                        // The family names should be defined by the user in WPF
                        // MILESTONE
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Walls", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        CreateWall.Execute(uiapp, wallCrvs, currentLevel, true);

                        // MILESTONE
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Columns", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        CreateColumn.Execute(app, doc, columnCrvs,
                                             Properties.Settings.Default.name_columnRect,
                                             Properties.Settings.Default.name_columnRound,
                                             currentLevel, true);

                        // MILESTONE
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Openings", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        CreateOpening.Execute(doc, doorCrvs, windowCrvs, wallCrvs, textDict[i],
                                              Properties.Settings.Default.name_door, Properties.Settings.Default.name_window, currentLevel, true);

                        // Create floor
                        // MILESTONE
                        var footprint = CreateRegion.Execute(doc, wallCrvs, columnCrvs, windowCrvs, doorCrvs);
                        using (var t_floor = new Transaction(doc))
                        {
                            t_floor.Start("Generate Floor");

                            Floor newFloor = doc.Create.NewFloor(footprint, floorType, currentLevel, false, XYZ.BasisZ);
                            newFloor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set(0);

                            t_floor.Commit();
                        }

                        // Generate rooms after the topology is established
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Rooms", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        // MILESTONE
                        using (var t_space = new Transaction(doc))
                        {
                            t_space.Start("Create rooms");

                            doc.Regenerate();

                            PlanTopology planTopology = doc.get_PlanTopology(currentLevel);
                            if (doc.ActiveView.ViewType == ViewType.FloorPlan)
                            {
                                foreach (PlanCircuit circuit in planTopology.Circuits)
                                {
                                    if (null != circuit && !circuit.IsRoomLocated)
                                    {
                                        Room room = doc.Create.NewRoom(null, circuit);
                                        room.LimitOffset = floorHeight;
                                        room.BaseOffset  = 0;
                                        string roomName = "";
                                        foreach (Util.TeighaText.CADTextModel label in textDict[i])
                                        {
                                            if (label.Layer == Properties.Settings.Default.layerSpace)
                                            {
                                                if (room.IsPointInRoom(label.Location + XYZ.BasisZ * (i - 1) * floorHeight))
                                                {
                                                    roomName += label.Text;
                                                }
                                            }
                                        }
                                        if (roomName != "")
                                        {
                                            room.Name = roomName;
                                        }
                                    }
                                }
                            }
                            t_space.Commit();
                        }



                        // Create roof when iterating to the last level
                        // MILESTONE
                        if (i == levelCounter)
                        {
                            using (var t_roof = new Transaction(doc))
                            {
                                t_roof.Start("Create roof");
                                Level    roofLevel = Level.Create(doc, i * floorHeight);
                                ViewPlan floorView = ViewPlan.Create(doc, viewType.Id, roofLevel.Id);
                                floorView.Name = "Roof";

                                ModelCurveArray footPrintToModelCurveMapping = new ModelCurveArray();
                                FootPrintRoof   footprintRoof = doc.Create.NewFootPrintRoof(footprint, roofLevel, roofType,
                                                                                            out footPrintToModelCurveMapping);

                                //ModelCurveArrayIterator iterator = footPrintToModelCurveMapping.ForwardIterator();

                                /*
                                 * iterator.Reset();
                                 * while (iterator.MoveNext())
                                 * {
                                 *  ModelCurve modelCurve = iterator.Current as ModelCurve;
                                 *  footprintRoof.set_DefinesSlope(modelCurve, true);
                                 *  footprintRoof.set_SlopeAngle(modelCurve, 0.5);
                                 * }
                                 */
                                t_roof.Commit();
                            }
                        }
                        tg.Assimilate();
                    }
                    catch
                    {
                        System.Windows.MessageBox.Show("Error", "Tips");
                        tg.RollBack();
                    }
                }
                pb.JobCompleted();
            }

            return(Result.Succeeded);
        }
示例#48
0
        public void QTO_2_PlaceHoldersFromDWFMarkups(
            Document doc,
            string activityId)
        {
            View activeView = doc.ActiveView;

            if (!(activeView is ViewSheet))
            {
                TaskDialog.Show("QTO",
                                "The current view must be a Sheet View with DWF markups");
                return;
            }

            ViewSheet vs = activeView as ViewSheet;

            Viewport vp = doc.GetElement(
                vs.GetAllViewports().First()) as Viewport;

            View plan = doc.GetElement(vp.ViewId) as View;

            int scale = vp.Parameters.Cast <Parameter>()
                        .First(x => x.Id.IntegerValue.Equals(
                                   (int)BuiltInParameter.VIEW_SCALE))
                        .AsInteger();

            IEnumerable <Element> dwfMarkups
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(ImportInstance))
                  .WhereElementIsNotElementType()
                  .Where(x => x.Name.StartsWith("Markup") &&
                         x.OwnerViewId.IntegerValue.Equals(
                             activeView.Id.IntegerValue));

            using (TransactionGroup tg = new TransactionGroup(doc))
            {
                tg.Start("DWF markups placeholders");

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("DWF Transfer");

                    plan.Parameters.Cast <Parameter>()
                    .First(x => x.Id.IntegerValue.Equals(
                               (int)BuiltInParameter.VIEWER_CROP_REGION))
                    .Set(1);

                    XYZ VC = (plan.CropBox.Min + plan.CropBox.Max) / 2;

                    XYZ BC = vp.GetBoxCenter();

                    t.RollBack();

                    foreach (Element e in dwfMarkups)
                    {
                        GeometryElement GeoElem = e.get_Geometry(new Options());

                        GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First();

                        GeometryElement gei = gi.GetSymbolGeometry();

                        IList <GeometryObject> gos = new List <GeometryObject>();

                        if (gei.Cast <GeometryObject>().Count(x => x is Arc) > 0)
                        {
                            continue;
                        }

                        foreach (GeometryObject go in gei)
                        {
                            XYZ med = new XYZ();

                            if (go is PolyLine)
                            {
                                PolyLine pl = go as PolyLine;

                                XYZ min = new XYZ(pl.GetCoordinates().Min(p => p.X),
                                                  pl.GetCoordinates().Min(p => p.Y),
                                                  pl.GetCoordinates().Min(p => p.Z));

                                XYZ max = new XYZ(pl.GetCoordinates().Max(p => p.X),
                                                  pl.GetCoordinates().Max(p => p.Y),
                                                  pl.GetCoordinates().Max(p => p.Z));

                                med = (min + max) / 2;
                            }

                            med = med - BC;

                            // Convert DWF sheet coordinates into model coordinates

                            XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0);
                        }
                    }

                    t.Start("DWF Transfer");

                    foreach (Element e in dwfMarkups)
                    {
                        GeometryElement GeoElem = e.get_Geometry(new Options());

                        GeometryInstance gi = GeoElem.Cast <GeometryInstance>().First();

                        GeometryElement gei = gi.GetSymbolGeometry();

                        IList <GeometryObject> gos = new List <GeometryObject>();

                        if (gei.Cast <GeometryObject>().Count(x => x is Arc) == 0)
                        {
                            continue;
                        }

                        foreach (GeometryObject go in gei)
                        {
                            if (go is Arc)
                            {
                                Curve c = go as Curve;

                                XYZ med = c.Evaluate(0.5, true);

                                med = med - BC;

                                XYZ a = VC + new XYZ(med.X * scale, med.Y * scale, 0);

                                // Warning CS0618:
                                // Autodesk.Revit.Creation.ItemFactoryBase.NewTextNote(
                                //   View, XYZ, XYZ, XYZ, double, TextAlignFlags, string)
                                // is obsolete:
                                // This method is deprecated in Revit 2016.
                                // Please use one of the TextNote.Create methods instead.

                                //doc.Create.NewTextNote( plan,
                                //                       a,
                                //                       XYZ.BasisX,
                                //                       XYZ.BasisY,
                                //                       MMtoFeet( 5 ),
                                //                       TextAlignFlags.TEF_ALIGN_CENTER,
                                //                       activityId );

                                ElementId textTypeId = new FilteredElementCollector(doc)
                                                       .OfClass(typeof(TextNoteType))
                                                       .FirstElementId();

                                TextNote.Create(doc, plan.Id, a, activityId, textTypeId);
                            }
                        }

                        t.Commit();
                    }
                }

                tg.Assimilate();
            }
        }
示例#49
0
        private void button2DCreate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List <RoomProperties> roomList = (List <RoomProperties>)dataGridRoom.ItemsSource;
                var selectedRooms = from room in roomList where room.IsSelected select room;

                if (selectedRooms.Count() > 0)
                {
                    statusLable.Text       = "Creating 2D Masses ..";
                    progressBar.Visibility = System.Windows.Visibility.Visible;
                    progressBar.Value      = 0;
                    progressBar.Maximum    = selectedRooms.Count();

                    bool createdParamMaps = (massConfig.UpdateType != ParameterUpdateType.None && massConfig.MassParameters.Count > 0) ? true : false;

                    UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);
                    using (TransactionGroup tg = new TransactionGroup(m_doc))
                    {
                        tg.Start("Create 2D Masses");
                        try
                        {
                            double count = 0;
                            foreach (RoomProperties rp in selectedRooms)
                            {
                                using (Transaction trans = new Transaction(m_doc))
                                {
                                    trans.Start("Create 2D Mass");
                                    var options = trans.GetFailureHandlingOptions();
                                    options.SetFailuresPreprocessor(new DuplicateWarningSwallower());
                                    trans.SetFailureHandlingOptions(options);

                                    try
                                    {
                                        MassProperties createdMass = null;
                                        if (MassCreator.CreateRoomFace(m_doc, rp, out createdMass))
                                        {
                                            if (roomDictionary.ContainsKey(rp.RoomUniqueId))
                                            {
                                                RoomProperties updatedRoom = new RoomProperties(rp);
                                                updatedRoom.IsSelected   = false;
                                                updatedRoom.Linked2d     = true;
                                                updatedRoom.Linked2dMass = createdMass;
                                                updatedRoom.ModifiedHost = false;
                                                if (updatedRoom.Linked3d && null != updatedRoom.Linked3dMass)
                                                {
                                                    updatedRoom.ToolTip  = "Mass 3D Id: " + updatedRoom.Linked3dMass.MassId;
                                                    updatedRoom.ToolTip += "\nMass 2D Id: " + updatedRoom.Linked2dMass.MassId;
                                                }
                                                else
                                                {
                                                    updatedRoom.ToolTip = "Mass 2D Id: " + updatedRoom.Linked2dMass.MassId;
                                                }

                                                if (createdParamMaps)
                                                {
                                                    bool parameterUpdated = UpdateParameter(rp.RoomElement, createdMass.MassElement);
                                                }
                                                roomDictionary.Remove(rp.RoomUniqueId);
                                                roomDictionary.Add(rp.RoomUniqueId, updatedRoom);
                                            }
                                        }
                                        trans.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        trans.RollBack();
                                        string message = ex.Message;
                                    }
                                }

                                count++;
                                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, count });
                            }

                            DisplayRoomInfo();
                            tg.Assimilate();
                        }
                        catch (Exception ex)
                        {
                            tg.RollBack();
                            MessageBox.Show("Failed to create masses from the selected rooms\n" + ex.Message, "Create 3D Masses from Rooms", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }

                    progressBar.Visibility = System.Windows.Visibility.Hidden;
                    statusLable.Text       = "Ready";
                }
                else
                {
                    MessageBox.Show("Please select rooms to update masses.", "Select Rooms", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create 2d masses from the selected rooms.\n" + ex.Message, "Create 2D Masses from Rooms", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
示例#50
0
        /// <summary>
        /// add node to tree view control
        /// </summary>
        /// <param name="type">indicate operation type</param>
        /// <param name="info">tree node text</param>
        private void AddNode(OperationType type, string info)
        {
            //add tree node according to operation type
            if (type == OperationType.StartTransactionGroup)
            {
                if (m_transGroupNode == null)
                {
                    m_transGroupNode = new TreeNode(m_transactionGroup.GetName());
                    int index = m_rootNode.Nodes.Add(m_transGroupNode);
                    m_rootNode.Nodes[index].Tag = m_transactionGroup;
                    m_rootNode.Expand();
                    UpdateTreeNode(m_transGroupNode, type);
                }
                else
                {
                    TreeNode newTransGroupNode = new TreeNode(m_transactionGroup.GetName());
                    int index = m_transGroupNode.Nodes.Add(newTransGroupNode);
                    m_transGroupNode.Nodes[index].Tag = m_transactionGroup;
                    m_transGroupNode.Expand();
                    m_transGroupNode = newTransGroupNode;
                    m_transGroupNode.Expand();
                    UpdateTreeNode(m_transGroupNode, type);
                }
                m_transNode = null;
                m_transaction = null;
            }
            else if (type == OperationType.RollbackTransactionGroup)
            {
                UpdateTreeNode(m_transGroupNode, type);
                if (m_transGroupNode.Parent.Equals(m_rootNode))
                {
                    m_rootNode.Expand();
                    m_transactionGroup = null;
                    m_transGroupNode = null;
                }
                else
                {
                    m_transGroupNode = m_transGroupNode.Parent;
                    m_transGroupNode.Expand();
                    m_transactionGroup = m_transGroupNode.Tag as TransactionGroup;
                }
                m_transNode = null;
                m_transaction = null;
            }
            else if (type == OperationType.CommitTransactionGroup)
            {
                UpdateTreeNode(m_transGroupNode, type);
                if (m_transGroupNode.Parent.Equals(m_rootNode))
                {
                    m_rootNode.Expand();
                    m_transactionGroup = null;
                    m_transGroupNode = null;
                }
                else
                {
                    m_transGroupNode.Expand();
                    m_transGroupNode = m_transGroupNode.Parent;
                    m_transactionGroup = m_transGroupNode.Tag as TransactionGroup;
                }
                m_transNode = null;
                m_transaction = null;
            }
            else if (type == OperationType.StartTransaction)
            {
                m_transNode = new TreeNode(m_transaction.GetName());
                m_transNode.ForeColor = m_startedColor;
                TreeNode node = m_transGroupNode == null ? m_rootNode : m_transGroupNode;
                node.Nodes.Add(m_transNode);
                node.Expand();
                UpdateTreeNode(m_transNode, type);
            }
            else if (type == OperationType.CommitTransaction)
            {
                UpdateTreeNode(m_transNode, type);
                TreeNode node = m_transGroupNode == null ? m_rootNode : m_transGroupNode;
                node.Expand();
                m_transNode = null;
            }
            else if (type == OperationType.RollbackTransaction)
            {
                UpdateTreeNode(m_transNode, type);
                TreeNode node = m_transGroupNode == null ? m_rootNode : m_transGroupNode;
                node.Expand();
                m_transNode = null;
            }
            else
            {
                string childNodeText = null;

                if (String.IsNullOrEmpty(info))
                {
                    childNodeText = "Operation";
                }
                else
                {
                    childNodeText = info;
                }

                TreeNode childNode = new TreeNode(childNodeText);
                if (type == OperationType.ObjectDeletion)
                   childNode.ForeColor = m_deletedColor;
                else
                   childNode.ForeColor = m_normalColor;
                m_transNode.Nodes.Add(childNode);
                m_transNode.Expand();
            }
        }
示例#51
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            app = commandData.Application.Application;
            doc = uidoc.Document;
            //Reference refer = uidoc.Selection.PickObject(ObjectType.Element, "Select a CAD Link");
            //Element elem = doc.GetElement(refer);
            //GeometryElement geoElem = elem.get_Geometry(new Options());



            Reference r  = uidoc.Selection.PickObject(ObjectType.PointOnElement);
            string    ss = r.ConvertToStableRepresentation(doc);



            Element         elem    = doc.GetElement(r);
            GeometryElement geoElem = elem.get_Geometry(new Options());
            GeometryObject  geoObj  = elem.GetGeometryObjectFromReference(r);


            //获取选中的cad图层
            Category  targetCategory  = null;
            ElementId graphicsStyleId = null;


            if (geoObj.GraphicsStyleId != ElementId.InvalidElementId)
            {
                graphicsStyleId = geoObj.GraphicsStyleId;
                GraphicsStyle gs = doc.GetElement(geoObj.GraphicsStyleId) as GraphicsStyle;
                if (gs != null)
                {
                    targetCategory = gs.GraphicsStyleCategory;
                    var name = gs.GraphicsStyleCategory.Name;
                }
            }
                        //隐藏选中的cad图层
                        Transaction trans = new Transaction(doc, "隐藏图层");

            trans.Start();
            if (targetCategory != null)
            {
                doc.ActiveView.SetVisibility(targetCategory, false);
            }


            trans.Commit();



            TransactionGroup transGroup = new TransactionGroup(doc, "绘制模型线");

            transGroup.Start();
            CurveArray curveArray = new CurveArray();


            //判断元素类型
            foreach (var gObj in geoElem)
            {
                GeometryInstance geomInstance = gObj as GeometryInstance;
                                //坐标转换。如果选择的是“自动-中心到中心”,或者移动了importInstance,需要进行坐标转换
                                Transform transform = geomInstance.Transform;


                if (null != geomInstance)
                {
                    foreach (var insObj in geomInstance.SymbolGeometry)
                    {
                        if (insObj.GraphicsStyleId.IntegerValue != graphicsStyleId.IntegerValue)
                        {
                            continue;
                        }


                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.NurbSpline")
                        {
                                                        //未实现
                                                   
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Line")
                        {
                            Line line   = insObj as Line;
                            XYZ  normal = XYZ.BasisZ;
                            XYZ  point  = line.GetEndPoint(0);
                            point = transform.OfPoint(point);


                            curveArray.Append(TransformLine(transform, line));


                            CreateModelCurveArray(curveArray, normal, point);
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Arc")
                        {
                                                        //未实现
                                                   
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.PolyLine")
                        {
                            PolyLine    polyLine = insObj as PolyLine;
                            IList <XYZ> points   = polyLine.GetCoordinates();


                            for (int i = 0; i < points.Count - 1; i++)
                            {
                                Line line = Line.CreateBound(points[i], points[i + 1]);
                                line = TransformLine(transform, line);
                                curveArray.Append(line);
                            }


                            XYZ normal = XYZ.BasisZ;
                            XYZ point  = points.First();
                            point = transform.OfPoint(point);


                            CreateModelCurveArray(curveArray, normal, point);
                        }
                    }
                }
            }
            transGroup.Assimilate();



            return(Result.Succeeded);
        }
示例#52
0
        /// <summary>
        /// Commit or rollback nested transaction groups
        /// </summary>
        /// <param name="operationType">The operation type determines whether to commit or to rollback transaction groups</param>
        private void HandleNestedTransactionGroups(OperationType operationType)
        {
            while (m_transactionGroup != null)
            {
                if (operationType.Equals(OperationType.CommitTransactionGroup))
                {
                    m_transactionGroup.Commit();
                }
                else
                {
                    m_transactionGroup.RollBack();
                }

                if (m_transactionGroup.HasEnded())
                {
                    m_transGroupNode = m_transGroupNode.Parent;
                    if (m_transGroupNode.Equals(m_rootNode))
                    {
                        m_transactionGroup = null;
                    }
                    else
                    {
                        m_transactionGroup = m_transGroupNode.Tag as TransactionGroup;
                    }
                }
                else
                {
                    throw new System.ApplicationException("Could not end a transaction group");
                }
            }
        }
示例#53
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            m_app = commandData.Application;
            m_doc = m_app.ActiveUIDocument.Document;
            Log.AppendLog(LogMessageType.INFO, "Started");

            // (Konrad) We are gathering information about the addin use. This allows us to
            // better maintain the most used plug-ins or discontiue the unused ones.
            AddinUtilities.PublishAddinLog(new AddinLog("Utilities-RoomMeasure", commandData.Application.Application.VersionNumber));

            try
            {
                var collector = new FilteredElementCollector(m_doc);
                var rooms     = collector.OfCategory(BuiltInCategory.OST_Rooms).ToElements().Cast <Room>().ToList();
                if (rooms.Count > 0)
                {
                    var sampleRoom = rooms.First();
                    if (MeasureUtil.ExistRoomParameter(sampleRoom))
                    {
                        using (var tg = new TransactionGroup(m_doc))
                        {
                            tg.Start("Calculate Rooms");
                            try
                            {
                                var roomCount = 0;
                                foreach (var room in rooms)
                                {
                                    if (room.Area == 0)
                                    {
                                        continue;
                                    }
                                    using (var trans = new Transaction(m_doc))
                                    {
                                        double width  = 0;
                                        double length = 0;

                                        var directShapeId       = ElementId.InvalidElementId;
                                        var perpendicularSwitch = false;
                                        trans.Start("Create Room DirecShape");
                                        try
                                        {
                                            var directShape = MeasureUtil.CreateRoomDirectShape(room);
                                            if (null != directShape)
                                            {
                                                directShapeId = directShape.Id;
                                                MeasureUtil.RotateDirectShape(directShape, room, out perpendicularSwitch);
                                            }
                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            trans.RollBack();
                                            var exMsg = ex.Message;
                                        }

                                        trans.Start("Calculate Dimension");
                                        try
                                        {
                                            var directShape = m_doc.GetElement(directShapeId) as DirectShape;
                                            if (null != directShape)
                                            {
                                                MeasureUtil.CalculateWidthAndLength(directShape, out width, out length);
                                            }
                                            m_doc.Delete(directShapeId);
                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            trans.RollBack();
                                            var exMsg = ex.Message;
                                        }

                                        trans.Start("Set Parameter");
                                        try
                                        {
                                            if (perpendicularSwitch)
                                            {
                                                var tempVal = width;
                                                width  = length;
                                                length = tempVal;
                                            }
                                            var param = room.LookupParameter(roomWidthParamName);
                                            param?.Set(width);
                                            param = room.LookupParameter(roomLengthParamName);
                                            param?.Set(length);


                                            trans.Commit();
                                        }
                                        catch (Exception ex)
                                        {
                                            trans.RollBack();
                                            var exMsg = ex.Message;
                                        }
                                        roomCount++;
                                    }
                                }
                                tg.Assimilate();
                                MessageBox.Show("Parameters [Room Width] and [Room Length] have been updated in " + roomCount + " rooms.", "Successfully Completed!", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            catch (Exception ex)
                            {
                                tg.RollBack();
                                MessageBox.Show("Failed to measure the width and length of rooms.\n" + ex.Message, "Measuring Rooms", MessageBoxButton.OK, MessageBoxImage.Warning);
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Room doesn't exist in the current project.", "Room Not Found", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                Log.AppendLog(LogMessageType.EXCEPTION, ex.Message);
            }

            Log.AppendLog(LogMessageType.INFO, "Ended");
            return(Result.Succeeded);
        }