[Transaction(TransactionMode.Manual)]
public class AddFamilyParameterCommand : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
var uiapp = commandData.Application;
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
var family = FindFamily(doc);
if (family == null)
{
message = "Семейство не найдено";
return Result.Failed;
}
var parameterDefinition = FindParameterDefinition(doc.Application);
if (parameterDefinition == null)
{
message = "В файле общих параметров отсутствует параметр";
return Result.Failed;
}
var familyDocument = doc.EditFamily(family);
if (AddParameter(familyDocument, parameterDefinition))
familyDocument.LoadFamily(doc, new FamilyLoadOptions());
familyDocument.Close(false);
return Result.Succeeded;
}
private static Family FindFamily(Document document)
{
var collector = new FilteredElementCollector(document);
return collector
.OfClass(typeof (Family))
.OfType<Family>()
.FirstOrDefault(x => x.Name == "M_Fixed");
}
private static ExternalDefinition FindParameterDefinition(Application application)
{
if (string.IsNullOrEmpty(application.SharedParametersFilename) || !File.Exists(application.SharedParametersFilename))
return null;
var definitionFile = application.OpenSharedParameterFile();
return definitionFile
.Groups
.FirstOrDefault()
?.Definitions
.Cast<ExternalDefinition>()
.FirstOrDefault();
}
private static bool AddParameter(Document familyDocument, ExternalDefinition parameterDefinition)
{
var familyManager = familyDocument.FamilyManager;
if (HasParameter(familyManager, parameterDefinition.GUID))
return false;
using (var transaction = new Transaction(familyDocument, "add parameter"))
{
transaction.Start();
familyManager.AddParameter(parameterDefinition, BuiltInParameterGroup.PG_IDENTITY_DATA, true);
transaction.Commit();
}
return true;
}
private static bool HasParameter(FamilyManager familyManager, Guid parameterId)
{
return familyManager
.Parameters
.Cast<FamilyParameter>()
.Where(x => x.IsShared)
.Any(x => x.GUID == parameterId);
}
class FamilyLoadOptions : IFamilyLoadOptions
{
public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues)
{
overwriteParameterValues = true;
return true;
}
public bool OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues)
{
source = FamilySource.Family;
overwriteParameterValues = true;
return true;
}
}
}