Example #1
2
        /// <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,
                                             ElementSet elements)
        {
            m_app = commandData.Application.Application;
             MessageManager.MessageBuff = new StringBuilder();

             try
             {
            bool succeeded = LoadFamiliesAndAddParameters();

            if (succeeded)
            {
               return Autodesk.Revit.UI.Result.Succeeded;
            }
            else
            {
               message = MessageManager.MessageBuff.ToString();
               return Autodesk.Revit.UI.Result.Failed;
            }
             }
             catch (Exception e)
             {
            message = e.Message;
            return Autodesk.Revit.UI.Result.Failed;
             }
        }
Example #2
1
        /// <summary>
        /// Command Entry Point
        /// </summary>
        /// <param name="commandData">Input argument providing access to the Revit application and documents</param>
        /// <param name="message">Return message to the user in case of error or cancel</param>
        /// <param name="elements">Return argument to highlight elements on the graphics screen if Result is not Succeeded.</param>
        /// <returns>Cancelled, Failed or Succeeded</returns>
        public Result Execute(ExternalCommandData commandData,
                            ref string message,
                            ElementSet elements)
        {
            m_app = commandData.Application;

              try
              {
            bool succeeded = AddParameters();

            if (succeeded)
            {
              MessageBox.Show("Done. Binding Shared Parameters Succeeded.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
              return Autodesk.Revit.UI.Result.Succeeded;
            }
            else
            {
              MessageBox.Show("Failed", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
              return Autodesk.Revit.UI.Result.Failed;
            }
              }
              catch (Exception ex)
              {
            // Failure Message
            message = ex.Message;
            return Result.Failed;
              }
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref String message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              Document doc = app.ActiveUIDocument.Document;

              ViewSheet currentSheet
            = doc.ActiveView as ViewSheet;

              foreach( View v in currentSheet.Views )
              {
            // the values returned here do not seem to
            // accurately reflect the positions of the
            // views on the sheet:

            BoundingBoxUV loc = v.Outline;

            Debug.Print(
              "Coordinates of {0} view '{1}': {2}",
              v.ViewType, v.Name,
              Util.PointString( loc.Min ) );
              }

              return Result.Failed;
        }
    public Result Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements)
    {
      // Get the access to the top most objects. 
      UIApplication uiApp = commandData.Application;
      UIDocument uiDoc = uiApp.ActiveUIDocument;
      _app = uiApp.Application;
      _doc = uiDoc.Document;

      // (1) In eailer lab, CommandData command, we 
      // learned how to access to the wallType. i.e., 
      // here we'll take a look at more on the topic 
      // of accessing to elements in the interal rvt 
      // project database. 

      ListFamilyTypes();

      // (2) List instances of specific object class. 
      ListInstances();

      // (3) Find a specific family type. 
      FindFamilyType();

      // (4) Find specific instances, including filtering by parameters. 
      FindInstance();

      // (5) List all elements. 
      ListAllElements();

      // We are done. 

      return Result.Succeeded;
    }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;

              //PickPointsForArea( uidoc );

              XYZ point_in_3d;

              if( PickFaceSetWorkPlaneAndPickPoint(
            uidoc, out point_in_3d ) )
              {
            TaskDialog.Show( "3D Point Selected",
              "3D point picked on the plane"
              + " defined by the selected face: "
              + Util.PointString( point_in_3d ) );

            return Result.Succeeded;
              }
              else
              {
            message = "3D point selection cancelled or failed";
            return Result.Failed;
              }
        }
Example #6
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Initialize();
            CommandData = commandData;
            //Login
            using(var login = new LoginForm())
            {
                login.ShowDialog();
                if(login.DialogResult == DialogResult.OK)
                {
                    Indexer = new RevitFamilyIndexer(CommandData);
                    var path = Assembly.GetExecutingAssembly().Location;
                    const string str = "CDWKS.RevitAddon.Indexer2012.dll";
                    var str1 = path.Substring(0, path.Length - str.Length);
                    var args = InstanceId.ToString() + " 2012";
                    var oProcess = Process.Start(str1 + "CDWKS.RevitAddOn.ProgressMonitor.exe", args);

                    while (oProcess != null && !oProcess.HasExited)
                    {
                        if (CanIndex())
                        {
                            IndexNext();
                        }
                    }
                }
            }

            return Result.Succeeded;
        }
Example #7
0
        GetAllSheets (Document doc)
        {
            ElementSet allSheets = new ElementSet();
            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter elementsAreWanted = new ElementClassFilter(typeof(ViewSheet));
            fec.WherePasses(elementsAreWanted);
            List<Element> elements = fec.ToElements() as List<Element>;

            foreach (Element element in elements)
            {
               ViewSheet viewSheet = element as ViewSheet;

               if (null == viewSheet)
               {
                  continue;
               }
               else
               {
                  ElementId objId = viewSheet.GetTypeId();
                  if (ElementId.InvalidElementId == objId)
                  {
                     continue;
                  }
                  else
                  {
                     allSheets.Insert(viewSheet);
                  }
               }
            }

            return allSheets;
        }
Example #8
0
 public RevitScriptContext(ExternalCommandData commandData, ref string message, ElementSet elements, string scriptName)
 {
     _commandData = commandData;
     _message = message;
     _elements = elements;
     _scriptName = scriptName;
 }
Example #9
0
   public Result Execute(
 ExternalCommandData commandData,
 ref string message,
 ElementSet elements )
   {
       return Result.Succeeded;
   }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              UIDocument uidoc = app.ActiveUIDocument;
              Document doc = uidoc.Document;

              List<Element> rooms = new List<Element>();
              if( !Util.GetSelectedElementsOrAll(
            rooms, uidoc, typeof( Room ) ) )
              {
            Selection sel = uidoc.Selection;
            message = ( 0 < sel.GetElementIds().Count )
              ? "Please select some room elements."
              : "No room elements found.";
            return Result.Failed;
              }
              foreach( Room room in rooms )
              {
            BumpOccupancy( room );
              }
              return Result.Succeeded;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              UIDocument uidoc = app.ActiveUIDocument;
              Document doc = uidoc.Document;

              Selection sel = uidoc.Selection;
              string msg = string.Empty;

              foreach( Element e in sel.Elements )
              {
            Wall wall = e as Wall;
            if( null != wall )
            {
              msg += ProcessWall( wall );
            }
              }
              if( 0 == msg.Length )
              {
            msg = "Please select some walls.";
              }
              Util.InfoMsg( msg );
              return Result.Succeeded;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              UIDocument uidoc = app.ActiveUIDocument;
              Document doc = uidoc.Document;

              List<Element> rooms = new List<Element>();
              if( !Util.GetSelectedElementsOrAll(
            rooms, uidoc, typeof( Room ) ) )
              {
            Selection sel = uidoc.Selection;
            message = ( 0 < sel.Elements.Size )
              ? "Please select some room elements."
              : "No room elements found.";
            return Result.Failed;
              }
              foreach( Room room in rooms )
              {
            DetermineAdjacentElementLengthsAndWallAreas(
              room );
              }
              return Result.Failed;
        }
        public Result Execute(
          ExternalCommandData commandData,
          ref string message,
          ElementSet elements)
        {
            // Get application and document objects
            UIApplication uiApp = commandData.Application;
            Document doc = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            try
            {
                if (!doc.IsWorkshared)
                {
                    TaskDialog.Show("Workset 3D View", "Project doesn't have any Worksets.");
                }
                else
                {
                    ViewFamilyType vft = new FilteredElementCollector(doc)
                    .OfClass(typeof(ViewFamilyType))
                    .Cast<ViewFamilyType>()
                    .FirstOrDefault(q => q.ViewFamily == ViewFamily.ThreeDimensional);

                    using (Transaction t = new Transaction(doc, "Workset View Creation"))
                    {
                        t.Start();
                        int i = 0;
                        // Loop through all User Worksets only
                        foreach (Workset wst in new FilteredWorksetCollector(doc)
                            .WherePasses(new WorksetKindFilter(WorksetKind.UserWorkset)))
                        {
                            // Create a 3D View
                            View3D view = View3D.CreateIsometric(doc, vft.Id);

                            // Set the name of the view to match workset
                            view.Name = "WORKSET - " + wst.Name;

                            // Isolate elements in the view using a filter to find elements only in this workset
                            view.IsolateElementsTemporary(new FilteredElementCollector(doc)
                                .WherePasses(new ElementWorksetFilter(wst.Id))
                                .Select(q => q.Id)
                                .ToList());
                            i++;
                        }
                        t.Commit();
                        TaskDialog.Show("Workset 3D View", i.ToString() + " Views Created Successfully!");
                    }
                }
                return Result.Succeeded;
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return Result.Cancelled;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return Result.Failed;
            }
        }
Example #14
0
        public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            SelElementSet selSet = commandData.Application.ActiveDocument.Selection.Elements;
            if (selSet.Size != 1)
            {
                return IExternalCommand.Result.Cancelled;
            }
            ElementSetIterator it = selSet.ForwardIterator();
            if (it.MoveNext())
            {
                Room room = it.Current as Room;
                if (room != null)
                {
                    ParameterSetIterator paraIt = room.Parameters.ForwardIterator();
                    while (paraIt.MoveNext())
                    {
                        Parameter para = paraIt.Current as Parameter;
                        if (para == null) continue;
                        if (para.Definition.Name.Equals("名称"))
                        {
                            para.Set("My Room");
                            break;
                        }
                    }
                }
            }

            return IExternalCommand.Result.Succeeded;
        }
