project parameters are not shown after transfering it

Hans_Dwe
Enthusiast
Enthusiast

project parameters are not shown after transfering it

Hans_Dwe
Enthusiast
Enthusiast

Hello !! I am working on transferring Project Parameters from a source document to a target document, it worked and showed me in the log that they have been successfully transferred but in the target document when I looked up Manage > project parameters none of these parameters were shown there, so what it could be the problem. and here is a part of the code. Thanks 

 

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

namespace TransferProjectParameter
{
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    public class Class1 : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Document sourceDoc = uiapp.ActiveUIDocument.Document;

            // Collect all project parameters from the source document
            BindingMap sourceBindingMap = sourceDoc.ParameterBindings;
            DefinitionBindingMapIterator iter = sourceBindingMap.ForwardIterator();
            iter.Reset();

            List<Definition> projectParameters = new List<Definition>();

            while (iter.MoveNext())
            {
                Definition def = iter.Key;
                projectParameters.Add(def);
            }

            Document targetDoc = null;
            foreach (Document doc in uiapp.Application.Documents)
            {
                if (!doc.Equals(sourceDoc))
                {
                    targetDoc = doc;
                    break;
                }
            }

            using (Transaction trans = new Transaction(targetDoc, "Copy Project Parameters"))
            {
                trans.Start();

                BindingMap targetBindingMap = targetDoc.ParameterBindings;

                foreach (var def in projectParameters)
                {
                    Binding binding = sourceBindingMap.get_Item(def);
                    if (binding != null)
                    {
                        // Get the parameter group
                        BuiltInParameterGroup paramGroup = (def as InternalDefinition)?.ParameterGroup ?? BuiltInParameterGroup.INVALID;

                        // Add the definition with the same binding to the target document
                        targetBindingMap.Insert(def, binding, paramGroup);
                    }
                }

                trans.Commit();
            }

            List<string> projectParameterNames = projectParameters.Select(p => p.Name).ToList();

            TaskDialog.Show("Transfer Project Parameters", $"{projectParameters.Count} project parameters transferred successfully.");

            return Result.Succeeded;
        }

    }
}
0 Likes
Reply
Accepted solutions (1)
584 Views
9 Replies
Replies (9)

Mohamed_Arshad
Advisor
Advisor

HI @Hans_Dwe 

 

    I checked your code, Most of the things are correct but we can't directly bind other projects' InternalDefintion, we need to convert from InternalDefinition to ExternalDefintion. I added small code snippet as a region and modified your code a little bit, Kindly refer to the below code.

 

Modified Code:

 

using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Xml.Linq;

namespace TransferProjectParameter
{
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    public class Class1 : IExternalCommand
    {
        private string logFilePath = @"C:\log.txt";

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Document sourceDoc = uiapp.ActiveUIDocument.Document;

            // Collect all project parameters from the source document
            BindingMap sourceBindingMap = sourceDoc.ParameterBindings;
            DefinitionBindingMapIterator iter = sourceBindingMap.ForwardIterator();
            iter.Reset();

            List<Definition> projectParameters = new List<Definition>();

            while (iter.MoveNext())
            {
                Definition def = iter.Key;
                projectParameters.Add(def);
            }

            if (projectParameters.Count == 0)
            {
                TaskDialog.Show("Error", "No project parameters found in the source document.");
                return Result.Failed;
            }

            Document targetDoc = null;
            foreach (Document doc in uiapp.Application.Documents)
            {
                if (!doc.Equals(sourceDoc))
                {
                    targetDoc = doc;
                    break;
                }
            }

            if (targetDoc == null)
            {
                TaskDialog.Show("Transfer Project Parameters", "No target document found.");
                return Result.Failed;
            }



            #region Convert Internal Definition to External Defintion

            string originalSharedParameterFile = uiapp.Application.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";
            using (File.Create(tempFile)) { }
            uiapp.Application.SharedParametersFilename = tempFile;

            Dictionary<ExternalDefinition, Definition> extDef = new Dictionary<ExternalDefinition, Definition>();

            foreach (Definition definition in projectParameters)
            {
                ExternalDefinitionCreationOptions creationOpt = new ExternalDefinitionCreationOptions(definition.Name, definition.ParameterType);
                ExternalDefinition def = uiapp.Application.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions.Create(creationOpt) as ExternalDefinition;
                extDef.Add(def, definition);
            }

            uiapp.Application.SharedParametersFilename = originalSharedParameterFile;

            File.Delete(tempFile);

            #endregion

            // Add project parameters to the target document
            using (Transaction trans = new Transaction(targetDoc, "Copy Project Parameters"))
            {
                trans.Start();

                foreach (KeyValuePair<ExternalDefinition,Definition> def in extDef)
                {
                    Binding binding = sourceBindingMap.get_Item(def.Value);

                    if (binding != null)
                    {
                        // Get the parameter group
                        BuiltInParameterGroup paramGroup = (def.Key)?.ParameterGroup ?? BuiltInParameterGroup.INVALID;

                        // Add the definition with the same binding to the target document
                        targetDoc.ParameterBindings.Insert(def.Key, binding, paramGroup);
                    }
                }

                trans.Commit();
            }

            List<string> projectParameterNames = projectParameters.Select(p => p.Name).ToList();

            LogProjectParameters(projectParameterNames);
            TaskDialog.Show("Transfer Project Parameters", $"{projectParameters.Count} project parameters transferred successfully.");

            return Result.Succeeded;
        }

