Assign Shared Parameters to Family (CSharp Macro)

Assign Shared Parameters to Family (CSharp Macro)

dwightduronidavy
Enthusiast Enthusiast
981 Views
14 Replies
Message 1 of 15

Assign Shared Parameters to Family (CSharp Macro)

dwightduronidavy
Enthusiast
Enthusiast

Dear all,

I have written (prompted) an application macro to retrieve shared parameters (from shared parameters file) and assign to a specific family. However, I keep getting similar error messages [see attached]. Any help would be very much appreciated.

MACRO

using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI.Selection;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace DDA_CSharpModule8
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.DB.Macros.AddInId("4BE8D9CF-2B20-4F03-A56B-6B9C6AA11B06")]
public partial class ThisApplication
{
private void Module_Startup(object sender, EventArgs e)
{

}

private void Module_Shutdown(object sender, EventArgs e)
{

}

#region Revit Macros generated code

private void InternalStartup()
{
this.Startup += new System.EventHandler(Module_Startup);
this.Shutdown += new System.EventHandler(Module_Shutdown);
}

#endregion

public void AssignSharedParametersMarkers()
{
UIApplication uiapp = new UIApplication(this.Application);
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;

string sharedParameterFilePath = "C:\\Users\\dda\\OneDrive - XXXXX\\Documents\\01. Revit Families\\XXXX_Shared_Parameters_1.1.txt";
string familyName = "TestIVCoordCube";
string parameterGroupName = "Parametrics";
string[] parameters = { "CoordIssue_Eastings", "CoordIssue_Northings", "CoordIssue_Elev" };

try
{
// Check if shared parameter file exists
if (!File.Exists(sharedParameterFilePath))
{
TaskDialog.Show("Error", string.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
return;
}

// Set the shared parameter file in Revit
Autodesk.Revit.ApplicationServices.Application app = doc.Application;
app.SharedParametersFilename = sharedParameterFilePath;

// Open the shared parameter file
DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
if (sharedParameterFile == null)
{
TaskDialog.Show("Error", "Unable to open the shared parameter file.");
return;
}

using (Transaction transaction = new Transaction(doc, "Assign Shared Parameters to Family"))
{
transaction.Start();

// Find the required family in the project
FilteredElementCollector familyInstances = new FilteredElementCollector(doc)
.OfCategory(BuiltInCategory.OST_SpecialityEquipment)
.WhereElementIsNotElementType();

foreach (Element element in familyInstances)
{
FamilyInstance familyInstance = element as FamilyInstance;
if (familyInstance != null && familyInstance.Name.Equals(familyName, StringComparison.OrdinalIgnoreCase))
{
Family family = familyInstance.Symbol.Family;

// Open the family document for editing
Document familyDoc = doc.EditFamily(family);

foreach (string parameterName in parameters)
{
// Check if the parameter already exists
bool parameterExists = familyDoc.FamilyManager.Parameters
.Cast<FamilyParameter>()
.Any(param => param.Definition.Name == parameterName);

if (!parameterExists)
{
// Get the shared parameter definition
DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
if (group == null)
{
TaskDialog.Show("Error", string.Format("Parameter group not found: {0}", parameterGroupName));
return;
}

Definition definition = group.Definitions.get_Item(parameterName);
if (definition is ExternalDefinition externalDefinition)
{
// Create a new shared parameter
familyDoc.FamilyManager.AddParameter(
externalDefinition,
GroupTypeId.Data,
true
);
}
else
{
TaskDialog.Show("Error", string.Format("Invalid definition for parameter: {0}", parameterName));
return;
}
}
}

// Save and reload the family into the project
familyDoc.Save();
familyDoc.Close();
}
}

transaction.Commit();
TaskDialog.Show("Success", string.Format("Shared parameters assigned successfully to family: {0}", familyName));
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", string.Format("An error occurred: {0}", ex.Message));
}
}
}
}

0 Likes
Accepted solutions (1)
982 Views
14 Replies
Replies (14)
Message 2 of 15

scgq425
Advocate
Advocate

Hi @dwightduronidavy :
this application type is error , you can change to this :


UIApplication uiapp = new UIApplication(this.Application);

and the file need to imprt this reference and write `using System.IO`:

scgq425_0-1733362107403.png

the last , in marco likely cant use the lasted c# version , you can change the quick code to some older write style :

Definition definition = group.Definitions.get_Item(parameterName);
	ExternalDefinition externalDefinition = definition  as ExternalDefinition;
	if (externalDefinition ==  null)
	{
			// Create a new shared parameter
			familyDoc.FamilyManager.AddParameter(
			externalDefinition,
			GroupTypeId.Data,
			true
			);
	}
	else
	{
			TaskDialog.Show("Error", string.Format("Invalid definition for parameter: {0}", parameterName));
			return;
	}

 

--- 

this is all code , you can run in you revit , and debug again , holp to help you .

/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2024/12/5
 * Time: 9:15
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace A
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("DC4F5661-F13E-487C-952B-F7A3DB8394CC")]
	public partial class ThisDocument
	{
		private void Module_Startup(object sender, EventArgs e)
		{

		}

		private void Module_Shutdown(object sender, EventArgs e)
		{

		}

		#region Revit Macros generated code
		private void InternalStartup()
		{
			this.Startup += new System.EventHandler(Module_Startup);
			this.Shutdown += new System.EventHandler(Module_Shutdown);
		}
		#endregion
		
		public void AssignSharedParametersMarkers()
{
var uiapp = Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;

string sharedParameterFilePath = "D:\\ShareSample.txt";
string familyName = "TestIVCoordCube";
string parameterGroupName = "Parametrics";
string[] parameters = { "CoordIssue_Eastings", "CoordIssue_Northings", "CoordIssue_Elev" };

try
{
// Check if shared parameter file exists
if (!File.Exists(sharedParameterFilePath))
{
TaskDialog.Show("Error", string.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
return;
}

// Set the shared parameter file in Revit
Autodesk.Revit.ApplicationServices.Application app = doc.Application;
app.SharedParametersFilename = sharedParameterFilePath;

// Open the shared parameter file
DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
if (sharedParameterFile == null)
{
TaskDialog.Show("Error", "Unable to open the shared parameter file.");
return;
}

using (Transaction transaction = new Transaction(doc, "Assign Shared Parameters to Family"))
{
transaction.Start();

// Find the required family in the project
FilteredElementCollector familyInstances = new FilteredElementCollector(doc)
.OfCategory(BuiltInCategory.OST_SpecialityEquipment)
.WhereElementIsNotElementType();

foreach (Element element in familyInstances)
{
FamilyInstance familyInstance = element as FamilyInstance;
if (familyInstance != null && familyInstance.Name.Equals(familyName, StringComparison.OrdinalIgnoreCase))
{
Family family = familyInstance.Symbol.Family;

// Open the family document for editing
Document familyDoc = doc.EditFamily(family);

foreach (string parameterName in parameters)
{
// Check if the parameter already exists
bool parameterExists = familyDoc.FamilyManager.Parameters
.Cast<FamilyParameter>()
.Any(param => param.Definition.Name == parameterName);

if (!parameterExists)
{
// Get the shared parameter definition
DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
if (group == null)
{
TaskDialog.Show("Error", string.Format("Parameter group not found: {0}", parameterGroupName));
return;
}

	Definition definition = group.Definitions.get_Item(parameterName);
	ExternalDefinition externalDefinition = definition  as ExternalDefinition;
	if (externalDefinition ==  null)
	{
			// Create a new shared parameter
			familyDoc.FamilyManager.AddParameter(
			externalDefinition,
			GroupTypeId.Data,
			true
			);
	}
	else
	{
			TaskDialog.Show("Error", string.Format("Invalid definition for parameter: {0}", parameterName));
			return;
	}
}
}

// Save and reload the family into the project
familyDoc.Save();
familyDoc.Close();
}
}

transaction.Commit();
TaskDialog.Show("Success", string.Format("Shared parameters assigned successfully to family: {0}", familyName));
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", string.Format("An error occurred: {0}", ex.Message));
}
}
	}
}

LanHui Xu 徐兰辉
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

Blog
LinkedIn
Revit/CAD Development | Steel Product Manager

EESignature

0 Likes
Message 3 of 15

dwightduronidavy
Enthusiast
Enthusiast

Hi scgq425,

Thanks for you help. However, I seems to be getting lots of errors (see below).

dwightduronidavy_0-1733367601305.png

 

0 Likes
Message 4 of 15

scgq425
Advocate
Advocate

Hi @dwightduronidavy :
you can just modify the function , is likely my create a new project different with you project name and if also have problem ,  push you all code  :

AssignSharedParametersMarkers()

 

 

 

LanHui Xu 徐兰辉
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

Blog
LinkedIn
Revit/CAD Development | Steel Product Manager

EESignature

0 Likes
Message 5 of 15

dwightduronidavy
Enthusiast
Enthusiast

Modified function still generate the same errors

0 Likes
Message 6 of 15

scgq425
Advocate
Advocate

Hi @dwightduronidavy :

 you can push you all code about this marco

LanHui Xu 徐兰辉
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

Blog
LinkedIn
Revit/CAD Development | Steel Product Manager

EESignature

0 Likes
Message 7 of 15

dwightduronidavy
Enthusiast
Enthusiast

Herewith code:

using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;

namespace DDA_CSharpModule8
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("DC4F5661-F13E-487C-952B-F7A3DB8394CC")]
    public partial class ThisDocument
    {
        private void Module_Startup(object sender, EventArgs e)
        {

        }

        private void Module_Shutdown(object sender, EventArgs e)
        {

        }

        #region Revit Macros generated code
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(Module_Startup);
            this.Shutdown += new System.EventHandler(Module_Shutdown);
        }
        #endregion
        
        public void AssignSharedParameters()
{
var uiapp = Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;

string sharedParameterFilePath = "C:\\Shared_Parameters_1.1.txt";
string familyName = "TestIVCoordCube";
string parameterGroupName = "Parametrics";
string[] parameters = { "CoordIssue_Eastings""CoordIssue_Northings""CoordIssue_Elev" };

try
{
// Check if shared parameter file exists
if (!File.Exists(sharedParameterFilePath))
{
TaskDialog.Show("Error"string.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
return;
}

// Set the shared parameter file in Revit
Autodesk.Revit.ApplicationServices.Application app = doc.Application;
app.SharedParametersFilename = sharedParameterFilePath;

// Open the shared parameter file
DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
if (sharedParameterFile == null)
{
TaskDialog.Show("Error""Unable to open the shared parameter file.");
return;
}

using (Transaction transaction = new Transaction(doc, "Assign Shared Parameters to Family"))
{
transaction.Start();

// Find the required family in the project
FilteredElementCollector familyInstances = new FilteredElementCollector(doc)
.OfCategory(BuiltInCategory.OST_SpecialityEquipment)
.WhereElementIsNotElementType();

foreach (Element element in familyInstances)
{
FamilyInstance familyInstance = element as FamilyInstance;
if (familyInstance != null && familyInstance.Name.Equals(familyName, StringComparison.OrdinalIgnoreCase))
{
Family family = familyInstance.Symbol.Family;

// Open the family document for editing
Document familyDoc = doc.EditFamily(family);

foreach (string parameterName in parameters)
{
// Check if the parameter already exists
bool parameterExists = familyDoc.FamilyManager.Parameters
.Cast<FamilyParameter>()
.Any(param => param.Definition.Name == parameterName);

if (!parameterExists)
{
// Get the shared parameter definition
DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
if (group == null)
{
TaskDialog.Show("Error"string.Format("Parameter group not found: {0}", parameterGroupName));
return;
}

    Definition definition = group.Definitions.get_Item(parameterName);
    ExternalDefinition externalDefinition = definition  as ExternalDefinition;
    if (externalDefinition ==  null)
    {
            // Create a new shared parameter
            familyDoc.FamilyManager.AddParameter(
            externalDefinition,
            GroupTypeId.Data,
            true
            );
    }
    else
    {
            TaskDialog.Show("Error"string.Format("Invalid definition for parameter: {0}", parameterName));
            return;
    }
}
}

// Save and reload the family into the project
familyDoc.Save();
familyDoc.Close();
}
}

transaction.Commit();
TaskDialog.Show("Success"string.Format("Shared parameters assigned successfully to family: {0}", familyName));
}
}
catch (Exception ex)
{
TaskDialog.Show("Error"string.Format("An error occurred: {0}", ex.Message));
}
}
    }
}