Example #15
0
 public Result Execute( Autodesk.Revit.UI.ExternalCommandData cmdData, ref string msg, ElementSet elems )
 {
   TaskDialog helloDlg = new TaskDialog( "Autodesk Revit" );
   helloDlg.MainContent = "Hello World from " + System.Reflection.Assembly.GetExecutingAssembly().Location;
   helloDlg.Show();
   return Result.Cancelled;
 }
        public Result Execute(
            ExternalCommandData commandData,
            ref String message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              Document doc = app.ActiveUIDocument.Document;

              ViewSheet currentSheet
            = doc.ActiveView as ViewSheet;

              //foreach( View v in currentSheet.Views ) // 2014 warning	'Autodesk.Revit.DB.ViewSheet.Views' is obsolete.  Use GetAllPlacedViews() instead.

              foreach( ElementId id in currentSheet.GetAllPlacedViews() ) // 2015
              {
            View v = doc.GetElement( id ) as View;

            // the values returned here do not seem to
            // accurately reflect the positions of the
            // views on the sheet:

            BoundingBoxUV loc = v.Outline;

            Debug.Print(
              "Coordinates of {0} view '{1}': {2}",
              v.ViewType, v.Name,
              Util.PointString( loc.Min ) );
              }

              return Result.Failed;
        }
        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;

              Transaction tx = new Transaction( doc,
            "Extract Part Atom" );

              tx.Start();

              string familyFilePath
            = "C:/Documents and Settings/All Users"
            + "/Application Data/Autodesk/RAC 2011"
            + "/Metric Library/Doors/M_Double-Flush.rfa";

              string xmlPath = "C:/tmp/ExtractPartAtom.xml";

              app.ExtractPartAtomFromFamilyFile(
            familyFilePath, xmlPath );

              tx.Commit();

              return Result.Succeeded;
        }
        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;

              // 'Autodesk.Revit.DB.Document.Mirror(ElementSet, Line)' is obsolete:
              // Use one of the replace methods in ElementTransformUtils.
              //
              //Line line = app.Create.NewLine(
              //  XYZ.Zero, XYZ.BasisX, true ); // 2011
              //
              //ElementSet els = uidoc.Selection.Elements; // 2011
              //
              //doc.Mirror( els, line ); // 2011

              Plane plane = new Plane( XYZ.BasisY, XYZ.Zero ); // 2012

              ICollection<ElementId> elementIds
            = uidoc.Selection.GetElementIds(); // 2012

              ElementTransformUtils.MirrorElements(
            doc, elementIds, plane ); // 2012

              return Result.Succeeded;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Document doc = commandData.Application
            .ActiveUIDocument.Document;

              FilteredElementCollector collector
            = new FilteredElementCollector( doc );

              collector.OfClass( typeof( Level ) );
              Level level = collector.FirstElement() as Level;

              Transaction t = new Transaction( doc );

              t.Start( "Create unbounded room" );

              FailureHandlingOptions failOpt
            = t.GetFailureHandlingOptions();

              failOpt.SetFailuresPreprocessor(
            new RoomWarningSwallower() );

              t.SetFailureHandlingOptions( failOpt );

              doc.Create.NewRoom( level, new UV( 0, 0 ) );

              t.Commit();

              return Result.Succeeded;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            var dialog = new TaskDialog( "Create DirectShape" )
              {
            MainInstruction = "Select the way you want to create shape"
              };

              dialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink1, "Initial shape builder" );
              dialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink2, "Jeremy's shape builder" );
              dialog.AddCommandLink( TaskDialogCommandLinkId.CommandLink3, "Simple shape builder" );

              switch( dialog.Show() )
              {
            case TaskDialogResult.CommandLink1:
              CreateDirectShapeInitial.Execute1( commandData );
              break;

            case TaskDialogResult.CommandLink2:
              CreateDirectShape.Execute( commandData );
              break;

            case TaskDialogResult.CommandLink3:
              CreateDirectShapeSimple.Execute( commandData );
              break;
              }
              return Result.Succeeded;
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              Application app = uiapp.Application;

              if( null == _handler )
              {
            _handler
              = new EventHandler<DocumentChangedEventArgs>(
            OnDocumentChanged );

            // Subscribe to DocumentChanged event

            app.DocumentChanged += _handler;
              }
              else
              {
            app.DocumentChanged -= _handler;
            _handler = null;
              }
              return Result.Succeeded;
        }
        public Result Execute(ExternalCommandData cmdData, ref string message, ElementSet elements)
        {
            Setup(cmdData);

            var exe = new RevitTestExecutive();
            return exe.Execute(cmdData, ref message, elements);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              UIDocument uidoc = app.ActiveUIDocument;
              Document doc = uidoc.Document;

              string msg = string.Empty;

              //Selection sel = uidoc.Selection; // 2014
              //foreach( Element e in sel.Elements ) // 2014

              List<Element> walls = new List<Element>();

              if( Util.GetSelectedElementsOrAll( walls, uidoc, typeof( Wall ) ) )
              {
            foreach( Wall wall in walls )
            {
              msg += ProcessWall( wall );
            }
              }

              if( 0 == msg.Length )
              {
            msg = "Please select some walls.";
              }

              Util.InfoMsg( msg );

              return Result.Succeeded;
        }
        /// <summary>
        /// Overload this method to implement and external command within Revit.
        /// </summary>
        /// <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>
        /// <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>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // FIXME: somehow fetch back message after script execution...
            var executor = new ScriptExecutor(commandData, message, elements);

            string source;
            using (var reader = File.OpenText(_scriptSource))
            {
                source = reader.ReadToEnd();
            }

            var result = executor.ExecuteScript(source);
            message = executor.Message;
            switch (result)
            {
                case (int)Result.Succeeded:
                    return Result.Succeeded;
                case (int)Result.Cancelled:
                    return Result.Cancelled;
                case (int)Result.Failed:
                    return Result.Failed;
                default:
                    return Result.Succeeded;
            }
        }
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
                                               ref string message,
                                               ElementSet elements)
        {
            if (null == commandData.Application.ActiveUIDocument.Document)
            {
                message = "Active document is null.";
                return Result.Failed;
            }

            try
            {
                var creator = new FamilyInstanceCreator(commandData.Application);

                var importer = new PSDataImporter(creator);

                importer.StartImport();

                return Autodesk.Revit.UI.Result.Succeeded;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return Autodesk.Revit.UI.Result.Failed;
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                // Find all of the runs and organize them
                doc = commandData.Application.ActiveUIDocument.Document;
                allRuns = FindExisting();
                
                if (allRuns != null && allRuns.Count > 0)
                {
                    RevitServerApp._app.ShowSelectionForm(allRuns, commandData.Application.ActiveUIDocument);
                }
                else
                {
                    TaskDialog.Show("Message", "No existing run elements found.");
                }

                return Result.Succeeded;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error", ex.Message);
                return Result.Failed;
            }
        }
Example #27
0
        /// <summary>
        /// Command Entry Point
        /// </summary>
        /// <param name="commandData">Input argument providing access to the Revit application and documents</param>
        /// <param name="message">Return message to the user in case of error or cancel</param>
        /// <param name="elements">Return argument to highlight elements on the graphics screen if Result is not Succeeded.</param>
        /// <returns>Cancelled, Failed or Succeeded</returns>
        public Result Execute(ExternalCommandData commandData,
                            ref string message,
                            ElementSet elements)
        {
            try
              {

            // Version
            if (!commandData.Application.Application.VersionName.Contains("2013"))
            {
              message = "This Add-In was built for Revit 2013, please contact CASE for assistance...";
              return Result.Failed;
            }

            // Construct and Display the form
            form_Main frm = new form_Main(commandData);
            frm.ShowDialog();

            // Return Success
            return Result.Succeeded;
              }
              catch (Exception ex)
              {

            // Failure Message
            message = ex.Message;
            return Result.Failed;

              }
        }
        public Result Execute(
            ExternalCommandData revit,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = revit.Application;
              UIDocument uidoc = uiapp.ActiveUIDocument;
              Document doc = uidoc.Document;

              string path = doc.PathName;

              BasicFileInfo info = BasicFileInfo.Extract(
            path );

              DocumentVersion v = info.GetDocumentVersion();

              int n = v.NumberOfSaves;

              Util.InfoMsg( string.Format(
            "Document '{0}' has GUID {1} and {2} save{3}.",
            path, v.VersionGUID, n,
            Util.PluralSuffix( n ) ) );

              return Result.Succeeded;
        }
        public static void beginCommand(Document doc, string strDomain, bool bForAllSystems = false, bool bFitlerUnCalculationSystems = false)
        {
            PressureLossReportHelper helper = PressureLossReportHelper.instance;
             UIDocument uiDocument = new UIDocument(doc);
             if (bFitlerUnCalculationSystems)
             {
            ElementSet calculationOnElems = new ElementSet();
            int nTotalCount = getCalculationElemSet(doc, strDomain, calculationOnElems, uiDocument.Selection.Elements);

            if (calculationOnElems.Size == 0)
            {//No item can be calculated
               popupWarning(ReportResource.allItemsCaculationOff, TaskDialogCommonButtons.Close, TaskDialogResult.Close);
               return;
            }
            else if (calculationOnElems.Size < nTotalCount)
            {//Part of them can be calculated
               if (popupWarning(ReportResource.partOfItemsCaculationOff, TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes, TaskDialogResult.Yes) == TaskDialogResult.No)
                  return;
            }

            helper.initialize(doc, calculationOnElems, strDomain);
            invokeCommand(doc, helper, bForAllSystems);
             }
             else
             {
            helper.initialize(doc, uiDocument.Selection.Elements, strDomain);
            invokeCommand(doc, helper, bForAllSystems);
             }
        }
Example #30
0
 /// <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(Autodesk.Revit.UI.ExternalCommandData commandData,
                                        ref string message,
                                        ElementSet elements)
 {
     try
     {
         Transaction documentTransaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Document");
         documentTransaction.Start();
         using (SpotDimensionInfoDlg infoForm = new SpotDimensionInfoDlg(commandData))
         {
             //Highlight the selected spotdimension
             if (infoForm.ShowDialog() == System.Windows.Forms.DialogResult.OK
                 && infoForm.SelectedSpotDimension != null)
             {
                 elements.Insert(infoForm.SelectedSpotDimension);
                 message = "High light the selected SpotDimension";
                 return Autodesk.Revit.UI.Result.Failed;
             }
         }
         documentTransaction.Commit();
         return Autodesk.Revit.UI.Result.Succeeded;
     }
     catch (Exception ex)
     {
        // If there are something wrong, give error information and return failed
        message = ex.Message;
        return Autodesk.Revit.UI.Result.Failed;
     }
 }
