Quantcast
Channel: All Revit API Forum posts
Viewing all 66715 articles
Browse latest View live

Imported Object Styles

$
0
0

Hi,

Is there any possibilities to collect Object Styles (Imported Object Styles) details from Revit API?. 

Please refer attached image.

Thanks and Regards,

Vinoth Kumar


Re: Imported Object Styles

$
0
0

Hi  ,

try using the below code

 FilteredElementCollector colle = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_ImportObjectStyles)

I hope this helps.

Re: PlanViewRange from Plan Region

$
0
0
private void ViewRange(Document doc, View view)
{
    if (view is ViewPlan)
    {
        ViewPlan viewPlan = view as ViewPlan;
        PlanViewRange viewRange = viewPlan.GetViewRange();

        ElementId topClipPlane = viewRange.GetLevelId(PlanViewPlane.TopClipPlane);
        double dOffset = viewRange.GetOffset(PlanViewPlane.TopClipPlane);

        if (topClipPlane.IntegerValue > 0)
        {
            Element levelAbove = doc.GetElement(topClipPlane);
            TaskDialog.Show(view.Name, "Top Clip Plane: " + levelAbove.Name + "\r\nTop Offset: " + dOffset + " ft");
        }
    }
}

Re: Revit crashes when exiting add-in WPF application

$
0
0

Thank you for the effort to again answer a question to a "topic that has probably come up and been answered a few hundred times in the past" ^^.


However even with your link and your suggestions my problem remains. I now tried the following setup:

 

using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;


namespace eqdb_revit_addin
{
    [Transaction(TransactionMode.Manual)]
    public class AddinEntryPoint : IExternalCommand
    {


        // This is the entry point in which the add-in starts:
        [STAThread]
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {

            IExternalEventHandler eventHandler = new MyExternalEvent();
            ExternalEvent externalEvent = ExternalEvent.Create(eventHandler);
            externalEvent.Raise();

            return Result.Succeeded;
        }

    } // end class
} // end namespace

 

With MyExternalEvent derived from your link:

using System.Windows;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

class MyExternalEvent : IExternalEventHandler
{
    public void Execute(UIApplication uiapp)
    {
        UIDocument uidoc = uiapp.ActiveUIDocument;
        if( null == uidoc )
        {
             return; // no document, nothing to do
        }
        Document doc = uidoc.Document;
        using( Transaction tx = new Transaction(doc))
        {
            tx.Start("MyEvent");
            var application = new Application();
            int returnCode = application.Run(new Window());
            tx.Commit();
        }
    }
    public string GetName()
    {
        return "my event";
    }
}

 

Of course the question remains what I am still missing but I'm also asking myself if the Execute() Method in my AddinEntryPoint has not already been just that Revit event handler that you mentioned.

Re: How to get DuctSystemType color

$
0
0

Does anyone know the answer to this question?
I also need to set the color for the system type via API

PrintManager - Suppress the save dialog for filename

$
0
0

I'm using the PrintManager API to submit a print, I'm using the Win 10 printer driver "Microsoft Print to PDF" as I would like a PDF.

Although I'm setting the property .PrintToFilename = "{my folder and filename.pdf}" I'm still getting a dialog appear asking user for PDF file and location.

 

Does anyone know of a way to suppress this dialog from appearing and for the driver to take the value assigned in the Revit PrintManager API property?

Thanks

Re: Revit crashes when exiting add-in WPF application

$
0
0

You might try using modal dialog boxes, at least to start with.

 

Use MessageBox.ShowDialog instead of MessageBox.Show.

 

 

SpectrumBIM Gamut crashes Revit

$
0
0

Hello,

 

I am a developer at Chaos Group and I develop V-Ray for Revit. Recently a customer contacted us and told us that Revit crashes when V-Ray for Revit starts. The bad thing is that the stack trace indicates that crash occurs in the SpectrumBIM Gamut code so we can't really do anything to fix this. Are all Revit third-party assemblies loaded in the same ApplicationDomain? This seems to be the case.

 

There is V-Ray Next for Revit installed and when it starts SpectrumBIM Gamut crashes Revit.

 

When V-Ray Next for Revit starts, it loads a Grpc Server. This causes the Grpc assembly to be loaded. It appears that SpectrumBIM Gamut listens for the CurrentDomain.AssemblyResolve event and when it receives it it tries to do something. The the exception occurs. Unfortunately, I cannot fix anything because the code is not mine, but SpectrumBIM's, i.e. the crash happens in SPTR.Gamut.Revit.App.GamutApp.CurrentDomain_AssemblyResolve(Object sender, ResolveEventArgs args)

 

 Here is the full stack trace:

 