0 Likes
Message 8 of 15

scgq425
Advocate
Advocate

Hi @dwightduronidavy :

i paste this code to my revit ,is ok .

you shoule import the `Systems.IO` and using ` using System.IO;`

and  the import step is for this issue

1. 

scgq425_0-1733377239175.png

2. 

scgq425_2-1733377255098.png

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace DDA_CSharpModule8
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("DC4F5661-F13E-487C-952B-F7A3DB8394CC")]
    public partial class ThisDocument
    {
        private void Module_Startup(object sender, EventArgs e)
        {
        	AssignSharedParameters();
        }

        private void Module_Shutdown(object sender, EventArgs e)
        {

        }

        #region Revit Macros generated code
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(Module_Startup);
            this.Shutdown += new System.EventHandler(Module_Shutdown);
        }
        #endregion
        
        public void AssignSharedParameters()
{
var uiapp = Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;

string sharedParameterFilePath = "C:\\Shared_Parameters_1.1.txt";
string familyName = "TestIVCoordCube";
string parameterGroupName = "Parametrics";
string[] parameters = { "CoordIssue_Eastings", "CoordIssue_Northings", "CoordIssue_Elev" };

try
{
// Check if shared parameter file exists
if (!File.Exists(sharedParameterFilePath))
{
TaskDialog.Show("Error", string.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
return;
}

// Set the shared parameter file in Revit
Autodesk.Revit.ApplicationServices.Application app = doc.Application;
app.SharedParametersFilename = sharedParameterFilePath;

// Open the shared parameter file
DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
if (sharedParameterFile == null)
{
TaskDialog.Show("Error", "Unable to open the shared parameter file.");
return;
}

using (Transaction transaction = new Transaction(doc, "Assign Shared Parameters to Family"))
{
transaction.Start();

// Find the required family in the project
FilteredElementCollector familyInstances = new FilteredElementCollector(doc)
.OfCategory(BuiltInCategory.OST_SpecialityEquipment)
.WhereElementIsNotElementType();

foreach (Element element in familyInstances)
{
FamilyInstance familyInstance = element as FamilyInstance;
if (familyInstance != null && familyInstance.Name.Equals(familyName, StringComparison.OrdinalIgnoreCase))
{
Family family = familyInstance.Symbol.Family;

// Open the family document for editing
Document familyDoc = doc.EditFamily(family);

foreach (string parameterName in parameters)
{
// Check if the parameter already exists
bool parameterExists = familyDoc.FamilyManager.Parameters
.Cast<FamilyParameter>()
.Any(param => param.Definition.Name == parameterName);

if (!parameterExists)
{
// Get the shared parameter definition
DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
if (group == null)
{
TaskDialog.Show("Error", string.Format("Parameter group not found: {0}", parameterGroupName));
return;
}

    Definition definition = group.Definitions.get_Item(parameterName);
    ExternalDefinition externalDefinition = definition  as ExternalDefinition;
    if (externalDefinition ==  null)
    {
            // Create a new shared parameter
            familyDoc.FamilyManager.AddParameter(
            externalDefinition,
            GroupTypeId.Data,
            true
            );
    }
    else
    {
            TaskDialog.Show("Error", string.Format("Invalid definition for parameter: {0}", parameterName));
            return;
    }
}
}

// Save and reload the family into the project
familyDoc.Save();
familyDoc.Close();
}
}

transaction.Commit();
TaskDialog.Show("Success", string.Format("Shared parameters assigned successfully to family: {0}", familyName));
}
}
catch (Exception ex)
{
TaskDialog.Show("Error", string.Format("An error occurred: {0}", ex.Message));
}
}
    }
}

 

 