Example #31
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            WindowsFormsApplication1.DBConnection DB = new WindowsFormsApplication1.DBConnection();

            string          sql            = "SELECT * FROM edilizia.users;";
            MySqlDataReader dataReaderInfo = DB.GetData(sql);

            if (dataReaderInfo.HasRows)
            {
                DataTable dtInfo = new DataTable();
                dtInfo.Load(dataReaderInfo);
                TaskDialog.Show("Revit", dtInfo.Rows[0][1].ToString());
                //lblLocal.Text = "Oficina: " + dtInfo.Rows[0][0].ToString();
                //lblResponsable.Text = "Dueño: " + dtInfo.Rows[0][1].ToString();
                //lblActivos.Text = "Cant. Bienes: " + dtInfo.Rows[0][2].ToString();
                //IdRoomSelected = int.Parse(dtInfo.Rows[0][3].ToString());
            }

            TaskDialog.Show("Revit", "Hola entorno!");
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
    public Result Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements)
    {
      UIApplication app = commandData.Application;
      UIDocument uidoc = app.ActiveUIDocument;
      Document doc = uidoc.Document;
      Selection sel = uidoc.Selection;
      ICollection<ElementId> ids = sel.GetElementIds();
      Options opt = app.Application.Create.NewGeometryOptions();
      Material mat;
      string msg = string.Empty;
      int i, n;

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

        // For 0310_ensure_material.htm:

        if (e is FamilyInstance)
        {
          mat = GetMaterial(doc, e as FamilyInstance);

          Util.InfoMsg(
            "Family instance element material: "
            + (null == mat ? "<null>" : mat.Name));
        }

        GeometryElement geo = e.get_Geometry(opt);

        // If you are not interested in duplicate
        // materials, you can define a class that
        // overloads the Add method to only insert
        // a new entry if its value is not already
        // present in the list, instead of using
        // the standard List<> class:

        List<string> materials = GetMaterials(doc, geo);

        msg += "\n" + Util.ElementDescription(e);

        n = materials.Count;

        if (0 == n)
        {
          msg += " has no materials.";
        }
        else
        {
          i = 0;

          msg += string.Format(
            " has {0} material{1}:",
            n, Util.PluralSuffix(n));

          foreach (string s in materials)
          {
            msg += string.Format(
              "\n  {0} {1}", i++, s);
          }
        }
      }

      if (0 == msg.Length)
      {
        msg = "Please select some elements.";
      }

      Util.InfoMsg(msg);

      return Result.Succeeded;
    }
Example #33
0
        /// <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)
        {
            Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "External Tool");

            try
            {
                transaction.Start();
                Wall  wall  = null;
                Floor floor = null;

                ElementSet elems = new ElementSet();
                foreach (ElementId elementId in commandData.Application.ActiveUIDocument.Selection.GetElementIds())
                {
                    elems.Insert(commandData.Application.ActiveUIDocument.Document.GetElement(elementId));
                }
                #region selection error handle
                //if user have some wrong selection, give user an error message
                if (1 != elems.Size)
                {
                    message = "please selected one Object (Floor or Wall) to create Opening.";
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                Autodesk.Revit.DB.Element selectElem = null;
                foreach (Autodesk.Revit.DB.Element e in elems)
                {
                    selectElem = e;
                }

                if (!(selectElem is Wall) && !(selectElem is Floor))
                {
                    message = "please selected one Object (Floor or Wall) to create Opening.";
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }
                #endregion
                try
                {
                    if (selectElem is Wall)
                    {
                        wall = selectElem as Wall;
                        ProfileWall     profileWall     = new ProfileWall(wall, commandData);
                        NewOpeningsForm newOpeningsForm = new NewOpeningsForm(profileWall);
                        newOpeningsForm.ShowDialog();
                    }
                    else if (selectElem is Floor)
                    {
                        floor = selectElem as Floor;
                        ProfileFloor    profileFloor    = new ProfileFloor(floor, commandData);
                        NewOpeningsForm newOpeningsForm = new NewOpeningsForm(profileFloor);
                        newOpeningsForm.ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    return(Autodesk.Revit.UI.Result.Cancelled);
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
            finally
            {
                transaction.Commit();
            }
        }
Example #34
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);
        }
        /// <summary>
        /// Here is a part or our code to start a Revit command.
        /// The aim of the code is to set a wall type current in the Revit property window.
        /// We only start up the wall command with the API and let the user do the drawing of the wall.
        /// This solution can also be used to launch other Revit commands.
        /// </summary>
        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;

            // Name of target wall type that we want to use:

            string wallTypeName = "Generic - 203";

            WallType wallType = GetFirstWallTypeNamed(
                doc, wallTypeName);

            Wall wall = GetFirstWallUsingType(
                doc, wallType);

            // Select the wall in the UI

            //uidoc.Selection.Elements.Add( wall ); // 2014

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

            ids.Add(wall.Id);
            uidoc.Selection.SetElementIds(ids); // 2015

            //if( 0 == uidoc.Selection.Elements.Size ) // 2014

            if (0 == uidoc.Selection.GetElementIds().Count) // 2015
            {
                // No wall with the correct wall type found

                FilteredElementCollector collector
                    = new FilteredElementCollector(doc);

                Level ll = collector
                           .OfClass(typeof(Level))
                           .FirstElement() as Level;

                // place a new wall with the
                // correct wall type in the project

                //Line geomLine = app.Create.NewLineBound( XYZ.Zero, new XYZ( 2, 0, 0 ) ); // 2013
                Line geomLine = Line.CreateBound(XYZ.Zero, new XYZ(2, 0, 0)); // 2014

                Transaction t = new Transaction(
                    doc, "Create dummy wall");

                t.Start();

                //Wall nw = doc.Create.NewWall( geomLine, // 2012
                //  wallType, ll, 1, 0, false, false );

                Wall nw = Wall.Create(doc, geomLine, // 2013
                                      wallType.Id, ll.Id, 1, 0, false, false);

                t.Commit();

                // Select the new wall in the project

                //uidoc.Selection.Elements.Add( nw ); // 2014

                ids.Clear();
                ids.Add(nw.Id);
                uidoc.Selection.SetElementIds(ids); // 2015

                // Start command create similar. In the
                // property menu, our wall type is set current

                Press.Keys("CS");

                // Select the new wall in the project,
                // so we can delete it

                //uidoc.Selection.Elements.Add( nw ); // 2014

                ids.Clear();
                ids.Add(nw.Id);
                uidoc.Selection.SetElementIds(ids); // 2015

                // Erase the selected wall (remark:
                // doc.delete(nw) may not be used,
                // this command will undo)

                Press.Keys("DE");

                // Start up wall command

                Press.Keys("WA");
            }
            else
            {
                // The correct wall is already selected:

                Press.Keys("CS"); // Start "create similar"
            }
            return(Result.Succeeded);
        }
Example #36
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            Element e = Util.SelectSingleElement(
                uidoc, "an element");

            if (null == e)
            {
                message = "No element selected";
                return(Result.Failed);
            }

            // Trying to call this property returns the
            // compile time error: Property, indexer, or
            // event 'BoundingBox' is not supported by
            // the language; try directly calling
            // accessor method 'get_BoundingBox( View )'

            //BoundingBoxXYZ b = e.BoundingBox[null];

            View v = null;

            BoundingBoxXYZ b = e.get_BoundingBox(v);

            if (null == b)
            {
                v = commandData.View;
                b = e.get_BoundingBox(v);
            }

            if (null == b)
            {
                Util.InfoMsg(
                    Util.ElementDescription(e)
                    + " has no bounding box.");
            }
            else
            {
                using (Transaction tx = new Transaction(doc))
                {
                    tx.Start("Draw Model Line Bounding Box Outline");

                    Debug.Assert(b.Transform.IsIdentity,
                                 "expected identity bounding box transform");

                    string in_view = (null == v)
            ? "model space"
            : "view " + v.Name;

                    Util.InfoMsg(string.Format(
                                     "Element bounding box of {0} in "
                                     + "{1} extends from {2} to {3}.",
                                     Util.ElementDescription(e),
                                     in_view,
                                     Util.PointString(b.Min),
                                     Util.PointString(b.Max)));

                    Creator creator = new Creator(doc);

                    creator.DrawPolygon(new List <XYZ>(
                                            Util.GetBottomCorners(b)));

                    Transform rotation = Transform.CreateRotation(
                        XYZ.BasisZ, 60 * Math.PI / 180.0);

                    b = RotateBoundingBox(b, rotation);

                    Util.InfoMsg(string.Format(
                                     "Bounding box rotated by 60 degrees "
                                     + "extends from {0} to {1}.",
                                     Util.PointString(b.Min),
                                     Util.PointString(b.Max)));

                    creator.DrawPolygon(new List <XYZ>(
                                            Util.GetBottomCorners(b)));

                    tx.Commit();
                }
            }
            return(Result.Succeeded);
        }
Example #37
0
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            ExternalCommandData cdata = commandData;

            Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application;
            Document   doc   = commandData.Application.ActiveUIDocument.Document;
            UIDocument uiDoc = commandData.Application.ActiveUIDocument;


            var line = Line.CreateBound(new XYZ(0, 0, 0), new XYZ(0, 40, 0));
            var arc  = Arc.Create(new XYZ(0, -50, 0), new XYZ(40, -50, 0), new XYZ(50, -60, 0));

            var drawingLine = new DrawingCurve(doc, line);

            drawingLine.Draw();

            var drawingArc = new DrawingCurve(doc, arc);

            drawingArc.Draw();

            return(Result.Succeeded);
        }
 public Result Execute(ExternalCommandData commandData, ref string message, ElementSet _)
 {
     return(RibbonButtonClickHandler.OpenSettingsPluginWindow(commandData, ref message));
 }