System.TypeInitializationException: The type initializer for 'Grpc.Core.Internal.PlatformApis' threw an exception. ---> System.IO.FileLoadException: Could not load file or assembly 'UnityEngine' or one of its dependencies. An argument was out of its legal range. (Exception from HRESULT: 0x80131502) ---> System.ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at SPTR.Gamut.Revit.App.GamutApp.CurrentDomain_AssemblyResolve(Object sender, ResolveEventArgs args)
at System.AppDomain.OnAssemblyResolveEvent(RuntimeAssembly assembly, String assemblyFullName)
— End of inner exception stack trace —
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName)
at Grpc.Core.Internal.PlatformApis..cctor()
— End of inner exception stack trace —
at Grpc.Core.Internal.PlatformApis.get_IsXamarinIOS()
at Grpc.Core.GrpcEnvironment.get_IsNativeShutdownAllowed()
at Grpc.Core.GrpcEnvironment.GrpcNativeInit()
at Grpc.Core.GrpcEnvironment..ctor()
at Grpc.Core.GrpcEnvironment.AddRef()
at Grpc.Core.Server..ctor(IEnumerable`1 options)
at Chaos.VRay4Revit.Addin.AssetEditor.AssetEditorServer.Start()

 

Chaos.VRay4Revit.Addin.AssetEditor.AssetEditorServer.Start() triggers the whole sequence of events but the crash occurs in SPTR.Gamut.Revit.App.GamutApp.CurrentDomain_AssemblyResolve

 

Has anyone encountered anything remotely similar, i.e. two completely different Revit addons cannot work together because all of their assemblies are loaded in one and the same application domain?

 

Thanks in advance.


Re: How to get default button name

Re: Use of Align function programatically to change the alignment of Tiles for f

$
0
0

Hey,

 

I needed to do alignments on a series of walls, so created a Python solution in Dynamo with the help of Alban de 

Chasteigner the link is here:

 

https://forum.dynamobim.com/t/align-surface-patterns-to-wall-edge/44646/5?u=mark.ackerley

 

The bulk of (Alban's) work is this...

 

#thanks to Alban de Chasteigner (Genius Loci) and Fair59
import clr
import sys

pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)

import string

# Import Element wrapper extension methods
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
# toProtoType etc.
clr.ImportExtensions(Revit.GeometryConversion)

# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument

# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
import System
from System import Guid

walls = UnwrapElement(IN[0])
refPlanesWall = UnwrapElement(IN[1])
indexRefs = IN[2]

refDimensions = []
for wall, refPlanes, indexes in zip(walls, refPlanesWall, indexRefs ):
	#get the external face reference of the wall as an array
	extFaceRefList = HostObjectUtils.GetSideFaces(wall,ShellLayerType.Exterior)
	#for (the array containing) the external face reference, get it's geometry
	for extFaceRef in extFaceRefList:
		extFace = wall.GetGeometryObjectFromReference(extFaceRef)
		#get the external face surface edges as lines, get the first line (the bottom)
		for	bottomEdgeCurve in extFace.GetEdgesAsCurveLoops()[0]:
			#get the finish point of the line
			corner = bottomEdgeCurve.GetEndPoint(1)
		#Check for model surfacepattern
		material = doc.GetElement(extFace.MaterialElementId)
		patterntype = doc.GetElement(material.SurfacePatternId)
		pattern = patterntype.GetFillPattern()
		#Get number of gridLines in pattern                
		gridCount = pattern.GridCount		
		#Construct StableRepresentation to top face reference
		stableRef = extFaceRef.ConvertToStableRepresentation(doc)
		
		#we want horizontal and vertical refs so we want 2 arrays
		refList = []
		refAll = []
		for hatchindex in range(0, gridCount):
			refAr = ReferenceArray()
			ip=0
			while ip<2:
				#generate an index for each hatch reference
				index = (hatchindex+1) + (ip * gridCount *2)
				#create a string for each hatch reference using the face reference and hatch index
				stableHatchString = stableRef + str.Format("/{0}", index)
				#generate a new reference for each hatch reference using the string
				HatchRef = Reference.ParseFromStableRepresentation(doc, stableHatchString)
				#the hatch reference is both 
				refAr.Append(HatchRef)
				ip += 1
			#refList contains arrays, each containing a pair of references
			#we only want 2 arrays, a horizontal and a vertical
			refAll.append(refAr)
		#we use the index we returned from the reference plane to
		#determine the index we need of the references... there aren't
		#any properties or methods of the reference to determine orientation
		for i in indexes:	
			refList.append(refAll[i])

	#for each wall, we run each refPlane against each reference, 1 hor, 1 vert
	for refAr, refPlane in zip(refList, refPlanes):
		#start a transaction
		TransactionManager.Instance.EnsureInTransaction(doc)
		refDim = doc.Create.NewDimension(doc.ActiveView, Line.CreateBound(XYZ.Zero, XYZ(10, 0, 0)), refAr)		
		ElementTransformUtils.MoveElement(doc, refDim.Id, XYZ(.1, 0, 0))			
		r1 = refDim.References.get_Item(0)
		direction = refDim.Curve.Direction
		hatchDirection = direction.CrossProduct(extFace.FaceNormal).Normalize()
		origin = refDim.Origin.Subtract(direction.Multiply(refDim.Value/2))
		#end transaction
		TransactionManager.Instance.TransactionTaskDone()
		
		stableRef = str.Format("{0}:0:{1}",refPlane.UniqueId,"SURFACE")
		ref2Plane = Reference.ParseFromStableRepresentation(doc,stableRef)
		
		#start a transaction
		TransactionManager.Instance.EnsureInTransaction(doc)
		doc.Create.NewAlignment(doc.ActiveView,ref2Plane,r1)
		#end transaction
		TransactionManager.Instance.TransactionTaskDone()
		
		#start a transaction
		TransactionManager.Instance.EnsureInTransaction(doc)
		translation = origin.Subtract(corner)
		ElementTransformUtils.MoveElement(doc,refPlane.Id,-translation)
		#end transaction
		TransactionManager.Instance.TransactionTaskDone()
		
		refDimensions.append(refDim)

#we don't need the dimensions or reference planes any more
#start a transaction		 
TransactionManager.Instance.EnsureInTransaction(doc)
for refDim in refDimensions:
	doc.Delete(refDim.Id)
for refPlanes in refPlanesWall:
	for refPlanes in refPlanes:
		doc.Delete(refPlanes.Id)
#finish transaction
TransactionManager.Instance.TransactionTaskDone()

OUT = walls

Align Wall Material.gif

 

 

Hopefully that's of interest,

 

Mark

 

Re: Revit crashes when exiting add-in WPF application

$
0
0

Thank you for your suggestion.

In the meantime I checked out some additional templates as suggested by Jeremy Tammik and found out that these appearantly do not create their own WPF Application. It seems like my suspicion was true in the sense that Revit already has its own Application running (I would not be surprised if Revit was also written with WPF). Maybe creating a new Application and shutting it down kills Revit's Application aswell.

 

Opening an empty window without creating a new Application around it did finally work for me! Revit survives closing that one.

 

Now i got a new issue:
If I create new Window by instantiating a custom class of mine which inherits from Window, the add-in crashes immediately without even executing the first line of the constructor. I get an error message like:
"Revit encountered System.IO.FileNotFoundException: The file or assembly "System.Collections,...." or a dependency of it has not been found. The system cannot find the file specified."
Here are my imports:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

 

The confusing part for me is that there are absolutely no compile errors and creating the exact same window outside a Revit add-in context works flawlessly. Another similar custom window of mine shows the same behaviour.

Here is my .csproj:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

    <PropertyGroup>
       <OutputType>Library</OutputType>
       <TargetFramework>netcoreapp3.1</TargetFramework>
       <UseWPF>true</UseWPF>
       <DebugType>portable</DebugType>
        <Platforms>x64</Platforms><!-- Only target x64 systems like the Revit APIs do -->
       <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
   </PropertyGroup>

 

    <ItemGroup>
       <Reference Include="RevitAPI">
          <HintPath>C:\Program Files\Autodesk\Revit 2019\RevitAPI.dll</HintPath>
          <Private>False</Private>
       </Reference>

       <Reference Include="RevitAPIUI">
          <HintPath>C:\Program Files\Autodesk\Revit 2019\RevitAPIUI.dll</HintPath>
          <Private>False</Private>
       </Reference>

       <!-- allows for ifc id generation: -->
       <Reference Include="RevitAPIIFC">
          <HintPath>C:\Autodesk\WI\Autodesk Revit 2019\x64\RVT\PF64\Autodesk\Root\RevitAPIIFC.dll</HintPath>
          <Private>False</Private>
       </Reference>
    </ItemGroup>

 

    <!-- packages installed via dotnet add package: -->
    <ItemGroup>
       <PackageReference Include="Dapper" Version="2.0.30" />
       <PackageReference Include="MySqlConnector" Version="0.61.0" />
    </ItemGroup>

</Project>

Parameter Bindings

$
0
0

Hello all,

 

I am using this code to add categories to existing parameters. Aim is to attach parameters defined in rooms automaticly to the generating walls of the room. I can do this manually via the userinterface, but ReInsert allways fails via API, any Idea?

 

 

            Document doc = target.Document;

            // Get the BingdingMap of current document.
            BindingMap bindingMap = doc.ParameterBindings;
            DefinitionBindingMapIterator it = bindingMap.ForwardIterator();
            it.Reset();
            while (it.MoveNext())
            {
                if (it.Key.Name.Contains(param)) 
                {
                    if (it.Current is InstanceBinding EB)
                    {
                        EB.Categories.Insert(target.Category);
                        bool success = bindingMap.ReInsert(it.Key, EB);
                        return success; // success;
                    }
                    else
                        return false;
                }
            }

Re: Revit crashes when exiting add-in WPF application

$
0
0

I managed to get a WPF usercontrol (or window, I'm really not sure which it is) to work inside one of my Revit Add-ins by following this intro:

 

https://spiderinnet.typepad.com/blog/2011/11/wpf-and-revit-addin-popup-wpf-window-from-external-command-using-c-and-revit-api.html

 

There is also a part 2 and a part 3 which I haven't got to yet.

 

And I haven't managed to get any Revit API code to run from the WPF control yet.  Hopefully, that's next after I read parts 2 and 3, and some more from Jeremy's blogs, and any other info I can find. 

 

Right now the event handlers for my WPF are in the WPF control's code, which doesn't have access to my Revit API stuff.

 

Anyhow, you might try looking through the link.


P.S.  You do have Windows.xaml added as a reference, right?

 

 

Switch focus to active view

$
0
0

Hello All,

 

I am fairly new to Revit API. I am doing some programming which requires selecting point and that command is activated through the dockable pane. The issue that I am running into is when I click on button in usercontrol, it seems that Revit looses focus from drawing area as well as ribbon, I have attached the screenshot for reference. The only way to bring back focus is either click in the active view, which selects point immediately (therefore not desirable), or another way is to click on scroll bars.

 

I tried using SetMainWindow to revithandle, it did not work. This may not contain elements initially.

 

 

ScreenCapture.png

Re: Switch focus to active view


Re: SpectrumBIM Gamut crashes Revit

Re: PrintManager - Suppress the save dialog for filename

Re: Parameter Bindings

Worksharing Monitor for Revit 2019

$
0
0

WSM for my Revit 2019.2 does not display the workshared model properly or not at all - see attachment.

It has kind of gone wors over an period but now it has stopped completly to show anything.

What to do??

Re: SpectrumBIM Gamut crashes Revit

$
0
0

The problem is that it is not our code (V-Ray for Revit) crashing, but another company's code (Gamut App) is crashing because we load the Grpc assembly, they listen for this event and then they crash. We have no control over their code! And our customers are blaming us (Chaos Group) that Revit crashes. Because this happens when V-Ray starts up and loads the Grps assemblies and then their addon throws an exception We can't fix something which is not ours.

 

How should we proceed in such a case? What should we tell them? What answer we should provide to a customer that says your software crashes Revit, when in fact it is not our software?

 

I should basically tell our customer to either choose SpectrumBIM Gamut or V-Ray for Revit because they cannot simultaneously live in the same App Domain in Revit.

 

Maybe Autodesk could log a feature request that every single add-on runs in its own isolated container, i.e. AppDomain?

 

Has Autodesk thought about that different add-ons might fight with each other and in case so what is the best thing to do? If two different add-ons want to use different versions of the same .NET library, lets sat Log4Net, what happens? The first one wins? With their version?

 

Is there a straightforward solution to a huge problem likes this?

 

In fact there might be even a security risk if someone develops a malicious add-on and tries to do funny stuff with other people's add-ons -- either directly or through reflection. Another idea to think about...

Viewing all 66715 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>