LanHui Xu 徐兰辉
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

Blog
LinkedIn
Revit/CAD Development | Steel Product Manager

EESignature

0 Likes
Message 9 of 15

dwightduronidavy
Enthusiast
Enthusiast

Hi scgq425,
After undertaking the above, the macro generated the attached errors

dwightduronidavy_0-1733437468374.png

 

0 Likes
Message 10 of 15

dwightduronidavy
Enthusiast
Enthusiast

Herewith new version:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace DDA_CSharpModule12
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("825BFCE5-C65B-410A-A72E-0A280B2F2280")]
    public partial class ThisApplication
    {
        public void AssignSharedParameters()
        {
            // Initialize UIApplication
            UIApplication uiapp = new UIApplication(this.Application); // Corrected to use `uiapp.Application`
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document doc = uidoc.Document;

            string sharedParameterFilePath = "C:\\Shared_Parameters_1.1.txt";
            string familyName = "TestIVCoordCube";
            string parameterGroupName = "Parametrics";
            string[] parameters = { "CoordIssue_Eastings""CoordIssue_Northings""CoordIssue_Elev" };

            try
            {
                // Check if shared parameter file exists
                if (!File.Exists(sharedParameterFilePath))
                {
                    TaskDialog.Show("Error", String.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
                    return;
                }

                // Set the shared parameter file in Revit
                Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                app.SharedParametersFilename = sharedParameterFilePath;

                // Open the shared parameter file
                DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
                if (sharedParameterFile == null)
                {
                    TaskDialog.Show("Error""Unable to open the shared parameter file.");
                    return;
                }

                using (Transaction transaction = new Transaction(doc, "Assign Shared Parameters to Family"))
                {
                    transaction.Start();

                    // Find the required family in the project
                    FilteredElementCollector familyInstances = new FilteredElementCollector(doc)
                        .OfCategory(BuiltInCategory.OST_SpecialityEquipment)
                        .WhereElementIsNotElementType();

                    foreach (Element element in familyInstances)
                    {
                        FamilyInstance familyInstance = element as FamilyInstance;
                        if (familyInstance != null && familyInstance.Name.Equals(familyName, StringComparison.OrdinalIgnoreCase))
                        {
                            Family family = familyInstance.Symbol.Family;

                            // Open the family document for editing
                            Document familyDoc = doc.EditFamily(family);

                            foreach (string parameterName in parameters)
                            {
                                // Check if the parameter already exists
                                bool parameterExists = familyDoc.FamilyManager.Parameters
                                    .Cast<FamilyParameter>()
                                    .Any(param => param.Definition.Name == parameterName);

                                if (!parameterExists)
                                {
                                    // Get the shared parameter definition
                                    DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
                                    if (group == null)
                                    {
                                        TaskDialog.Show("Error", String.Format("Parameter group not found: {0}", parameterGroupName));
                                        return;
                                    }

                                    Definition definition = group.Definitions.get_Item(parameterName);
                                    ExternalDefinition externalDefinition = definition as ExternalDefinition;
                                    if (externalDefinition != null)
                                    {
                                        // Add the shared parameter to the family
                                        familyDoc.FamilyManager.AddParameter(externalDefinition, GroupTypeId.Data, true);
                                    }
                                    else
                                    {
                                        TaskDialog.Show("Error", String.Format("Invalid definition for parameter: {0}", parameterName));
                                        return;
                                    }
                                }
                            }

                            // Save and reload the family into the project
                            familyDoc.Save();
                            familyDoc.Close();
                        }
                    }

                    transaction.Commit();
                    TaskDialog.Show("Success", String.Format("Shared parameters assigned successfully to family: {0}", familyName));
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", String.Format("An error occurred: {0}", ex.Message));
            }
        }
    }
}


Error:
'DDA_CSharpModule12.ThisApplication' does not contain a definition for 'InternalStartup' and no extension method 'InternalStartup' accepting a first argument of type 'DDA_CSharpModule12.ThisApplication' could be found (are you missing a using directive or an assembly reference?) (CS1061) - C:\ProgramData\Autodesk\Revit\Macros\2024\Revit\AppHookup\DDA_CSharpModule12\Source\DDA_CSharpModule12\ThisApplication.Designer.cs:29,18

0 Likes
Message 11 of 15

scgq425
Advocate
Advocate

Hi @dwightduronidavy :
this error is the project name not same with my push name .  and in you push code , you deleted the most import function like this and i give you the step how to success use it and my project with marco :

private void Module_Startup(object sender, EventArgs e)
		{
			TaskDialog.Show("Error", "A");
			AssignSharedParameters();
		}

		private void Module_Shutdown(object sender, EventArgs e)
		{

		}

		#region Revit Macros generated code
		private void InternalStartup()
		{
			this.Startup += new System.EventHandler(Module_Startup);
			this.Shutdown += new System.EventHandler(Module_Shutdown);
		}
		#endregion

this code is necessary for revit marco , so if you want to get a current marco you need to create for this step :

1. 

create a marco :

 

scgq425_0-1733449905255.png

2. import the refernce and paste this code to the current locate , rember the other code dont delte  .

scgq425_1-1733449995706.png

scgq425_2-1733450049294.png

public void AssignSharedParameters()
        {
            // Initialize UIApplication
            UIApplication uiapp = Application; // Corrected to use `uiapp.Application`
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document doc = uidoc.Document;

            string sharedParameterFilePath = "C:\\Shared_Parameters_1.1.txt";
            string familyName = "TestIVCoordCube";
            string parameterGroupName = "Parametrics";
            string[] parameters = { "CoordIssue_Eastings", "CoordIssue_Northings", "CoordIssue_Elev" };

            try
            {
                // Check if shared parameter file exists
                if (!File.Exists(sharedParameterFilePath))
                {
                    TaskDialog.Show("Error", String.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
                    return;
                }

                // Set the shared parameter file in Revit
                Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                app.SharedParametersFilename = sharedParameterFilePath;

                // Open the shared parameter file
                DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
                if (sharedParameterFile == null)
                {
                    TaskDialog.Show("Error", "Unable to open the shared parameter file.");
                    return;
                }

                using (Transaction transaction = new Transaction(doc, "Assign Shared Parameters to Family"))
                {
                    transaction.Start();

                    // Find the required family in the project
                    FilteredElementCollector familyInstances = new FilteredElementCollector(doc)
                        .OfCategory(BuiltInCategory.OST_SpecialityEquipment)
                        .WhereElementIsNotElementType();

                    foreach (Element element in familyInstances)
                    {
                        FamilyInstance familyInstance = element as FamilyInstance;
                        if (familyInstance != null && familyInstance.Name.Equals(familyName, StringComparison.OrdinalIgnoreCase))
                        {
                            Family family = familyInstance.Symbol.Family;

                            // Open the family document for editing
                            Document familyDoc = doc.EditFamily(family);

                            foreach (string parameterName in parameters)
                            {
                                // Check if the parameter already exists
                                bool parameterExists = familyDoc.FamilyManager.Parameters
                                    .Cast<FamilyParameter>()
                                    .Any(param => param.Definition.Name == parameterName);

                                if (!parameterExists)
                                {
                                    // Get the shared parameter definition
                                    DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
                                    if (group == null)
                                    {
                                        TaskDialog.Show("Error", String.Format("Parameter group not found: {0}", parameterGroupName));
                                        return;
                                    }

                                    Definition definition = group.Definitions.get_Item(parameterName);
                                    ExternalDefinition externalDefinition = definition as ExternalDefinition;
                                    if (externalDefinition != null)
                                    {
                                        // Add the shared parameter to the family
                                        familyDoc.FamilyManager.AddParameter(externalDefinition, GroupTypeId.Data, true);
                                    }
                                    else
                                    {
                                        TaskDialog.Show("Error", String.Format("Invalid definition for parameter: {0}", parameterName));
                                        return;
                                    }
                                }
                            }

                            // Save and reload the family into the project
                            familyDoc.Save();
                            familyDoc.Close();
                        }
                    }

                    transaction.Commit();
                    TaskDialog.Show("Success", String.Format("Shared parameters assigned successfully to family: {0}", familyName));
                }
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", String.Format("An error occurred: {0}", ex.Message));
            }
        }
    

 

3.  add the using about  using System.IO; , and use the   AssignSharedParameters() in Module_Startup and then build this project  , this code will run in revit

scgq425_4-1733450252576.png

 

LanHui Xu 徐兰辉
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

Blog
LinkedIn
Revit/CAD Development | Steel Product Manager

EESignature

0 Likes
Message 12 of 15

dwightduronidavy
Enthusiast
Enthusiast

Hi  scgq425

The below code no long throw previous errors, however, now throws the attached error after execution

dwightduronidavy_0-1733456641611.png

which prevents shared parameters being added to the Project Parameters and assigned to the family.




MACRO:
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;


namespace DDA_CSharpModule13
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("C544A221-18AB-4900-B1A5-C9C52D9FFDDE")]   

    public partial class ThisApplication
    {
        private void Module_Startup(object sender, EventArgs e)
        {
            // Add any startup logic here, if needed.
        }

        private void Module_Shutdown(object sender, EventArgs e)
        {
            // Add any cleanup logic here, if needed.
        }

        #region Revit Macros generated code
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(Module_Startup);
            this.Shutdown += new System.EventHandler(Module_Shutdown);
        }
        #endregion

        public void AssignSharedParameters()
        {
            UIApplication uiapp = new UIApplication(this.Application);
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document doc = uidoc.Document;

            string sharedParameterFilePath = "C:\\Shared_Parameters_1.1.txt";
            string parameterGroupName = "Parametrics";
            string[] parameters = { "CoordIssue_Eastings""CoordIssue_Northings""CoordIssue_Elev" };

            try
            {
                if (!File.Exists(sharedParameterFilePath))
                {
                    TaskDialog.Show("Error", String.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
                    return;
                }

                Autodesk.Revit.ApplicationServices.Application app = doc.Application;
                app.SharedParametersFilename = sharedParameterFilePath;

                DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
                if (sharedParameterFile == null)
                {
                    TaskDialog.Show("Error""Unable to open the shared parameter file.");
                    return;
                }

                // Collect family instances in the project
                FilteredElementCollector collector = new FilteredElementCollector(doc)
                    .OfCategory(BuiltInCategory.OST_SpecialityEquipment)
                    .WhereElementIsNotElementType();

                foreach (Element element in collector)
                {
                    FamilyInstance familyInstance = element as FamilyInstance;
                    if (familyInstance != null)
                    {
                        Family family = familyInstance.Symbol.Family;

                        // Open family document outside the transaction
                        Document familyDoc = doc.EditFamily(family);

                        using (Transaction familyTransaction = new Transaction(familyDoc, "Assign Shared Parameters"))
                        {
                            familyTransaction.Start();

                            foreach (string parameterName in parameters)
                            {
                                if (!familyDoc.FamilyManager.Parameters
                                    .Cast<FamilyParameter>()
                                    .Any(p => p.Definition.Name == parameterName))
                                {
                                    DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
                                    if (group == null)
                                    {
                                        TaskDialog.Show("Error", String.Format("Parameter group not found: {0}", parameterGroupName));
                                        familyTransaction.RollBack();
                                        return;
                                    }

                                    Definition definition = group.Definitions.get_Item(parameterName);
                                    ExternalDefinition externalDefinition = definition as ExternalDefinition;
                                    if (externalDefinition != null)
                                    {
                                        familyDoc.FamilyManager.AddParameter(externalDefinition, GroupTypeId.Data, true);
                                    }
                                    else
                                    {
                                        TaskDialog.Show("Error", String.Format("Invalid definition for parameter: {0}", parameterName));
                                        familyTransaction.RollBack();
                                        return;
                                    }
                                }
                            }

                            familyTransaction.Commit();
                        }

                        // Save and close the family document
                        familyDoc.Save();
                        familyDoc.Close();
                    }
                }

                TaskDialog.Show("Success""Shared parameters assigned successfully.");
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", String.Format("An error occurred: {0}", ex.Message));
            }
        }
    }
}