Example #39
0
        private OutputExchangeItem buildExchangeItemFromFolder(string folder)
        {
            //The routine will construct an OpenMI exchange item from a folder of WaterML files.
            //assumptions: (1) all files within the folder are waterML files
            //             (2) all files within folder have the same variable element
            //
            // --- MAPPING BETWEEN OPENMI AND WATERML
            // Qunatity <-- from the first file in the directory
            //   ID [REQUIRED] = WaterML's variableParam element inner text
            //   Description [optional] = WaterML's variableName element inner text
            //   ValueType [hard coded] = Scalar
            //   Unit
            //     ID [optional]= WaterML's units element attribute unitsAbbreviation
            //     ConversionFactortoSI [optional] = not in WaterML
            //     ConverstionOffsettoSI [optional] = not in WaterML
            //   Dimension
            //     Power [optional] = not in WaterML
            // ElementSet
            //   ID [REQUIRED] = folder name
            //   Description [REQUIRED] = folder relative path
            //   ElementType [hard coded] = XYPoint or IDBased
            //   Element
            //     ID [optional]= WaterML's SiteCode element inner text [changing to locationParam]
            //     Vertex
            //       X = WaterML's longitude element inner text
            //       Y = WaterML's latitude element inner text
            //   ...
            // TimeHorizon <-- union of all file-level time horizons

            //get list of files within the folder
            string[] files = Directory.GetFiles(folder);

            //load the first file in the directory as an XML document
            XmlDocument xmldoc = new XmlDocument();

            // load the first xml file in the directory
            StreamReader sr = new StreamReader(files[0]);

            //deserialize
            XmlSerializer          xml_reader = new XmlSerializer(typeof(TimeSeriesResponseType));
            TimeSeriesResponseType tsr        = (TimeSeriesResponseType)xml_reader.Deserialize(sr);

            Quantity           quantity           = new Quantity();
            Unit               unit               = new Unit();
            Dimension          dimension          = new Dimension();
            ElementSet         elementset         = new ElementSet();
            OutputExchangeItem outputexchangeitem = new OutputExchangeItem();

            //Quantity ID -- REQUIRED
            try { quantity.ID = tsr.queryInfo.criteria.variableParam; }
            catch { throw new Exception("waterML document must contain a variableParam element"); }

            //Quantity Description -- optional
            try { quantity.Description = tsr.timeSeries.variable.variableName; }
            catch { quantity.Description = ""; }

            //Quantity Variable Type -- hard coded
            quantity.ValueType = global::OpenMI.Standard.ValueType.Scalar;

            //Unit ID -- optional
            try { unit.ID = tsr.timeSeries.variable.units.unitsAbbreviation; }
            catch { unit.ID = ""; }

            //Unit Converstion Factor to SI
            //TODO WaterML does not include conversion factors to SI
            //unit.ConversionFactorToSI = 0;

            //Unit Converstion Offset to SI
            //TODO WaterML does not include conversion offest to SI
            //unit.OffSetToSI = 0;

            quantity.Unit = unit;

            //Dimension Powers -- optional
            //TODO WaterML does not include dimension info for units
            //Examples below ...
            //dimension.SetPower(DimensionBase.Length, 3);
            //dimension.SetPower(DimensionBase.Time, -1);

            quantity.Dimension = dimension;

            //ElementSet ID -- folder name
            elementset.ID = new DirectoryInfo(folder).Name;

            //ElementSet Description -- folder relative path
            elementset.Description = folder;

            //ElementSet ElementType -- hard coded
            elementset.ElementType = ElementType.XYPoint;

            // -------------------------------------------------------------------
            // The remaining objects require access to all files in the directory.
            // -------------------------------------------------------------------

            foreach (string fileName in files)
            {
                //load the first file in the directory as an XML document
                sr  = new StreamReader(fileName);
                tsr = (TimeSeriesResponseType)xml_reader.Deserialize(sr);

                Element element = new Element();
                Vertex  vertex  = new Vertex();

                //Element ID -- optional
                try { element.ID = tsr.queryInfo.criteria.locationParam; }
                catch { element.ID = ""; }

                //Vertex X and Y -- optional
                //tsr.timeSeries. TODO fix this.
                //if (xml_location != null && xml_location["longitude"] != null && xml_location["latitude"] != null)
                //{
                //    vertex.x = Convert.ToDouble(xml_location["longitude"].InnerText);
                //    vertex.y = Convert.ToDouble(xml_location["latitude"].InnerText);
                //}
                //else { vertex.x = double.NaN; vertex.y = double.NaN; elementset.ElementType = ElementType.IDBased; }
                element.AddVertex(vertex);

                elementset.AddElement(element);

                //TimeHorizon -- REQUIRED
//if (_earliestInputTime == 0.0)
//               {
                string beginDateTimeString;
                try { beginDateTimeString = tsr.queryInfo.criteria.timeParam.beginDateTime; }
                catch { throw new Exception("waterML document must contain a beginDateTime element"); }

                string endDateTimeString;
                try { endDateTimeString = tsr.queryInfo.criteria.timeParam.endDateTime; }
                catch { throw new Exception("waterML document must contain an endDateTime element"); }

                DateTime beginDateTime       = Convert.ToDateTime(beginDateTimeString);
                DateTime endDateTime         = Convert.ToDateTime(endDateTimeString);
                double   beginDateTimeDouble = CalendarConverter.Gregorian2ModifiedJulian(beginDateTime);
                double   endDateTimeDouble   = CalendarConverter.Gregorian2ModifiedJulian(endDateTime);

                //update time horizon to be inclusive of this time horizon
                if (_earliestInputTime == 0.0)
                {
                    _earliestInputTime = beginDateTimeDouble;
                }
                if (beginDateTimeDouble < _earliestInputTime)
                {
                    _earliestInputTime = beginDateTimeDouble;
                }
                ;
                if (endDateTimeDouble > _latestInputTime)
                {
                    _latestInputTime = endDateTimeDouble;
                }
                ;
                //              }
            }
            outputexchangeitem.Quantity   = quantity;
            outputexchangeitem.ElementSet = elementset;

            // add data operations and return
            return(addDataOperations(outputexchangeitem));
        }