        private void LogProjectParameters(List<string> parameterNames)
        {
            using (StreamWriter sw = new StreamWriter(logFilePath, true))
            {
                foreach (var name in parameterNames)
                {
                    sw.WriteLine(name);
                }

            }
        }
    }
}

 

 

 

Hope this will Helps 🙂

Thanks & Regards,
Mohamed Arshad K

Hans_Dwe
Enthusiast
Enthusiast
Thanks @Mohamed_Arshad for the answer, just by checking it, the part definition.ParameterType there is no definition for the Parametertype. any idea ?
0 Likes

Mohamed_Arshad
Advisor
Advisor

Hi @Hans_Dwe 
  

     To Create ExternalDefinition need to pass the Name and ParameterType in the Constructor, So I use the definition and pass its name and ParameterType to constructor for creating ExternalDefinition.

 

 

ExternalDefinitionCreationOptions creationOpt = new ExternalDefinitionCreationOptions(definition.Name, definition.ParameterType);

 

Hope this will Helps 🙂

 

 

Thanks & Regards,
Mohamed Arshad K
0 Likes

Hans_Dwe
Enthusiast
Enthusiast

@Mohamed_Arshad i am sorry i am not that deep into this before, this is what i meant, what should i do as next ? 

Hans_Dwe_0-1718970796687.png

 

0 Likes

Mohamed_Arshad
Advisor
Advisor

@Hans_Dwe  Check the Below snippet

 

ExternalDefinitionCreationOptions creationOpt = new ExternalDefinitionCreationOptions(definition.Name, definition.GetDataType());
Thanks & Regards,
Mohamed Arshad K
0 Likes

Mohamed_Arshad
Advisor
Advisor

Hi @Hans_Dwe 

 

    I think you're using higher version of Revit so I have updated the code from 2021 to 2024, Kindly refer to the below code for Revit version 2024. Not too many changes only a few changes are there (Enum to Classes).

 

Updated Code:

 

using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Xml.Linq;

namespace TransferProjectParameter
{
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    public class Class1 : IExternalCommand
    {
        private string logFilePath = @"C:\log.txt";

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Document sourceDoc = uiapp.ActiveUIDocument.Document;

            // Collect all project parameters from the source document
            BindingMap sourceBindingMap = sourceDoc.ParameterBindings;
            DefinitionBindingMapIterator iter = sourceBindingMap.ForwardIterator();
            iter.Reset();

            List<Definition> projectParameters = new List<Definition>();

            while (iter.MoveNext())
            {
                Definition def = iter.Key;
                projectParameters.Add(def);
            }

            if (projectParameters.Count == 0)
            {
                TaskDialog.Show("Error", "No project parameters found in the source document.");
                return Result.Failed;
            }

            Document targetDoc = null;
            foreach (Document doc in uiapp.Application.Documents)
            {
                if (!doc.Equals(sourceDoc))
                {
                    targetDoc = doc;
                    break;
                }
            }

            if (targetDoc == null)
            {
                TaskDialog.Show("Transfer Project Parameters", "No target document found.");
                return Result.Failed;
            }



            #region Convert Internal Definition to External Defintion

            string originalSharedParameterFile = uiapp.Application.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";
            using (File.Create(tempFile)) { }
            uiapp.Application.SharedParametersFilename = tempFile;

            Dictionary<ExternalDefinition, Definition> extDef = new Dictionary<ExternalDefinition, Definition>();

            foreach (Definition definition in projectParameters)
            {
                ExternalDefinitionCreationOptions creationOpt = new ExternalDefinitionCreationOptions(definition.Name, definition.GetDataType());
                ExternalDefinition def = uiapp.Application.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions.Create(creationOpt) as ExternalDefinition;
                extDef.Add(def, definition);
            }

            uiapp.Application.SharedParametersFilename = originalSharedParameterFile;

            File.Delete(tempFile);

            #endregion

            // Add project parameters to the target document
            using (Transaction trans = new Transaction(targetDoc, "Copy Project Parameters"))
            {
                trans.Start();

                foreach (KeyValuePair<ExternalDefinition, Definition> def in extDef)
                {
                    Binding binding = sourceBindingMap.get_Item(def.Value);

                    if (binding != null)
                    {
                        // Get the parameter group
                        ForgeTypeId paramGroup = (def.Key)?.GetGroupTypeId() ?? new ForgeTypeId(string.Empty);

                        // Add the definition with the same binding to the target document
                        targetDoc.ParameterBindings.Insert(def.Key, binding, paramGroup);
                    }
                }

                trans.Commit();
            }

            List<string> projectParameterNames = projectParameters.Select(p => p.Name).ToList();
            LogProjectParameters(projectParameterNames);
            TaskDialog.Show("Transfer Project Parameters", $"{projectParameters.Count} project parameters transferred successfully.");

            return Result.Succeeded;
        }

