using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.ADF.CATIDs; namespace GPCalculateArea
{ public class CalculateAreaFunction : IGPFunction2
{
private string m_ToolName = "CalculateArea"; //Function Name
//Local members private string m_metadatafile = "CalculateArea_area.xml";
private IArray m_Parameters; // Array of Parameters
private IGPUtilities m_GPUtilities; // GPUtilities object public CalculateAreaFunction()
{
m_GPUtilities = new GPUtilitiesClass();
} #region IGPFunction Members // Set the name of the function tool.
// This name appears when executing the tool at the command line or in scripting.
// This name should be unique to each toolbox and must not contain spaces.
public string Name
{
get { return m_ToolName; }
} // Set the function tool Display Name as seen in ArcToolbox.
public string DisplayName
{
get { return "Calculate Area"; }
} // This is the location where the parameters to the Function Tool are defined.
// This property returns an IArray of parameter objects (IGPParameter).
// These objects define the characteristics of the input and output parameters.
public IArray ParameterInfo
{
get
{
//Array to the hold the parameters
IArray parameters = new ArrayClass(); //Input DataType is GPFeatureLayerType
IGPParameterEdit3 inputParameter = new GPParameterClass();
inputParameter.DataType = new GPFeatureLayerTypeClass(); // Default Value object is GPFeatureLayer
inputParameter.Value = new GPFeatureLayerClass(); // Set Input Parameter properties
inputParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputParameter.DisplayName = "Input Features";
inputParameter.Name = "input_features";
inputParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
parameters.Add(inputParameter); // Area field parameter
inputParameter = new GPParameterClass();
inputParameter.DataType = new GPStringTypeClass(); // Value object is GPString
IGPString gpStringValue = new GPStringClass();
gpStringValue.Value = "Area";
inputParameter.Value = (IGPValue)gpStringValue; // Set field name parameter properties
inputParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
inputParameter.DisplayName = "Area Field Name";
inputParameter.Name = "field_name";
inputParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
parameters.Add(inputParameter); // Output parameter (Derived) and data type is DEFeatureClass
IGPParameterEdit3 outputParameter = new GPParameterClass();
outputParameter.DataType = new GPFeatureLayerTypeClass(); // Value object is DEFeatureClass
outputParameter.Value = new DEFeatureClassClass(); // Set output parameter properties
outputParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
outputParameter.DisplayName = "Output FeatureClass";
outputParameter.Name = "out_featureclass";
outputParameter.ParameterType = esriGPParameterType.esriGPParameterTypeDerived; // Create a new schema object - schema means the structure or design of the feature class (field information, geometry information, extent)
IGPFeatureSchema outputSchema = new GPFeatureSchemaClass();
IGPSchema schema = (IGPSchema)outputSchema; // Clone the schema from the dependency.
//This means update the output with the same schema as the input feature class (the dependency).
schema.CloneDependency = true; // Set the schema on the output because this tool will add an additional field.
outputParameter.Schema = outputSchema as IGPSchema;
outputParameter.AddDependency("input_features");
parameters.Add(outputParameter); return parameters;
}
} // Validate:
// - Validate is an IGPFunction method, and we need to implement it in case there
// is legacy code that queries for the IGPFunction interface instead of the IGPFunction2
// interface.
// - This Validate code is boilerplate - copy and insert into any IGPFunction2 code..
// - This is the calling sequence that the gp framework now uses when it QI's for IGPFunction2..
public IGPMessages Validate(IArray paramvalues, bool updateValues, IGPEnvironmentManager envMgr)
{
if (m_Parameters == null)
m_Parameters = ParameterInfo; // Call UpdateParameters().
// Only Call if updatevalues is true.
if (updateValues == true)
{
UpdateParameters(paramvalues, envMgr);
} // Call InternalValidate (Basic Validation). Are all the required parameters supplied?
// Are the Values to the parameters the correct data type?
IGPMessages validateMsgs = m_GPUtilities.InternalValidate(m_Parameters, paramvalues, updateValues, true, envMgr); // Call UpdateMessages();
UpdateMessages(paramvalues, envMgr, validateMsgs); // Return the messages
return validateMsgs;
} // This method will update the output parameter value with the additional area field.
public void UpdateParameters(IArray paramvalues, IGPEnvironmentManager pEnvMgr)
{
m_Parameters = paramvalues; // Retrieve the input parameter value
IGPValue parameterValue = m_GPUtilities.UnpackGPValue(m_Parameters.get_Element()); // Get the derived output feature class schema and empty the additional fields. This will ensure you don't get duplicate entries.
IGPParameter3 derivedFeatures = (IGPParameter3)paramvalues.get_Element();
IGPFeatureSchema schema = (IGPFeatureSchema)derivedFeatures.Schema;
schema.AdditionalFields = null; // If we have an input value, create a new field based on the field name the user entered.
if (parameterValue.IsEmpty() == false)
{
IGPParameter3 fieldNameParameter = (IGPParameter3)paramvalues.get_Element();
string fieldName = fieldNameParameter.Value.GetAsText(); // Check if the user's input field already exists
IField areaField = m_GPUtilities.FindField(parameterValue, fieldName);
if (areaField == null)
{
IFieldsEdit fieldsEdit = new FieldsClass();
IFieldEdit fieldEdit = new FieldClass();
fieldEdit.Name_2 = fieldName;
fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
fieldsEdit.AddField(fieldEdit); // Add an additional field for the area values to the derived output.
IFields fields = fieldsEdit as IFields;
schema.AdditionalFields = fields;
} }
} // Called after returning from the update parameters routine.
// You can examine the messages created from internal validation and change them if desired.
public void UpdateMessages(IArray paramvalues, IGPEnvironmentManager pEnvMgr, IGPMessages Messages)
{
// Check for error messages
IGPMessage msg = (IGPMessage)Messages;
if (msg.IsError())
return; // Get the first Input Parameter
IGPParameter parameter = (IGPParameter)paramvalues.get_Element(); // UnPackGPValue. This ensures you get the value either form the dataelement or GpVariable (ModelBuilder)
IGPValue parameterValue = m_GPUtilities.UnpackGPValue(parameter); // Open the Input Dataset - Use DecodeFeatureLayer as the input might be a layer file or a feature layer from ArcMap.
IFeatureClass inputFeatureClass;
IQueryFilter qf;
m_GPUtilities.DecodeFeatureLayer(parameterValue, out inputFeatureClass, out qf); IGPParameter3 fieldParameter = (IGPParameter3)paramvalues.get_Element();
string fieldName = fieldParameter.Value.GetAsText(); // Check if the field already exists and provide a warning.
int indexA = inputFeatureClass.FindField(fieldName);
if (indexA > )
{
Messages.ReplaceWarning(, "Field already exists. It will be overwritten.");
} return;
} // Execute: Execute the function given the array of the parameters
public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message)
{ // Get the first Input Parameter
IGPParameter parameter = (IGPParameter)paramvalues.get_Element(); // UnPackGPValue. This ensures you get the value either form the dataelement or GpVariable (ModelBuilder)
IGPValue parameterValue = m_GPUtilities.UnpackGPValue(parameter); // Open Input Dataset
IFeatureClass inputFeatureClass;
IQueryFilter qf;
m_GPUtilities.DecodeFeatureLayer(parameterValue, out inputFeatureClass, out qf); if (inputFeatureClass == null)
{
message.AddError(, "Could not open input dataset.");
return;
} // Add the field if it does not exist.
int indexA; parameter = (IGPParameter)paramvalues.get_Element();
string field = parameter.Value.GetAsText(); indexA = inputFeatureClass.FindField(field);
if (indexA < )
{
IFieldEdit fieldEdit = new FieldClass();
fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
fieldEdit.Name_2 = field;
inputFeatureClass.AddField(fieldEdit);
} int featcount = inputFeatureClass.FeatureCount(null); //Set the properties of the Step Progressor
IStepProgressor pStepPro = (IStepProgressor)trackcancel;
pStepPro.MinRange = ;
pStepPro.MaxRange = featcount;
pStepPro.StepValue = ();
pStepPro.Message = "Calculating Area";
pStepPro.Position = ;
pStepPro.Show(); // Create an Update Cursor
indexA = inputFeatureClass.FindField(field);
IFeatureCursor updateCursor = inputFeatureClass.Update(qf, false);
IFeature updateFeature = updateCursor.NextFeature();
IGeometry geometry;
IArea area;
double dArea; while (updateFeature != null)
{
geometry = updateFeature.Shape;
area = (IArea)geometry;
dArea = area.Area;
updateFeature.set_Value(indexA, dArea);
updateCursor.UpdateFeature(updateFeature);
updateFeature.Store();
updateFeature = updateCursor.NextFeature();
pStepPro.Step();
} pStepPro.Hide(); // Release the update cursor to remove the lock on the input data.
System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor);
} // This is the function name object for the Geoprocessing Function Tool.
// This name object is created and returned by the Function Factory.
// The Function Factory must first be created before implementing this property.
public IName FullName
{
get
{
// Add CalculateArea.FullName getter implementation
IGPFunctionFactory functionFactory = new CalculateAreaFunctionFactory();
return (IName)functionFactory.GetFunctionName(m_ToolName);
}
} // This is used to set a custom renderer for the output of the Function Tool.
public object GetRenderer(IGPParameter pParam)
{
return null;
} // This is the unique context identifier in a [MAP] file (.h).
// ESRI Knowledge Base article #27680 provides more information about creating a [MAP] file.
public int HelpContext
{
get { return ; }
} // This is the path to a .chm file which is used to describe and explain the function and its operation.
public string HelpFile
{
get { return ""; }
} // This is used to return whether the function tool is licensed to execute.
public bool IsLicensed()
{
IAoInitialize aoi = new AoInitializeClass();
ILicenseInformation licInfo = (ILicenseInformation)aoi; string licName = licInfo.GetLicenseProductName(aoi.InitializedProduct()); if (licName == "ArcInfo")
{
return true;
}
else
return false;
} // This is the name of the (.xml) file containing the default metadata for this function tool.
// The metadata file is used to supply the parameter descriptions in the help panel in the dialog.
// If no (.chm) file is provided, the help is based on the metadata file.
// ESRI Knowledge Base article #27000 provides more information about creating a metadata file.
public string MetadataFile
{
get { return m_metadatafile; }
} // By default, the Toolbox will create a dialog based upon the parameters returned
// by the ParameterInfo property.
public UID DialogCLSID
{
// DO NOT USE. INTERNAL USE ONLY.
get { return null; }
} #endregion
} //////////////////////////////
// Function Factory Class
////////////////////////////
[
Guid("2554BFC7-94F9-4d28-B3FE-14D17599B35A"),
ComVisible(true)
]
public class CalculateAreaFunctionFactory : IGPFunctionFactory
{
private const string m_ToolName = "ylArea"; //Function Name
// Register the Function Factory with the ESRI Geoprocessor Function Factory Component Category.
#region "Component Category Registration"
[ComRegisterFunction()]
static void Reg(string regKey)
{ GPFunctionFactories.Register(regKey);
} [ComUnregisterFunction()]
static void Unreg(string regKey)
{
GPFunctionFactories.Unregister(regKey);
}
#endregion // Utility Function added to create the function names.
private IGPFunctionName CreateGPFunctionNames(long index)
{
IGPFunctionName functionName = new GPFunctionNameClass();
functionName.MinimumProduct = esriProductCode.esriProductCodeProfessional;
IGPName name; switch (index)
{
case ():
name = (IGPName)functionName;
name.Category = "AreaCalculation";
name.Description = "Calculate Area for FeatureClass";
name.DisplayName = "Calculate Area";
name.Name = m_ToolName;
name.Factory = (IGPFunctionFactory)this;
break;
} return functionName;
} // Implementation of the Function Factory
#region IGPFunctionFactory Members // This is the name of the function factory.
// This is used when generating the Toolbox containing the function tools of the factory.
public string Name
{
get { return m_ToolName; }
} // This is the alias name of the factory.
public string Alias
{
get { return "area"; }
} // This is the class id of the factory.
public UID CLSID
{
get
{
UID id = new UIDClass();
id.Value = this.GetType().GUID.ToString("B");
return id;
}
} // This method will create and return a function object based upon the input name.
public IGPFunction GetFunction(string Name)
{
switch (Name)
{
case (m_ToolName):
IGPFunction gpFunction = new CalculateAreaFunction();
return gpFunction;
} return null;
} // This method will create and return a function name object based upon the input name.
public IGPName GetFunctionName(string Name)
{
IGPName gpName = new GPFunctionNameClass(); switch (Name)
{
case (m_ToolName):
return (IGPName)CreateGPFunctionNames(); }
return null;
} // This method will create and return an enumeration of function names that the factory supports.
public IEnumGPName GetFunctionNames()
{
IArray nameArray = new EnumGPNameClass();
nameArray.Add(CreateGPFunctionNames());
return (IEnumGPName)nameArray;
} // This method will create and return an enumeration of GPEnvironment objects.
// If tools published by this function factory required new environment settings,
//then you would define the additional environment settings here.
// This would be similar to how parameters are defined.
public IEnumGPEnvironment GetFunctionEnvironments()
{
return null;
} #endregion
} }