Example #40
0
        static public Result Execute2(
            ExternalCommandData commandData,
            ref String message,
            ElementSet elements,
            bool populateFullHierarchy)
        {
            try
            {
                WaitCursor    waitCursor = new WaitCursor();
                UIApplication app        = commandData.Application;
                Document      doc        = app.ActiveUIDocument.Document;
                //
                // display electrical equipment instance data,
                // i.e. equipment_name:system_name, and convert it to
                // a map from key = panel:circuit --> equipment:
                //
                List <Element> equipment = Util.GetElectricalEquipment(doc);
                int            n         = equipment.Count;
                Debug.WriteLine(string.Format("Retrieved {0} electrical equipment instance{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                Dictionary <string, List <Element> > mapPanelAndSystemToEquipment = new Dictionary <string, List <Element> >();
                foreach (FamilyInstance elecEqip in equipment)
                {
                    ListEquipment(elecEqip, mapPanelAndSystemToEquipment);
                }
                //
                // determine mapping from panel to circuit == electrical system:
                //
                Dictionary <string, ElectricalSystemSet> mapPanelToSystems = new Dictionary <string, ElectricalSystemSet>();
                IList <Element> systems = Util.GetElectricalSystems(doc);
                n = systems.Count;
                Debug.WriteLine(string.Format("Retrieved {0} electrical system{1}.", n, Util.PluralSuffix(n)));
                //
                // all circuits which are fed from the same family instance have
                // the same panel name, so you can retrieve all of these circuits.
                //
                // todo: there is an issue here if there are several different panels
                // with the same name! they will get merged in the tree view,
                // but they should stay separate. possible workaround: add the
                // element id to keep them separate, and then remove it again
                // when displaying in tree view.
                //
                foreach (ElectricalSystem system in systems)
                {
                    string panelName = system.PanelName;

                    Debug.WriteLine("  system " + system.Name + ": panel " + panelName
                                    + " load classifications " + system.LoadClassifications);

                    if (!mapPanelToSystems.ContainsKey(panelName))
                    {
                        mapPanelToSystems.Add(panelName, new ElectricalSystemSet());
                    }
                    mapPanelToSystems[panelName].Insert(system);
                }
                n = mapPanelToSystems.Count;
                //Debug.WriteLine( string.Format( "Mapping from the {0} panel{1} to systems, system name :circuit name(connectors/unused connectors):", n, Util.PluralSuffix( n ) ) );
                Debug.WriteLine(string.Format("Mapping from the {0} panel{1} to electrical systems == circuits:",
                                              n, Util.PluralSuffix(n)));
                List <string> keys = new List <string>(mapPanelToSystems.Keys);
                keys.Sort();
                string s;
                foreach (string panelName in keys)
                {
                    s = string.Empty;
                    foreach (ElectricalSystem system in mapPanelToSystems[panelName])
                    {
                        ConnectorManager cmgr = system.ConnectorManager;

                        // the connector manager does not include any logical connectors
                        // in the Revit 2009 fcs and wu1 API, only physical ones:
                        //Debug.Assert( 0 == cmgr.Connectors.Size,
                        //  "electrical connector count is always zero" );

                        Debug.Assert(cmgr.UnusedConnectors.Size <= cmgr.Connectors.Size,
                                     "unused connectors is a subset of connectors");

                        Debug.Assert(system.Name.Equals(system.CircuitNumber),
                                     "ElectricalSystem Name and CircuitNumber properties are always identical");

                        //s += ( 0 < s.Length ? ", " : ": " ) + system.Name;

                        s += (0 < s.Length ? ", " : ": ") + system.Name // + ":" + system.CircuitNumber
                             + "(" + cmgr.Connectors.Size.ToString()
                             + "/" + cmgr.UnusedConnectors.Size.ToString() + ")";
                    }
                    Debug.WriteLine("  " + panelName + s);
                }

                /*
                 * Debug.WriteLine( "Mapping from panels to systems to connected elements:" );
                 * foreach( string panelName in keys )
                 * {
                 * Debug.WriteLine( "  panel " + panelName + ":" );
                 * foreach( ElectricalSystem system in mapPanelToSystems[panelName] )
                 * {
                 *  ConnectorManager cmgr = system.ConnectorManager;
                 *  n = cmgr.Connectors.Size;
                 *  Debug.WriteLine( string.Format( "    system {0} has {1} connector{2}{3}", system.Name, n, Util.PluralSuffix( n ), Util.DotOrColon( n ) ) );
                 *  foreach( Connector connector in system.ConnectorManager.Connectors )
                 *  {
                 *    Element owner = connector.Owner;
                 *    Debug.WriteLine( string.Format( "    owner {0} {1}, domain {2}", owner.Name, owner.Id.IntegerValue, connector.Domain ) );
                 *  }
                 * }
                 * }
                 */

                //
                // list all circuit elements:
                //
                // this captures all elements in circuits H-2: 2, 4, 6 etc,
                // but not the element T2 in H-2:1,3,5, because it has no circuit number,
                // just a panel number.
                //
                BuiltInParameter bipPanel        = BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM;
                BuiltInParameter bipCircuit      = BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER;
                IList <Element>  circuitElements = Util.GetCircuitElements(doc);
                n = circuitElements.Count;
                Debug.WriteLine(string.Format("Retrieved {0} circuit element{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                Dictionary <string, List <Element> > mapPanelAndCircuitToElements = new Dictionary <string, List <Element> >();
                foreach (Element e in circuitElements)
                {
                    string circuitName = e.get_Parameter(bipCircuit).AsString();
                    //
                    // do not map an electrical system to itself:
                    //
                    if (!(e is ElectricalSystem && e.Name.Equals(circuitName)))
                    {
                        string panelName = e.get_Parameter(bipPanel).AsString();
                        string key       = panelName + ":" + circuitName;
                        Debug.WriteLine(string.Format("  {0} <{1} {2}> panel:circuit {3}", e.GetType().Name, e.Name, e.Id.IntegerValue, key));
                        if (!mapPanelAndCircuitToElements.ContainsKey(key))
                        {
                            mapPanelAndCircuitToElements.Add(key, new List <Element>());
                        }
                        mapPanelAndCircuitToElements[key].Add(e);
                    }
                }
                n = mapPanelAndCircuitToElements.Count;
                Debug.WriteLine(string.Format("Mapped circuit elements to {0} panel:circuit{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                keys.Clear();
                keys.AddRange(mapPanelAndCircuitToElements.Keys);
                keys.Sort(new PanelCircuitComparer());
                foreach (string panelAndCircuit in keys)
                {
                    List <string> a = new List <string>(mapPanelAndCircuitToElements[panelAndCircuit].Count);
                    foreach (Element e in mapPanelAndCircuitToElements[panelAndCircuit])
                    {
                        FamilyInstance inst = e as FamilyInstance;
                        a.Add((null == inst ? e.Category.Name : inst.Symbol.Family.Name) + " " + e.Name);
                    }
                    a.Sort();
                    s = string.Join(", ", a.ToArray());
                    Debug.WriteLine("  " + panelAndCircuit + ": " + s);
                }

                #region Aborted attempt to use RBS_ELEC_CIRCUIT_PANEL_PARAM
#if USE_RBS_ELEC_CIRCUIT_PANEL_PARAM
                //
                // list all panel elements:
                //
                // selecting all elements with a BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER
                // captures all elements in circuits H-2: 2, 4, 6 etc, but not the element
                // T2 in H-2:1,3,5, because it has no circuit number, just a panel number.
                //
                // so grab everything with a panel number instead.
                //
                // all this added to the selection was lots of wires, so forget it again.
                //
                BuiltInParameter bipCircuit      = BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER;
                BuiltInParameter bipPanel        = BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM;
                List <Element>   circuitElements = new List <Element>();
                Util.GetElementsWithParameter(circuitElements, bipPanel, app);
                n = circuitElements.Count;
                Debug.WriteLine(string.Format("Retrieved {0} circuit element{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                Dictionary <string, List <Element> > mapCircuitToElements = new Dictionary <string, List <Element> >();
                foreach (Element e in circuitElements)
                {
                    string    panelName = e.get_Parameter(bipPanel).AsString();
                    Parameter p         = e.get_Parameter(bipCircuit);
                    if (null == p)
                    {
                        Debug.WriteLine(string.Format("  {0} <{1} {2}> panel:circuit {3}:null", e.GetType().Name, e.Name, e.Id.IntegerValue, panelName));
                    }
                    else
                    {
                        string circuitName = p.AsString();
                        //
                        // do not map an electrical system to itself:
                        //
                        if (!(e is ElectricalSystem && e.Name.Equals(circuitName)))
                        {
                            string key = panelName + ":" + circuitName;
                            Debug.WriteLine(string.Format("  {0} <{1} {2}> panel:circuit {3}", e.GetType().Name, e.Name, e.Id.IntegerValue, key));
                            if (!mapCircuitToElements.ContainsKey(key))
                            {
                                mapCircuitToElements.Add(key, new List <Element>());
                            }
                            mapCircuitToElements[key].Add(e);
                        }
                    }
                }
                n = mapCircuitToElements.Count;
                Debug.WriteLine(string.Format("Mapped circuit elements to {0} panel:circuit{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                keys.Clear();
                keys.AddRange(mapCircuitToElements.Keys);
                keys.Sort(new PanelCircuitComparer());
                foreach (string circuitName in keys)
                {
                    List <string> a = new List <string>(mapCircuitToElements[circuitName].Count);
                    foreach (Element e in mapCircuitToElements[circuitName])
                    {
                        FamilyInstance inst = e as FamilyInstance;
                        a.Add((null == inst ? e.Category.Name : inst.Symbol.Family.Name) + " " + e.Name);
                    }
                    a.Sort();
                    s = string.Join(", ", a.ToArray());
                    Debug.WriteLine("  " + circuitName + ": " + s);
                }
#endif // USE_RBS_ELEC_CIRCUIT_PANEL_PARAM
                #endregion // Aborted attempt to use RBS_ELEC_CIRCUIT_PANEL_PARAM

                //
                // merge the two trees of equipment and circuit elements
                // to reproduce the content of the system browser ... the
                // hardest part of this is setting up the PanelSystemComparer
                // to generate the same sort order as the system browser:
                //
                //n = mapPanelAndSystemToEquipment.Count + mapPanelAndCircuitToElements.Count;
                //Dictionary<string, List<Element>> mapSystemBrowser = new Dictionary<string, List<Element>>( n );
                Dictionary <string, List <Element> > mapSystemBrowser = new Dictionary <string, List <Element> >(mapPanelAndCircuitToElements);
                foreach (KeyValuePair <string, List <Element> > pair in mapPanelAndSystemToEquipment)
                {
                    mapSystemBrowser[pair.Key] = pair.Value;
                }
                n = mapSystemBrowser.Count;
                Debug.WriteLine(string.Format("Mapped equipment + circuit elements to {0} panel:system{1}{2}",
                                              n, Util.PluralSuffix(n), Util.DotOrColon(n)));
                keys.Clear();
                keys.AddRange(mapSystemBrowser.Keys);
                keys.Sort(new PanelSystemComparer());
                foreach (string panelAndSystem in keys)
                {
                    List <string> a = new List <string>(mapSystemBrowser[panelAndSystem].Count);
                    foreach (Element e in mapSystemBrowser[panelAndSystem])
                    {
                        a.Add(Util.BrowserDescription(e));
                    }
                    a.Sort();
                    s = string.Join(", ", a.ToArray());
                    Debug.WriteLine(string.Format("  {0}({1}): ", panelAndSystem, a.Count) + s);
                }
                //
                // get the electrical equipment category id:
                //
                Categories categories = doc.Settings.Categories;
                ElementId  electricalEquipmentCategoryId = categories.get_Item(BuiltInCategory.OST_ElectricalEquipment).Id;
                //
                // we have assembled the required information and structured it
                // sufficiently for the tree view, so now let us go ahead and display it:
                //
                CmdInspectElectricalForm dialog = new CmdInspectElectricalForm(mapSystemBrowser, electricalEquipmentCategoryId, populateFullHierarchy);
                dialog.Show();
                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
        ///// <summary>
        ///// Allow selection of curve elements only.
        ///// </summary>
        //class CurveElementSelectionFilter : ISelectionFilter
        //{
        //  public bool AllowElement( Element e )
        //  {
        //    return e is CurveElement;
        //  }

        //  public bool AllowReference( Reference r, XYZ p )
        //  {
        //    return true;
        //  }
        //}

        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;

            // Select all model curves in the entire model.

            List <CurveElement> curves = new List <CurveElement>(
                new FilteredElementCollector(doc)
                .OfClass(typeof(CurveElement))
                .ToElements()
                .Cast <CurveElement>());

            int n = curves.Count;

            // If there are less than two,
            // there is nothing we can do.

            if (2 > n)
            {
                message = _prompt;
                return(Result.Failed);
            }

            // If there are exactly two, pick those.

            if (2 < n)
            {
                // Else, check for a pre-selection.

                curves.Clear();

                Selection sel = uidoc.Selection;
                ICollection <ElementId> ids = sel.GetElementIds();
                n = ids.Count;

                Debug.Print("{0} pre-selected elements.",
                            n);

                // If two or more model curves were pre-
                // selected, use the first two encountered.

                if (1 < n)
                {
                    foreach (ElementId id in ids)
                    {
                        CurveElement c = doc.GetElement(id)
                                         as CurveElement;

                        if (null != c)
                        {
                            curves.Add(c);

                            if (2 == curves.Count)
                            {
                                Debug.Print("Found two model curves, "
                                            + "ignoring everything else.");

                                break;
                            }
                        }
                    }
                }

                // Else, prompt for an
                // interactive post-selection.

                if (2 != curves.Count)
                {
                    curves.Clear();

                    ISelectionFilter f
                        = new JtElementsOfClassSelectionFilter <CurveElement>();

                    try
                    {
                        Reference r = sel.PickObject(
                            ObjectType.Element, f,
                            "Please pick first model curve.");

                        curves.Add(doc.GetElement(r.ElementId)
                                   as CurveElement);
                    }
                    catch (Autodesk.Revit.Exceptions
                           .OperationCanceledException)
                    {
                        return(Result.Cancelled);
                    }

                    try
                    {
                        Reference r = sel.PickObject(
                            ObjectType.Element, f,
                            "Please pick second model curve.");

                        curves.Add(doc.GetElement(r.ElementId)
                                   as CurveElement);
                    }
                    catch (Autodesk.Revit.Exceptions
                           .OperationCanceledException)
                    {
                        return(Result.Cancelled);
                    }
                }
            }

            // Extract data from the two selected curves.

            Curve c0 = curves[0].GeometryCurve;
            Curve c1 = curves[1].GeometryCurve;

            double sp0   = c0.GetEndParameter(0);
            double ep0   = c0.GetEndParameter(1);
            double step0 = (ep0 - sp0) / _nSegments;

            double sp1   = c1.GetEndParameter(0);
            double ep1   = c1.GetEndParameter(1);
            double step1 = (ep1 - sp1) / _nSegments;

            Debug.Print("Two curves' step size [start, end]:"
                        + " {0} [{1},{2}] -- {3} [{4},{5}]",
                        Util.RealString(step0),
                        Util.RealString(sp0),
                        Util.RealString(ep0),
                        Util.RealString(step1),
                        Util.RealString(sp1),
                        Util.RealString(ep1));

            // Modify document within a transaction.

            using (Transaction tx = new Transaction(doc))
            {
                Creator creator = new Creator(doc);

                tx.Start("MidCurve");

                // Current segment start points.

                double t0 = sp0;
                double t1 = sp1;

                XYZ p0 = c0.GetEndPoint(0);
                XYZ p1 = c1.GetEndPoint(0);
                XYZ p  = Util.Midpoint(p0, p1);

                Debug.Assert(
                    p0.IsAlmostEqualTo(c0.Evaluate(t0, false)),
                    "expected equal start points");

                Debug.Assert(
                    p1.IsAlmostEqualTo(c1.Evaluate(t1, false)),
                    "expected equal start points");

                // Current segment end points.

                t0 += step0;
                t1 += step1;

                XYZ  q0, q1, q;
                Line line;

                for (int i = 0; i < _nSegments; ++i, t0 += step0, t1 += step1)
                {
                    q0 = c0.Evaluate(t0, false);
                    q1 = c1.Evaluate(t1, false);
                    q  = Util.Midpoint(q0, q1);

                    Debug.Print(
                        "{0} {1} {2} {3}-{4} {5}-{6} {7}-{8}",
                        i,
                        Util.RealString(t0),
                        Util.RealString(t1),
                        Util.PointString(p0),
                        Util.PointString(q0),
                        Util.PointString(p1),
                        Util.PointString(q1),
                        Util.PointString(p),
                        Util.PointString(q));

                    // Create approximating curve segment.

                    line = Line.CreateBound(p, q);
                    creator.CreateModelCurve(line);

                    p0 = q0;
                    p1 = q1;
                    p  = q;
                }
                tx.Commit();
            }
            return(Result.Succeeded);
        }
Example #42
0
        protected override Result ExecuteCommand(ExternalCommandData data, ref string message, ElementSet elements)
        {
            _app = data.Application;
            _doc = data.Application.ActiveUIDocument.Document;
            Selection        selection  = data.Application.ActiveUIDocument.Selection;
            List <ElementId> elementIds = selection.GetElementIds().ToList();

            if (elementIds.Count == 0)
            {
                TaskDialog.Show("提示", "您未选择任何图元");
            }
            else
            {
                string info = "您选择的图元ID列表:";
                foreach (var item in elementIds)
                {
                    info += "\n\t" + item.IntegerValue;
                }
                TaskDialog.Show("提示", info);
            }
            ElementClassFilter       familyInstanceFilter = new ElementClassFilter(typeof(FamilyInstance));
            ElementCategoryFilter    doorCategoryFilter   = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
            LogicalAndFilter         logicalAndFilter     = new LogicalAndFilter(familyInstanceFilter, doorCategoryFilter);
            FilteredElementCollector collector            = new FilteredElementCollector(_doc);
            List <ElementId>         doors = collector.WherePasses(logicalAndFilter).ToElementIds().ToList();
            string info2 = "文档中的门ID列表:";

            foreach (var item in doors)
            {
                info2 += "\n\t" + item.IntegerValue;
            }
            TaskDialog.Show("提示", info2);
            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref String message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            Element e = Util.SelectSingleElement(
                uidoc, "a line or wall");

            LocationCurve curve = null;

            if (null == e)
            {
                message = "No element selected";
            }
            else
            {
                curve = e.Location as LocationCurve;
            }

            if (null == curve)
            {
                message = "No curve available";
            }
            else
            {
                XYZ p = curve.Curve.GetEndPoint(0);
                XYZ q = curve.Curve.GetEndPoint(1);

                Debug.WriteLine("Start point "
                                + Util.PointString(p));

                Debug.WriteLine("End point "
                                + Util.PointString(q));

                // the angle between the vectors from the project origin
                // to the start and end points of the wall is pretty irrelevant:

                double a = p.AngleTo(q);
                Debug.WriteLine(
                    "Angle between start and end point vectors = "
                    + Util.AngleString(a));

                XYZ v  = q - p;
                XYZ vx = XYZ.BasisX;
                a = vx.AngleTo(v);
                Debug.WriteLine(
                    "Angle between points measured from X axis = "
                    + Util.AngleString(a));

                XYZ z = XYZ.BasisZ;
                a = vx.AngleOnPlaneTo(v, z);
                Debug.WriteLine(
                    "Angle around measured from X axis = "
                    + Util.AngleString(a));

                if (e is Wall)
                {
                    Wall wall = e as Wall;
                    XYZ  w    = z.CrossProduct(v).Normalize();
                    if (wall.Flipped)
                    {
                        w = -w;
                    }
                    a = vx.AngleOnPlaneTo(w, z);
                    Debug.WriteLine(
                        "Angle pointing out of wall = "
                        + Util.AngleString(a));
                }
            }

            foreach (ProjectLocation location
                     in doc.ProjectLocations)
            {
                ProjectPosition projectPosition
                    = location.get_ProjectPosition(XYZ.Zero);
                double pna = projectPosition.Angle;
                Debug.WriteLine(
                    "Angle between project north and true north "
                    + Util.AngleString(pna));
            }
            return(Result.Failed);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Debug.Assert(false,
                         "setting the disallow join property was not possible prior to Revit 2012. "
                         + "In Revit 2012, you can use the WallUtils.DisallowWallJoinAtEnd method.");

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

            string s = "a wall, to retrieve its join types";

            Wall wall = Util.SelectSingleElementOfType(
                uidoc, typeof(Wall), s, false) as Wall;

            if (null == wall)
            {
                message = "Please select a wall.";
            }
            else
            {
                JoinType []     a1 = ( JoinType [] )Enum.GetValues(typeof(JoinType));
                List <JoinType> a  = new List <JoinType>((JoinType[])Enum.GetValues(typeof(JoinType)));
                int             n  = a.Count;

                LocationCurve lc = wall.Location as LocationCurve;

                s = Util.ElementDescription(wall) + ":\n";

                /*for( int i = 0; i < 2; ++i )
                 * {
                 * JoinType jt = lc.get_JoinType( i );
                 * int j = a.IndexOf( jt ) + 1;
                 * JoinType jtnew = a[ j < n ? j : 0];
                 * lc.set_JoinType( j, jtnew );
                 * s += string.Format(
                 *  "\nChanged join type at {0} from {1} to {2}.",
                 *  ( 0 == i ? "start" : "end" ), jt, jtnew );
                 * }
                 * // wall.Location = lc; // Property or indexer 'Autodesk.Revit.Element.Location' cannot be assigned to -- it is read only
                 */

                using (Transaction t = new Transaction(doc))
                {
                    t.Start("Set Wall Join Type");

                    for (int i = 0; i < 2; ++i)
                    {
                        JoinType jt    = ((LocationCurve)wall.Location).get_JoinType(i);
                        int      j     = a.IndexOf(jt) + 1;
                        JoinType jtnew = a[j < n ? j : 0];
                        ((LocationCurve)wall.Location).set_JoinType(j, jtnew);
                        s += string.Format(
                            "\nChanged join type at {0} from {1} to {2}.",
                            (0 == i ? "start" : "end"), jt, jtnew);
                    }
                    t.Commit();
                }
            }
            Util.InfoMsg(s);
            return(Result.Succeeded);
        }
Example #45
0
            public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements)
            {
                string filePath;

                using (var openFileDialog = new OpenFileDialog())
                {
                    openFileDialog.Filter = "Grasshopper Binary (*.gh)|*.gh|Grasshopper Xml (*.ghx)|*.ghx";
#if DEBUG
                    openFileDialog.FilterIndex = 2;
#else
                    openFileDialog.FilterIndex = 1;
#endif
                    openFileDialog.RestoreDirectory = true;

                    switch (openFileDialog.ShowDialog(ModalForm.OwnerWindow))
                    {
                    case DialogResult.OK: filePath = openFileDialog.FileName; break;

                    case DialogResult.Cancel: return(Result.Cancelled);

                    default: return(Result.Failed);
                    }
                }

                return(Execute(data, ref message, elements, filePath));
            }
Example #46
0
 public class Mru5 : Sample4 { public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements) => Execute(data, ref message, elements, mruPushPuttons[5].ToolTip); }
Example #47
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            if (_subscribed)
            {
                Autodesk.Windows.ComponentManager.ItemExecuted
                    -= OnItemExecuted;

                _subscribed = false;
            }
            else
            {
                RibbonTabCollection tabs
                    = ComponentManager.Ribbon.Tabs;

                foreach (RibbonTab tab in tabs)
                {
                    Debug.Print("  {0} {1} '{2}'", tab,
                                tab.GetType().Name, tab.AutomationName);

                    if (tab.KeyTip == null)
                    {
                        // This tab is user defined.

                        foreach (var panel in tab.Panels)
                        {
                            // Cannot convert type 'Autodesk.Windows.RibbonPanel'
                            // to 'Autodesk.Revit.UI.RibbonPanel' via a reference
                            // conversion, boxing conversion, unboxing conversion,
                            // wrapping conversion, or null type conversion.
                            //
                            //Autodesk.Revit.UI.RibbonPanel rp
                            //  = panel as Autodesk.Revit.UI.RibbonPanel;

                            Autodesk.Windows.RibbonPanel rp
                                = panel as Autodesk.Windows.RibbonPanel;

                            Debug.Print("    {0} {1}",
                                        panel.ToString(), panel.GetType().Name);

                            foreach (var item in panel.Source.Items)
                            {
                                Autodesk.Windows.RibbonItem ri = item
                                                                 as Autodesk.Windows.RibbonItem;

                                string automationName = ri.AutomationName;

                                Debug.Print("      {0} {1} '{2}' {3}",
                                            item.ToString(), item.GetType().Name,
                                            automationName, ri.Cookie);
                            }
                        }
                    }
                }

                Autodesk.Windows.ComponentManager.ItemExecuted
                    += OnItemExecuted;

                _subscribed = true;
            }
            return(Result.Succeeded);
        }
Example #48
0
 public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
 {
     return(Result.Succeeded);
 }
        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;

            // Build a wall profile for the wall creation

            XYZ[] pts = new XYZ[] {
                XYZ.Zero,
                new XYZ(20, 0, 0),
                new XYZ(20, 0, 15),
                new XYZ(10, 0, 30),
                new XYZ(0, 0, 15)
            };

            // Get application creation object

            Autodesk.Revit.Creation.Application appCreation
                = app.Create;

            // Create wall profile

            //CurveArray profile = new CurveArray(); // 2012

            //XYZ q = pts[pts.Length - 1];

            //foreach( XYZ p in pts )
            //{
            //  profile.Append( appCreation.NewLineBound(
            //    q, p ) );

            //  q = p;
            //}

            List <Curve> profile = new List <Curve>( // 2013
                pts.Length);

            XYZ q = pts[pts.Length - 1];

            foreach (XYZ p in pts)
            {
                //profile.Add( appCreation.NewLineBound( q, p ) ); // 2013
                profile.Add(Line.CreateBound(q, p)); // 2014
                q = p;
            }

            XYZ normal = XYZ.BasisY;

            //WallType wallType
            //  = new FilteredElementCollector( doc )
            //    .OfClass( typeof( WallType ) )
            //    .First<Element>( e
            //      => e.Name.Contains( "Generic" ) )
            //    as WallType;

            WallType wallType
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(WallType))
                  .First <Element>()
                  as WallType;

            Level level
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(Level))
                  .First <Element>(e
                                   => e.Name.Equals("Level 1"))
                  as Level;

            Transaction tx = new Transaction(doc);

            tx.Start("Create Gable Wall");

            //Wall wall = doc.Create.NewWall( // 2012
            //  profile, wallType, level, true, normal );

            Wall wall = Wall.Create( // 2013
                doc, profile, wallType.Id, level.Id, true, normal);

            tx.Commit();

            return(Result.Succeeded);
        }
 public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
 {
     TaskDialog.Show("Revit", "Hello World");
     return(Autodesk.Revit.UI.Result.Succeeded);
 }
Example #51
0
        /// <summary>
        /// The function set value to rotation of the beams and braces
        /// and rotate columns.
        /// </summary>
        public void RotateElement()
        {
            Transaction transaction = new Transaction(m_revit.ActiveUIDocument.Document, "RotateElement");

            transaction.Start();
            try
            {
                ElementSet selection = m_revit.ActiveUIDocument.Selection.Elements;
                foreach (Autodesk.Revit.DB.Element e in selection)
                {
                    FamilyInstance familyComponent = e as FamilyInstance;
                    if (familyComponent == null)
                    {
                        //is not a familyInstance
                        continue;
                    }
                    // if be familyInstance,judge the types of familyInstance
                    if (StructuralType.Beam == familyComponent.StructuralType ||
                        StructuralType.Brace == familyComponent.StructuralType)
                    {
                        // selection is a beam or Brace
                        ParameterSetIterator paraIterator = familyComponent.Parameters.ForwardIterator();
                        paraIterator.Reset();

                        while (paraIterator.MoveNext())
                        {
                            object    para            = paraIterator.Current;
                            Parameter objectAttribute = para as Parameter;
                            //set generic property named "Cross-Section Rotation"
                            if (objectAttribute.Definition.Name.Equals(AngleDefinitionName))
                            {
                                Double originDegree = objectAttribute.AsDouble();
                                double rotateDegree = m_receiveRotationTextBox * Math.PI / 180;
                                if (!m_isAbsoluteChecked)
                                {
                                    // absolute rotation
                                    rotateDegree += originDegree;
                                }
                                objectAttribute.Set(rotateDegree);
                                // relative rotation
                            }
                        }
                    }
                    else if (StructuralType.Column == familyComponent.StructuralType)
                    {
                        // rotate a column
                        Autodesk.Revit.DB.Location columnLocation = familyComponent.Location;
                        // get the location object
                        LocationPoint         pointLocation = columnLocation as LocationPoint;
                        Autodesk.Revit.DB.XYZ insertPoint   = pointLocation.Point;
                        // get the location point
                        double temp = pointLocation.Rotation;
                        //existing rotation
                        Autodesk.Revit.DB.XYZ directionPoint = new Autodesk.Revit.DB.XYZ(0, 0, 1);
                        // define the vector of axis
                        Line   rotateAxis   = Line.CreateUnbound(insertPoint, directionPoint);
                        double rotateDegree = m_receiveRotationTextBox * Math.PI / 180;
                        // rotate column by rotate method
                        if (m_isAbsoluteChecked)
                        {
                            rotateDegree -= temp;
                        }
                        bool rotateResult = pointLocation.Rotate(rotateAxis, rotateDegree);
                        if (rotateResult == false)
                        {
                            TaskDialog.Show("Revit", "Rotate Failed.");
                        }
                    }
                }

                transaction.Commit();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Revit", "Rotate failed! " + ex.Message);
                transaction.RollBack();
            }
        }
Example #52
0
        /// <summary>
        /// Non-recursively list all import instances
        /// in all families used in the current project document.
        /// </summary>
        public Result ExecuteWithoutRecursion(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            FilteredElementCollector instances
                = new FilteredElementCollector(doc);

            instances.OfClass(typeof(FamilyInstance));

            Dictionary <string, Family> families
                = new Dictionary <string, Family>();

            foreach (FamilyInstance i in instances)
            {
                Family family = i.Symbol.Family;
                if (!families.ContainsKey(family.Name))
                {
                    families[family.Name] = family;
                }
            }

            List <string> keys = new List <string>(
                families.Keys);

            keys.Sort();

            foreach (string key in keys)
            {
                Family family = families[key];
                if (family.IsInPlace)
                {
                    Debug.Print("Family '{0}' is in-place.", key);
                }
                else
                {
                    Document fdoc = doc.EditFamily(family);

                    FilteredElementCollector c
                        = new FilteredElementCollector(doc);

                    c.OfClass(typeof(ImportInstance));

                    IList <Element> imports = c.ToElements();

                    int n = imports.Count;

                    Debug.Print(
                        "Family '{0}' contains {1} import instance{2}{3}",
                        key, n, Util.PluralSuffix(n),
                        Util.DotOrColon(n));

                    if (0 < n)
                    {
                        foreach (ImportInstance i in imports)
                        {
                            //string name = i.ObjectType.Name; // 2011
                            string name = doc.GetElement(i.GetTypeId()).Name; // 2012

                            Debug.Print("  '{0}'", name);
                        }
                    }
                }
            }
            return(Result.Failed);
        }
Example #53
0
 Result IExternalCommand.Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
 {
     throw new NotImplementedException();
 }
Example #54
0
        /// <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(Autodesk.Revit.UI.ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.UI.UIApplication revit = commandData.Application;

            m_revit = revit;
            RotateFramingObjectsForm displayForm = new RotateFramingObjectsForm(this);

            displayForm.StartPosition = FormStartPosition.CenterParent;
            ElementSet selection           = revit.ActiveUIDocument.Selection.Elements;
            bool       isSingle            = true; //selection is single object
            bool       isAllFamilyInstance = true; //all is not familyInstance

            // There must be beams, braces or columns selected
            if (selection.IsEmpty)
            {
                // nothing selected
                message = "Please select some beams, braces or columns.";
                return(Autodesk.Revit.UI.Result.Failed);
            }
            else if (1 != selection.Size)
            {
                isSingle = false;
                try
                {
                    if (DialogResult.OK != displayForm.ShowDialog())
                    {
                        return(Autodesk.Revit.UI.Result.Cancelled);
                    }
                }
                catch (Exception)
                {
                    return(Autodesk.Revit.UI.Result.Failed);
                }
                //    return Autodesk.Revit.UI.Result.Succeeded;
                // more than one object selected
            }

            // if the selected elements are familyInstances, try to get their existing rotation
            foreach (Autodesk.Revit.DB.Element e in selection)
            {
                FamilyInstance familyComponent = e as FamilyInstance;
                if (familyComponent != null)
                {
                    if (StructuralType.Beam == familyComponent.StructuralType ||
                        StructuralType.Brace == familyComponent.StructuralType)
                    {
                        // selection is a beam or brace
                        string returnValue = this.FindParameter(AngleDefinitionName, familyComponent);
                        displayForm.rotationTextBox.Text = returnValue.ToString();
                    }
                    else if (StructuralType.Column == familyComponent.StructuralType)
                    {
                        // selection is a column
                        Location      columnLocation = familyComponent.Location;
                        LocationPoint pointLocation  = columnLocation as LocationPoint;
                        double        temp           = pointLocation.Rotation;
                        string        output         = (Math.Round(temp * 180 / (Math.PI), 3)).ToString();
                        displayForm.rotationTextBox.Text = output;
                    }
                    else
                    {
                        // other familyInstance can not be rotated
                        message = "It is not a beam, brace or column.";
                        elements.Insert(familyComponent);
                        return(Autodesk.Revit.UI.Result.Failed);
                    }
                }
                else
                {
                    if (isSingle)
                    {
                        message = "It is not a FamilyInstance.";
                        elements.Insert(e);
                        return(Autodesk.Revit.UI.Result.Failed);
                    }
                    // there is some objects is not familyInstance
                    message = "They are not FamilyInstances";
                    elements.Insert(e);
                    isAllFamilyInstance = false;
                }
            }

            if (isSingle)
            {
                try
                {
                    if (DialogResult.OK != displayForm.ShowDialog())
                    {
                        return(Autodesk.Revit.UI.Result.Cancelled);
                    }
                }
                catch (Exception)
                {
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }

            if (isAllFamilyInstance)
            {
                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            else
            {
                //output error information
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Example #55
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)

        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            try
            {
                using (Transaction t = new Transaction(doc, "Correct grid bubbles"))
                {
                    t.Start();
                    foreach (ElementId elemId in uidoc.Selection.GetElementIds())
                    {
                        Element SelectedElem = doc.GetElement(elemId);
                        if (SelectedElem is DatumPlane)
                        {
                            DatumPlane xGrid = SelectedElem as DatumPlane;

                            IList <Curve> CurvesInGrid = xGrid.GetCurvesInView(DatumExtentType.ViewSpecific, uidoc.ActiveView);

                            Curve cv = CurvesInGrid.First(); // only one segment grids allowed

                            XYZ cvStart = cv.GetEndPoint(0);
                            XYZ cvEnd   = cv.GetEndPoint(1);

                            XYZ cvTop  = null;
                            XYZ cvLeft = null;

                            #region FIND TOP AND LEFT
                            if (Convert.ToInt32(cvStart.Y) == Convert.ToInt32(cvEnd.Y)) // then its a horizontal line
                            {
                                if (cvStart.X < cvEnd.X)                                // drawn left to right, keep start    X--------->
                                {
                                    cvLeft = cvStart;
                                }

                                else if (cvStart.X > cvEnd.X) // drawn right to left, keep end    <---------X
                                {
                                    cvLeft = cvEnd;
                                }
                            }

                            else if (Convert.ToInt32(cvStart.X) == Convert.ToInt32(cvEnd.X)) // then its a vertical
                            {
                                if (cvStart.Y < cvEnd.Y)                                     // drawn bottom to top, keep end
                                {
                                    cvTop = cvEnd;
                                }

                                else if (cvStart.Y > cvEnd.Y) // drawn top to bottom, keep start
                                {
                                    cvTop = cvStart;
                                }
                            }
                            #endregion

                            // Use top and left, and start and end to find which endpoint to turn on

                            if ((cvLeft != null && cvLeft.IsAlmostEqualTo(cvStart)) || (cvTop != null && cvTop.IsAlmostEqualTo(cvStart))) // the grid was drawn correctly
                            {
                                xGrid.ShowBubbleInView(DatumEnds.End0, uidoc.ActiveView);
                                xGrid.HideBubbleInView(DatumEnds.End1, uidoc.ActiveView);
                            }

                            else if ((cvLeft != null && cvLeft.IsAlmostEqualTo(cvEnd)) || cvTop != null && cvTop.IsAlmostEqualTo(cvEnd)) // the grid was drawn the other way around
                            {
                                xGrid.ShowBubbleInView(DatumEnds.End1, uidoc.ActiveView);
                                xGrid.HideBubbleInView(DatumEnds.End0, uidoc.ActiveView);
                            }
                        }
                    }

                    t.Commit();
                }


                return(Result.Succeeded);
            }

            catch (Exception ex)
            {
                Utils.CatchDialog(ex);
                return(Result.Failed);
            }
        }
Example #56
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 (Transaction t = new Transaction(doc))
            {
                t.Start("Create Steel Stair Beams");

                // Check whether the required family is loaded:

                FilteredElementCollector collector
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(Family));

                // If the family is not already loaded, do so:

                if (!collector.Any <Element>(
                        e => e.Name.Equals(FamilyName)))
                {
                    FamilySymbol symbol;

                    if (!doc.LoadFamilySymbol(
                            _family_path, SymbolName, out symbol))
                    {
                        message = string.Format(
                            "Unable to load '{0}' from '{1}'.",
                            SymbolName, _family_path);

                        t.RollBack();

                        return(Result.Failed);
                    }
                }

                try
                {
                    // Create a couple of connected beams:

                    BeamCreator s = new BeamCreator(doc);

                    s.Run();

                    t.Commit();

                    return(Result.Succeeded);
                }
                catch (Exception ex)
                {
                    message = ex.Message;

                    t.RollBack();

                    return(Result.Failed);
                }
            }
        }
Example #57
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            #region Assertions
            Debug.Assert(0 == (int)DisplayUnitType.DUT_METERS, _s);
            Debug.Assert(1 == (int)DisplayUnitType.DUT_CENTIMETERS, _s);
            Debug.Assert(2 == (int)DisplayUnitType.DUT_MILLIMETERS, _s);
            Debug.Assert(3 == (int)DisplayUnitType.DUT_DECIMAL_FEET, _s);
            Debug.Assert(4 == (int)DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES, _s);
            Debug.Assert(5 == (int)DisplayUnitType.DUT_FRACTIONAL_INCHES, _s);
            Debug.Assert(6 == (int)DisplayUnitType.DUT_DECIMAL_INCHES, _s);
            Debug.Assert(7 == (int)DisplayUnitType.DUT_ACRES, _s);
            Debug.Assert(8 == (int)DisplayUnitType.DUT_HECTARES, _s);
            Debug.Assert(9 == (int)DisplayUnitType.DUT_METERS_CENTIMETERS, _s);
            Debug.Assert(10 == (int)DisplayUnitType.DUT_CUBIC_YARDS, _s);
            Debug.Assert(11 == (int)DisplayUnitType.DUT_SQUARE_FEET, _s);
            Debug.Assert(12 == (int)DisplayUnitType.DUT_SQUARE_METERS, _s);
            Debug.Assert(13 == (int)DisplayUnitType.DUT_CUBIC_FEET, _s);
            Debug.Assert(14 == (int)DisplayUnitType.DUT_CUBIC_METERS, _s);
            Debug.Assert(15 == (int)DisplayUnitType.DUT_DECIMAL_DEGREES, _s);
            Debug.Assert(16 == (int)DisplayUnitType.DUT_DEGREES_AND_MINUTES, _s);
            Debug.Assert(17 == (int)DisplayUnitType.DUT_GENERAL, _s);
            Debug.Assert(18 == (int)DisplayUnitType.DUT_FIXED, _s);
            Debug.Assert(19 == (int)DisplayUnitType.DUT_PERCENTAGE, _s);
            Debug.Assert(20 == (int)DisplayUnitType.DUT_SQUARE_INCHES, _s);
            Debug.Assert(21 == (int)DisplayUnitType.DUT_SQUARE_CENTIMETERS, _s);
            Debug.Assert(22 == (int)DisplayUnitType.DUT_SQUARE_MILLIMETERS, _s);
            Debug.Assert(23 == (int)DisplayUnitType.DUT_CUBIC_INCHES, _s);
            Debug.Assert(24 == (int)DisplayUnitType.DUT_CUBIC_CENTIMETERS, _s);
            Debug.Assert(25 == (int)DisplayUnitType.DUT_CUBIC_MILLIMETERS, _s);
            Debug.Assert(26 == (int)DisplayUnitType.DUT_LITERS, _s);
            #endregion // Assertions

            MapDutToUt map_dut_to_ut = new MapDutToUt();

            DisplayUnitType n
                = DisplayUnitType.DUT_GALLONS_US;

            Debug.Print("Here is a list of the first {0} "
                        + "display unit types with official Revit API "
                        + "LabelUtils, hard-coded The Building Coder "
                        + "abbreviations and valid unit symbols:\n",
                        (int)n - 1);

            string unit_types, valid_unit_symbols;

            for (DisplayUnitType i = DisplayUnitType
                                     .DUT_METERS; i < n; ++i)
            {
                List <string> uts = new List <string>(
                    map_dut_to_ut[i]
                    .Select <UnitType, string>(
                        u => u.ToString().Substring(3)));

                int m = uts.Count;

                unit_types = 4 > m
          ? string.Join(", ", uts)
          : string.Format("{0}, {1} and {2} more",
                          uts[0], uts[1], m - 2);

                valid_unit_symbols = string.Join(", ",
                                                 FormatOptions.GetValidUnitSymbols(i)
                                                 .Where(u => UnitSymbolType.UST_NONE != u)
                                                 .Select <UnitSymbolType, string>(
                                                     u => LabelUtils.GetLabelFor(u)
                                                     + "/" + Util.UnitSymbolTypeString(u)));

                Debug.Print("{0,6} - {1} - {2}: {3}",
                            Util.DisplayUnitTypeAbbreviation[(int)i],
                            LabelUtils.GetLabelFor(i),
                            unit_types,
                            //i
                            //UnitFormatUtils.Format( UnitType. ???
                            //UnitUtils.ConvertFromInternalUnits( 1, i ),
                            valid_unit_symbols);
            }
            return(Result.Succeeded);
        }
Example #58
0
 public Autodesk.Revit.UI.Result Execute(ExternalCommandData revit,
                                         ref string message,
                                         ElementSet elements)
 {
     return(Autodesk.Revit.UI.Result.Succeeded);
 }
Example #59
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            if (commandData == null)
            {
                return(Result.Failed);
            }

            if (!System.IO.Directory.Exists(Constants.DefaultExportDirectory))
            {
                System.IO.Directory.CreateDirectory(Constants.DefaultExportDirectory);
            }

            if (string.IsNullOrEmpty(FileUtilities.GetCentralFileName(commandData.Application.ActiveUIDocument.Document)))
            {
                WindowManager.ShowMessageBox("FAIL", "Please save the file before continuing");
                return(Result.Failed);
            }

            var uidoc = commandData.Application.ActiveUIDocument;

            if (uidoc == null)
            {
                return(Result.Failed);
            }

            var manager = new Manager(uidoc);
            var log     = new ExportLog();
            var vm      = new ViewModels.SCexportViewModel(manager);
            var wm      = WindowManager;

            wm.ShowDialog(vm, null, ViewModels.SCexportViewModel.DefaultWindowSettings);

            if (vm.CloseStatus != ViewModels.SCexportViewModel.CloseMode.Exit)
            {
                string exportType = string.Empty;

                switch (vm.CloseStatus)
                {
                case ViewModels.SCexportViewModel.CloseMode.Export:
                    exportType = "Exporting";
                    break;

                case ViewModels.SCexportViewModel.CloseMode.Print:
                case ViewModels.SCexportViewModel.CloseMode.PrintA3:
                case ViewModels.SCexportViewModel.CloseMode.PrintA2:
                    exportType = "Printing";
                    break;
                }

                var progressVm = new ViewModels.ProgressMonitorViewModel
                {
                    MaximumValue = vm.SelectedSheets.Count, Value = 0
                };

                log.Clear();
                log.Start(exportType + " Started.");

                WindowManager.ShowWindow(progressVm, null, ViewModels.ProgressMonitorViewModel.DefaultWindowSettings);

                foreach (var sheet in vm.SelectedSheets)
                {
                    progressVm.ProgressSummary += @" --> " + exportType + @" " + sheet.FullExportName + "...";

                    switch (vm.CloseStatus)
                    {
                    case ViewModels.SCexportViewModel.CloseMode.Export:
                        manager.ExportSheet(sheet, log);
                        break;

                    case ViewModels.SCexportViewModel.CloseMode.Print:
                        manager.Print(sheet, manager.PrinterNameLargeFormat, 1, log);
                        break;

                    case ViewModels.SCexportViewModel.CloseMode.PrintA3:
                        manager.Print(sheet, manager.PrinterNameA3, 3, log);
                        break;

                    case ViewModels.SCexportViewModel.CloseMode.PrintA2:
                        manager.Print(sheet, manager.PrinterNameLargeFormat, 2, log);
                        break;

                    default:
                        return(Result.Succeeded);
                    }

                    progressVm.Value++;
                    string niceTime = string.Format(
                        System.Globalization.CultureInfo.CurrentCulture,
                        "OK  [ time {0:hh\\.mm\\:ss}  total {1:hh\\.mm\\:ss}  ~remaining {2:hh\\.mm\\:ss}]",
                        log.LastItemElapsedTime,
                        log.TimeSinceStart,
                        System.TimeSpan.FromTicks(log.TimeSinceStart.Ticks / progressVm.Value * (progressVm.MaximumValue - progressVm.Value)));
                    progressVm.ProgressSummary += niceTime + System.Environment.NewLine;

                    if (progressVm.CancelPressed)
                    {
                        break;
                    }
                }

                log.Stop("Finished");
                progressVm.Stop(log);
                progressVm.ProcessComplete = true;
            }

            if (manager.ShowExportLog || log.Errors > 0)
            {
                var exportLogViewModel = new ViewModels.ExportLogViewModel(log);
                WindowManager.ShowDialog(exportLogViewModel, null, ViewModels.ExportLogViewModel.DefaultWindowSettings);
            }

            return(Result.Succeeded);
        }
    public Result Execute( 
      ExternalCommandData commandData, 
      ref string message, 
      ElementSet elements )
    {
      var doc = commandData.Application.ActiveUIDocument.Document;

      const string materialName = "Concrete";

      FilteredElementCollector collector =
          new FilteredElementCollector( doc );

      var sw = Stopwatch.StartNew();
      var materialsLinq =
          doc
              .Settings
              .Materials
              .OfType<Material>()
              .ToList();
      sw.Stop();
      Debug.Print( "LINQ: Elapsed time: {0}\tMaterials count: {1}", sw.Elapsed, materialsLinq.Count );

      sw = Stopwatch.StartNew();
      var materials = collector
          .OfClass( typeof( Material ) )
          .OfType<Material>()
          .ToList();
      sw.Stop();
      Debug.Print( "FilteredElementCollector: Elapsed time: {0}\tMaterials count: {1}", sw.Elapsed, materials.Count );

      Debug.Print( "Document.Settings.Materials count: {0}", doc.Settings.Materials.Size );

  #region using extension methods

      var materialsInDocument = doc.GetMaterials();

      var concreteMaterial = doc.Settings.Materials
        .GetMaterialByName( materialName );

  #endregion

      var materialsRetrievingViaCollectorButNotInDocumentSettings =
          materials
              .Except( materialsLinq, new MaterialComparer() )
              .ToList();

      // ******
      // Materials.get_Item required transaction
      // Why? I'm just read data
      // ******
      var tx = new Transaction( doc, "Get Material" );
      tx.Start();

      // ******
      // NullReferencException throws here if
      // Materials collection contains null
      // ******
      var material = doc.Settings.Materials.get_Item( materialName );

      tx.RollBack();

      return Result.Succeeded;
    }