0 Likes
Message 13 of 15

scgq425
Advocate
Advocate

Hi @dwightduronidavy :

this error is you family file is read-only , you can check this like the picture , if is read-only you can cancel this bool or use anthor api is SaveAs();

also in you code , if loop every instance will " push the file is already exits exception" , beacuse you add paramater to all instance , but in logic you should add paramater in the ftamily document and re-load this . so you can change the file read-only and try again.

scgq425_0-1733466187496.png

///familyDoc.SaveAs("E:\\A\\" + family.Name + ".rfa");

 

 

LanHui Xu 徐兰辉
Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

Blog
LinkedIn
Revit/CAD Development | Steel Product Manager

EESignature

0 Likes
Message 14 of 15

dwightduronidavy
Enthusiast
Enthusiast

Hi @scgq425 

Thank you for the advice. Will take a look over the weekend and let you know how I get on.

Regards,

Dwight

0 Likes
Message 15 of 15

dwightduronidavy
Enthusiast
Enthusiast
Accepted solution

Dear all,

Herewith updated Macro which successfully retrieves parameters from a shared parameters file; adds to Project Parameters and then assign to family:

using System;
using System.IO;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace DDA_CSharpModule13
{
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.DB.Macros.AddInId("C544A221-18AB-4900-B1A5-C9C52D9FFDDE")]
    public partial class ThisApplication
    {
        private void Module_Startup(object sender, EventArgs e)
        {
            // Add any startup logic here, if needed.
        }

        private void Module_Shutdown(object sender, EventArgs e)
        {
            // Add any cleanup logic here, if needed.
        }

        #region Revit Macros generated code
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(Module_Startup);
            this.Shutdown += new System.EventHandler(Module_Shutdown);
        }
        #endregion

        public void AssignSharedParametersAsProjectParameters()
        {
            UIApplication uiapp = new UIApplication(this.Application);
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document doc = uidoc.Document;

            string sharedParameterFilePath = "C:\\Shared_Parameters_1.1.txt";
            string parameterGroupName = "Parametrics";
            string[] parameters = { "CoordIssue_Eastings""CoordIssue_Northings""CoordIssue_Elev" };

            try
            {
                if (!File.Exists(sharedParameterFilePath))
                {
                    TaskDialog.Show("Error", String.Format("Shared parameter file not found at: {0}", sharedParameterFilePath));
                    return;
                }

                Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                app.SharedParametersFilename = sharedParameterFilePath;

                DefinitionFile sharedParameterFile = app.OpenSharedParameterFile();
                if (sharedParameterFile == null)
                {
                    TaskDialog.Show("Error""Unable to open the shared parameter file.");
                    return;
                }

                DefinitionGroup group = sharedParameterFile.Groups.get_Item(parameterGroupName);
                if (group == null)
                {
                    TaskDialog.Show("Error", String.Format("Parameter group not found: {0}", parameterGroupName));
                    return;
                }

                // Create a CategorySet for the categories you want the parameter to apply to.
                CategorySet categorySet = app.Create.NewCategorySet();
                categorySet.Insert(doc.Settings.Categories.get_Item(BuiltInCategory.OST_SpecialityEquipment));

                using (Transaction t = new Transaction(doc, "Add Project Parameters"))
                {
                    t.Start();

                    foreach (string parameterName in parameters)
                    {
                        Definition definition = group.Definitions.get_Item(parameterName);
                        if (definition == null)
                        {
                            TaskDialog.Show("Error", String.Format("Parameter not found in shared file: {0}", parameterName));
                            continue;
                        }

                        // Create an instance binding
                        InstanceBinding binding = app.Create.NewInstanceBinding(categorySet);

                        // Insert the parameter into the project using GroupTypeId instead of BuiltInParameterGroup
                        bool inserted = doc.ParameterBindings.Insert(definition, binding, GroupTypeId.Data);

                        if (!inserted)
                        {
                            TaskDialog.Show("Warning", String.Format("Parameter '{0}' may already exist or could not be inserted.", parameterName));
                        }
                    }

                    t.Commit();
                }

                TaskDialog.Show("Success""Project parameters added successfully.");
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error", String.Format("An error occurred: {0}", ex.Message));
            }
        }
    }
}
@scgq425 thank you for you valuable help as usual

0 Likes