AE(ArcEngine)定制工具Tool工具箱的更多相关文章

  1. 利用C#与AE调用GP工具

    转自原文 利用C#与AE调用GP工具 第一,首先要明确自己需要调用arctoolbox里面的什么工具,实现什么样的功能. 第三,编写command或tool工具,编写自己要的功能工具. 1)首先创建一 ...

  2. arcengine自己做一个工具Tool放到工具箱中

    // Copyright 2010 ESRI // // All rights reserved under the copyright laws of the United States // an ...

  3. 一款批量修改AE模板的工具

    一.需求分析 对于视频后期剪辑及相关从业人员来说,AE(After Effects)模板效果是一个不错的开始点.在模板效果的基础上,可以很快的做出各种炫酷的后期效果.但是在网上下载的模板工程中,往往包 ...

  4. AE调用GP工具的方法(转)

    第一,首先要明确自己需要调用arctoolbox里面的什么工具,实现什么样的功能. 第二,按照需求看看在arctoolbox工具中是怎么实现功能的,然后确定需要的数据源. 第三,编写command或t ...

  5. 基于Alpine镜像定制自己的工具箱

    Alpine介绍 Alpine 操作系统是一个面向安全的轻型 Linux 发行版.目前 Docker 官方已开始推荐使用 Alpine 替代之前的 Ubuntu 做为基础镜像环境.这样会带来多个好处. ...

  6. 【199】ArcGIS 添加自定义工具到工具箱

    点击工具栏最右边的三角块,弹出菜单,点击“Customize”. 切换到“Command”,在搜索框中输入“idw”查找相应工具,然后将工具通过鼠标左键拖拽到工具栏中. 在工具上右键修改工具的显示图片 ...

  7. Java 定制工具库 —— Print(import static)

    创建自己的工具库以减少或消除重复的程序代码.例如,我们在Print类中,对常常用到的System.out.println()封装调用以减少输入负担.这样,我们在使用该类时,可以用一个更具可读性的 im ...

  8. AE调用GP工具(创建缓冲区和相交为例)

    引用 Geoprocessing是ArcGIS提供的一个非常实用的工具,借由Geoprocessing工具可以方便的调用ArcToolBox中提供的各类工具,本文在ArcEngine9.2平台环境下总 ...

  9. 从工具、工具箱到数字化软件工厂——DevOps 设计理念与工程实践专场 | CIF 精彩看点

    西方经典管理理论认为,组织效率可以归为劳动效率.组织效率和人的效率.美国管理学家泰勒所著的<科学管理原理>被德鲁克誉为"20 世纪最伟大的发明",劳动效率说认为分工提升 ...