        private void LogProjectParameters(List<string> parameterNames)
        {
            using (StreamWriter sw = new StreamWriter(logFilePath, true))
            {
                foreach (var name in parameterNames)
                {
                    sw.WriteLine(name);
                }

            }
        }
    }
}

 

Hope this will Helps 🙂

Thanks & Regards,
Mohamed Arshad K
0 Likes

Hans_Dwe
Enthusiast
Enthusiast

@Mohamed_Arshad Yes you are right its 2024 version but unfortunately, i faced another error , i will look for it 

Hans_Dwe_0-1718972759641.png

 

0 Likes

Mohamed_Arshad
Advisor
Advisor
Accepted solution

HI @Hans_Dwe 

 

  Sorry I made a small mistake in my Code, I'm trying to create the same group repeatedly so the error comes. Kindly check the below updated code.

 

Updated Code:

 

using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Linq;
using System.Dynamic;

namespace TransferProjectParameter
{
    [Transaction(TransactionMode.Manual)]
    [Regeneration(RegenerationOption.Manual)]
    public class Class1 : IExternalCommand
    {
        private string logFilePath = @"C:\log.txt";

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            Document sourceDoc = uiapp.ActiveUIDocument.Document;

            // Collect all project parameters from the source document
            BindingMap sourceBindingMap = sourceDoc.ParameterBindings;
            DefinitionBindingMapIterator iter = sourceBindingMap.ForwardIterator();
            iter.Reset();

            List<Definition> projectParameters = new List<Definition>();

            while (iter.MoveNext())
            {
                Definition def = iter.Key;
                projectParameters.Add(def);
            }

            if (projectParameters.Count == 0)
            {
                TaskDialog.Show("Error", "No project parameters found in the source document.");
                return Result.Failed;
            }

            Document targetDoc = null;
            foreach (Document doc in uiapp.Application.Documents)
            {
                if (!doc.Equals(sourceDoc))
                {
                    targetDoc = doc;
                    break;
                }
            }

            if (targetDoc == null)
            {
                TaskDialog.Show("Transfer Project Parameters", "No target document found.");
                return Result.Failed;
            }



            #region Convert Internal Definition to External Defintion

            string originalSharedParameterFile = uiapp.Application.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";
            using (File.Create(tempFile)) { }
            uiapp.Application.SharedParametersFilename = tempFile;

            Dictionary<ExternalDefinition, Definition> extDef = new Dictionary<ExternalDefinition, Definition>();

            DefinitionFile definitionFile = uiapp.Application.OpenSharedParameterFile();
            DefinitionGroup definitionGroup = definitionFile.Groups.Create($"TemporaryDefintionGroup"); ;

            for (int i = 0; i < projectParameters.Count; i++)
            {
                ExternalDefinitionCreationOptions creationOpt = new ExternalDefinitionCreationOptions(projectParameters[i].Name,
                    projectParameters[i].GetDataType());

                ///Create New Group for Identity Parameter Names
                if (definitionGroup.Definitions != null && definitionGroup.Definitions.Select(x => x.Name).Contains(projectParameters[i].Name))
                {
                    DefinitionGroup temp = definitionFile.Groups.Create($"TemporaryDefintionGroup {i}");
                    extDef.Add(temp.Definitions.Create(creationOpt) as ExternalDefinition, projectParameters[i]);
                }
                else
                {
                    extDef.Add(definitionGroup.Definitions.Create(creationOpt) as ExternalDefinition, projectParameters[i]);
                }
            }

            uiapp.Application.SharedParametersFilename = originalSharedParameterFile;

            File.Delete(tempFile);

            #endregion

            // Add project parameters to the target document
            using (Transaction trans = new Transaction(targetDoc, "Copy Project Parameters"))
            {
                trans.Start();

                foreach (KeyValuePair<ExternalDefinition, Definition> def in extDef)
                {
                    Binding binding = sourceBindingMap.get_Item(def.Value);

                    if (binding != null)
                    {
                        // Get the parameter group
                        ForgeTypeId paramGroup = (def.Value)?.GetGroupTypeId() ?? new ForgeTypeId(string.Empty);

                        // Add the definition with the same binding to the target document
                        targetDoc.ParameterBindings.Insert(def.Key, binding, paramGroup);
                    }
                }

                trans.Commit();
            }

            List<string> projectParameterNames = projectParameters.Select(p => p.Name).ToList();
            LogProjectParameters(projectParameterNames);
            TaskDialog.Show("Transfer Project Parameters", $"{projectParameters.Count} project parameters transferred successfully.");

            return Result.Succeeded;
        }

        private void LogProjectParameters(List<string> parameterNames)
        {
            using (StreamWriter sw = new StreamWriter(logFilePath, true))
            {
                foreach (var name in parameterNames)
                {
                    sw.WriteLine(name);
                }

            }
        }

    }
}

 

 

Hope now it will work without error 🙂

 

Thanks & Regards,
Mohamed Arshad K

Hans_Dwe
Enthusiast
Enthusiast

@Mohamed_Arshad perfect it worked like a charm. appreciate it 🙂