应用程序:ValidateParameters

Revit平台:所有

Revit版本:2011.0

首次发布于:2010.0

编程语言:C#

技能水平:初学者

类别:

类型:ExternalCommandExternalApplication

主题:验证参数

摘要:此示例将演示每个类型是否具有某些参数的有效值。

相关类:

Autodesk.Revit.UI.IExternalCommand

Autodesk.Revit.UI.IExternalApplication

Autodesk.Revit.UI.UIDocument

Autodesk.Revit.DB.Element

Autodesk.Revit.DB.FamilyManager

Autodesk.Revit.DB.ParameterSet

项目文件:

Command.cs

该文件包含实现IExternalCommand界面的类Command。该类的函数是调用API FamilyType.HasValueFamilyType.AsDouble(Parameter)AsElementId(Parameter)方法来验证参数。

Application.cs

该文件包含实现IExternalApplication界面的类Application。在启动Revit时,OnStartUp方法将注册DocumentSavingDocumentSavingAs事件。预事件处理程序将在文档保存时验证参数;后事件处理程序将在将文档保存为另一个文件时验证参数。OnShutdown方法将删除两个事件当Revit关闭时。

MessageForm.cs

该文件包含一个Windows窗体,将参数验证结果显示给用户。

描述:

此示例只能用于族。示例实现了IExternalApplication界面并在OnStartUp方法中订阅了DocumentSavingDocumentSavingAs事件;注册的事件处理程序将在事件被触发时验证参数。也可以通过外部命令启动。如果有任何无法通过验证的参数,将显示一条警告消息并列出无效的类型和参数。有一个日志文件,存储在表格中显示的所有信息。

--要将事件注册到应用程序中,请使用受控应用程序的事件处理程序DocumentSavingDocumentSavingAs

--要获取族类型,请使用属性FamilyManager.Types

--要获取族参数,请使用属性FamilyManager.Parameters

--要检查某个参数是否具有某个参数值,请使用方法FamilyType.HasValue(FamilyParameter)

--要检查参数的存储类型,请使用属性Parameter.StorageType

--要检索参数值,请使用方法FamilyType.AsDouble(Parameter)AsElementId(Parameter)等。

说明:

1.按照以下行更新Revit.ini

[ExternalApplications]

EACount      = 1

EAClassName1=Revit.SDK.Samples.ValidateParameters.CS.Application

EAAssembly1  = <your path>\ValidateParameters.dll

[ExternalCommands]

ECCount        = 1

ECName1= Validate Parameters

ECClassName1   = Revit.SDK.Samples.ValidateParameters.CS.Command

ECAssembly1    = <your path>\ValidateParameters.dll

ECDescription1   = Validate every type has valid values for certain parameters.

2.启动RevitDocumentSavingDocumentSavingAs事件将自动注册。

3.为了使用家族,用户应手动打开一个家族文档。

4.运行External Command ValidateParameters

5.通过用户界面菜单文件\保存触发保存事件。

6.通过用户界面菜单文件\另存为触发SaveAs事件。

源代码:
完整的源代码请加入QQ群649037449,在群文件中下载RevitSDK.exe,解压后在文件夹中搜索本文中应用程序名称即可获得完整源码