随机推荐

  1. vim-git for window 默认编辑器

    vim其实是linux的一个文本编辑器,所以 vi+文件名 后,其实是进入vi程序了.vi有两种模式,编辑模式和命令模式 在命令模式下,我们可以直接按 i ,此时就会切换到编辑模式,如上图,下方有个i ...

  2. Optimizing graphics performance

    看U3D文档,心得:对于3D场景,使用分层次的距离裁剪,小物件分到一个层,稍远时就被裁掉,大物体分到一个层,距离很远时才裁掉,甚至不载.中物体介于二者之间. 文档如下: Good performanc ...

  3. mysql启动报错 The server quit without updating PID file

    [root@uz6542 data]# /etc/init.d/mysqld startStarting MySQL... ERROR! The server quit without updatin ...

  4. SQL语言类别

    SQL语言主要分为四大类:数据查询语言DQL,数据操纵语言DML, 数据定义语言DDL,数据控制语言DCL. DQL (data query language) DML(data manipulati ...

  5. Oracle免客户端InstantClient安装使用

    正常情况下,用PL/SQL等软件连接Oracle,需要安装Oracle客户端软件,一般安装oracle客户端差不多需要2G左右的硬盘空间,但如果我们仅仅是连接数据库进行查询和执行一些相应的语句而不进行 ...

  6. Spoon新建repository的时候

    Spoon新建repository的时候,下面选项选择‘否’,不要选择‘是’,不然可能会出错.

  7. sql server 2000能否得到一个表的最后更新日期?

    如果是SQL 2005 或 2008.运行下面的代码.就可以看到从上次启动SQL 服务以来,某个表的使用情况,包括select/update/delete/insert. SELECT * FROM ...

  8. 英语广播原声听力100篇MP3及听力原文

    =============7.6================ Passage 031- 人工智能对人类的利与弊From a personal assistant, to doing searche ...

  9. testlink问题--linux环境下

    搭建testlink 时出现问题,相关解决办法: 1.Maximum Session Idle Time before Timeout 修改php.ini文件,修改成session.gc_maxlif ...

  10. Oracle to_date()函数的用法《转载》

    to_date()是Oracle数据库函数的代表函数之一,下文对Oracle to_date()函数的几种用法作了详细的介绍说明, 原文地址:http://database.51cto.com/art ...