Application.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.ApplicationServices;
namespace Revit.SDK.Samples.ValidateParameters.CS
{
    /// <summary>
    /// A class inherits IExternalApplication interface to add an event to the document saving,
    /// which will be called when the document is being saved.
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
    class Application: IExternalApplication
    {
        #region IExternalApplication Members    
        /// <summary>
        /// Implement this method to implement the external application which should be called when 
        /// Revit starts before a file or default template is actually loaded.
        /// </summary>
        /// <param name="application">An object that is passed to the external application 
        /// which contains the controlled application.</param>
        /// <returns>Return the status of the external application. 
        /// A result of Succeeded means that the external application successfully started. 
        /// Cancelled can be used to signify that the user cancelled the external operation at 
        /// some point.
        /// If false is returned then Revit should inform the user that the external application 
        /// failed to load and the release the internal reference.</returns>
        public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application)
        {
            try
            {               
                application.ControlledApplication.DocumentSaving += new EventHandler<Autodesk.Revit.DB.Events.DocumentSavingEventArgs>(application_DocumentSaving);
                application.ControlledApplication.DocumentSavingAs += new EventHandler<Autodesk.Revit.DB.Events.DocumentSavingAsEventArgs>(application_DocumentSavingAs);
            }
            catch (Exception)
            {
                return Autodesk.Revit.UI.Result.Failed;
            }
            return Autodesk.Revit.UI.Result.Succeeded;
        }
        /// <summary>
        /// Implement this method to implement the external application which should be called when 
        /// Revit is about to exit,Any documents must have been closed before this method is called.
        /// </summary>
        /// <param name="application">An object that is passed to the external application 
        /// which contains the controlled application.</param>
        /// <returns>Return the status of the external application. 
        /// A result of Succeeded means that the external application successfully shutdown. 
        /// Cancelled can be used to signify that the user cancelled the external operation at 
        /// some point.
        /// If false is returned then the Revit user should be warned of the failure of the external 
        /// application to shut down correctly.</returns>
        public Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application)
        {
            try
            {
                application.ControlledApplication.DocumentSaving -= new EventHandler<Autodesk.Revit.DB.Events.DocumentSavingEventArgs>(application_DocumentSaving);
                application.ControlledApplication.DocumentSavingAs -= new EventHandler<Autodesk.Revit.DB.Events.DocumentSavingAsEventArgs>(application_DocumentSavingAs);
            }
            catch (Exception)
            {
                return Autodesk.Revit.UI.Result.Failed;
            }
            return Autodesk.Revit.UI.Result.Succeeded;
        }
        /// <summary>
        /// Subscribe to the DocumentSaving event to be notified when Revit is just about to save the document. 
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">The event argument used by DocumentSaving event. </param>
        private void application_DocumentSaving(Object sender, Autodesk.Revit.DB.Events.DocumentSavingEventArgs e)
        {
            validateParameters(e.Document);
        }
        /// <summary>
        /// Subscribe to the DocumentSavingAs event to be notified when Revit is just about to save the document with a new file name. 
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">The event argument used by DocumentSavingAs event.</param>
        private void application_DocumentSavingAs(Object sender, Autodesk.Revit.DB.Events.DocumentSavingAsEventArgs e)
        {   
            validateParameters(e.Document);
        }
        /// <summary>
        /// The method is to validate parameters via FamilyParameter and FamilyType
        /// </summary>
        /// <param name="doc">the document which need to validate parameters</param>
        private void validateParameters(Document doc)
        {
            List<string> errorInfo = new List<string>();
            FamilyManager familyManager;
            if (doc.IsFamilyDocument)
            {
                familyManager = doc.FamilyManager;
                errorInfo = Command.ValidateParameters(familyManager);
            }
            else
            {
                errorInfo.Add("The current document isn't a family document, so the validation doesn't work correctly!");
            }
            using (MessageForm msgForm = new MessageForm(errorInfo.ToArray()))
            {
                msgForm.StartPosition = FormStartPosition.CenterParent;
                msgForm.ShowDialog();
            }
        }
        #endregion
    }
}

Command.cs

//
// (C) Copyright 2003-2019 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
namespace Revit.SDK.Samples.ValidateParameters.CS
{  
    /// <summary>
    /// A class inherits IExternalCommand interface.
    /// this class controls the class which subscribes handle events and the events' information UI.
    /// like a bridge between them.
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
    [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
    public class Command:IExternalCommand
    {
        #region Class Memeber Variables
        /// <summary>
        /// store the family manager
        /// </summary>
        FamilyManager m_familyManager;         
        #endregion
        
        #region Class Interface Implementation
        /// <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)
        {
            Document document;            
            document = commandData.Application.ActiveUIDocument.Document;           
            // only a family document can retrieve family manager
            if (document.IsFamilyDocument)
            {                
                m_familyManager = document.FamilyManager;
                List<string> errorMessages = ValidateParameters(m_familyManager);
                using(MessageForm msgForm = new MessageForm(errorMessages.ToArray()))
                {
                    msgForm.StartPosition = FormStartPosition.CenterParent;
                    msgForm.ShowDialog();                    
                    return Autodesk.Revit.UI.Result.Succeeded;
                }
            }
            else
            {
                message = "please make sure you have opened a family document!";
                return Autodesk.Revit.UI.Result.Failed;
            }
        }
        #endregion
        #region Class Implementation
        /// <summary>
        /// implementation of validate parameters, get all family types and parameters, 
        /// use the function FamilyType.HasValue() to make sure if the parameter needs to
        /// validate. Then along to the storage type to validate the parameters.
        /// </summary>
        /// <returns>error information list</returns>
        public static List<string> ValidateParameters(FamilyManager familyManager)
        {
            List<string> errorInfo = new List<string>();
            // go though all parameters
            foreach (FamilyType type in familyManager.Types)
            {
                bool right = true;
                foreach (FamilyParameter para in familyManager.Parameters)
                {
                    try
                    { 
                        if (type.HasValue(para))
                        {
                            switch (para.StorageType)
                            {
                                case StorageType.Double:
                                    if (!(type.AsDouble(para) is double))
                                        right = false;
                                    break;
                                case StorageType.ElementId:
                                    try
                                    {
                                        Autodesk.Revit.DB.ElementId elemId=type.AsElementId(para);
                                    }
                                    catch
                                    {
                                        right = false;
                                    }                                    
                                    break;
                                case StorageType.Integer:
                                    if (!(type.AsInteger(para) is int))
                                        right = false;
                                    break;
                                case StorageType.String:
                                    if (!(type.AsString(para) is string))
                                        right = false;
                                    break;
                                default:
                                    break;
                            }
                        }
                    } 
                    // output the parameters which failed during validating.
                    catch
                    {
                        errorInfo.Add("Family Type:" + type.Name + "   Family Parameter:" 
                            + para.Definition.Name + "   validating failed!");                       
                    }
                    if (!right)
                    {
                        errorInfo.Add("Family Type:" + type.Name + "   Family Parameter:"
                            + para.Definition.Name + "   validating failed!");                       
                    }                  
                } 
            }           
            return errorInfo;
        }       
        #endregion   
    }   
}