C# + ArcEngine 常用方法(不定时更新)
1、Arcengine调用GP服务,抛出异常方法
object sev = null; try { Application.DoEvents(); gp.Execute(gpBuildPyramidsandStatistics, null); Application.DoEvents(); Console.WriteLine(gp.GetMessages(ref sev)); } catch (Exception ex) { // Print geoprocessing execution error messages. MessageBox.Show(gp.GetMessages(ref sev)); } //ps:调用GP服务处理数据库中的数据,必须添加gp的环境变量workspace.http://www.ithao123.cn/content-7464230.html //Geoprocessor GP = new Geoprocessor(); //string sWorkPath; //IWorkspace pWork; //if(pWork.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) //{ //sWorkPath = System.IO.Path.Combine(Application.StartupPath,"gpenvwk.sde"); //pWork.WorkspaceFactory.Create(Application.StartupPath,"gpenvwk.sde",pWork.ConnectionProperties,0); //} //else //{ //sWorkPath = pWork.PathName; //} //GP.SetEnvironmentValue("workspace",sWorkPath); //GP.OverwriteOutput = true;
2、日志生成类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; namespace Geoway.IDB.FileCheck.Utility { ///<summary> ///目的:日志操作类 ///创建人:jwh ///创建日期:2016/7/11 ///修改描述: ///修改人: ///修改日期: ///备注: ///</summary> public class LogExport { private static object _lockerForLog = new object(); public static string LOGPATH = Application.StartupPath + "\\log\\checklog";//日志文件夹 /// <summary> /// 记录日志 /// </summary> /// <param name="content"></param> /// <param name="logPath"></param> public static void SaveLog(string content, string logPath = "") { try { if (string.IsNullOrEmpty(logPath)) { logPath = LOGPATH; } lock (_lockerForLog) { FileStream fs; if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } fs = new FileStream(Path.Combine(logPath, DateTime.Now.ToString("yyyyMMdd") + ".log"), FileMode.OpenOrCreate); StreamWriter streamWriter = new StreamWriter(fs); streamWriter.BaseStream.Seek(0, SeekOrigin.End); streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + " " + content); streamWriter.Flush(); streamWriter.Close(); fs.Close(); } } catch { } } } }
3、获取数据库中的镶嵌数据集
/// <summary> /// 获取界面上选择的镶嵌数据集 /// </summary> /// <returns></returns> public IMosaicDataset GetMosaicDataset() { try { _selMosicName = cmbMosicData.SelectedItem.ToString(); IPropertySet propertySet = new PropertySetClass(); propertySet.SetProperty("SERVER", ""); propertySet.SetProperty("INSTANCE", "sde:oracle11g:XXX.XXX.XXX/db11g"); propertySet.SetProperty("USER", "XXX"); propertySet.SetProperty("PASSWORD", "XXX"); propertySet.SetProperty("DATABASE", ""); propertySet.SetProperty("VERSION", ""); IWorkspaceFactory2 workspaceFactory2 = new SdeWorkspaceFactoryClass(); IWorkspace pWorkspace = workspaceFactory2.Open(propertySet, 0); IMosaicDataset pMosicDataset = null; IMosaicWorkspaceExtensionHelper pMosaicWsExHelper = new MosaicWorkspaceExtensionHelperClass(); IMosaicWorkspaceExtension pMosaicWsExt = pMosaicWsExHelper.FindExtension(pWorkspace); if (pMosaicWsExt != null) { try { pMosicDataset = pMosaicWsExt.OpenMosaicDataset(_selMosicName); } catch (Exception ex) { return pMosicDataset; } } return pMosicDataset; } catch (Exception ex) { return null; } }
4、跨线程调用控件的属性和方法
//定义两个委托 delegate void SetTextValueCallback(Control oControl, string propName, object propValue); delegate void SetUCLogValueHandler(string log, EnumLogType enumLogType); /// <summary> /// 设置控件参数 /// </summary> /// <param name="oControl">控件</param> /// <param name="propName">参数名称</param> /// <param name="propValue">参数值</param> private void SetTextPropertyValue(Control oControl, string propName, object propValue) { if (oControl.InvokeRequired) { SetTextValueCallback d = new SetTextValueCallback(SetTextPropertyValue); oControl.Invoke(d, new object[] { oControl, propName, propValue }); } else { Type t = oControl.GetType(); System.Reflection.PropertyInfo[] props = t.GetProperties(); foreach (System.Reflection.PropertyInfo p in props) { if (p.Name.ToUpper() == propName.ToUpper()) { p.SetValue(oControl, propValue, null); } } } } /// <summary> /// 设置UCLog控件输出 /// </summary> /// <param name="log"></param> /// <param name="enumLogType"></param> private void SetUClogValue(string log, EnumLogType enumLogType) { if (_ucLog.InvokeRequired == true) { SetUCLogValueHandler set = new SetUCLogValueHandler(_ucLog.AddMsg);//委托的方法参数应和SetCalResult一致 _ucLog.Invoke(set, new object[] { log, enumLogType }); //此方法第二参数用于传入方法,代替形参result } } //实例化 SetTextValueCallback setControlvalue = new SetTextValueCallback(SetTextPropertyValue); SetUCLogValueHandler setUClogValue = new SetUCLogValueHandler(SetUClogValue); //调用 setControlvalue(_progresslabal, "Text", "正在创建金字塔... ..."); setUClogValue(_selMosicName + "数据BuildPyramids处理成功." + log, EnumLogType.SuccessAudit);
5、创建XML文件
public static void CreateXmlFile(string xmlPath, string rootName) { XmlDocument xmlDoc = new XmlDocument(); //创建类型声明节点 XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "GB2312", ""); xmlDoc.AppendChild(node); //创建根节点 XmlNode root = xmlDoc.CreateElement(rootName); xmlDoc.AppendChild(root); CreateNode(xmlDoc, root, "NodeName", "value"); try { xmlDoc.Save(xmlPath); } catch (Exception ex) { } } /// <summary> /// 创建节点 /// </summary> /// <param name="xmldoc"></param> xml文档 /// <param name="parentnode"></param>父节点 /// <param name="name"></param> 节点名 /// <param name="value"></param> 节点值 /// public static void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value) { XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null); node.InnerText = value; parentNode.AppendChild(node); }
6、我们在执行控制台应用程序或者其他程序时,有时候加了断点也无法调试,一个可能是我们设置了新的项目生成配置,而该配置默认的不生成.pdb文件,导致无法调试,解决方案是在“生成”页面的“高级”里把输出——>调试信息改成full。
7、查询用户job的运行状态
select job,what,failures,broken from user_jobs
8、arcengine删除表
/// <summary> /// 从工作空间中删除指定表 /// </summary> /// <param name="pWorkSpace"></param> /// <param name="tableName"></param> /// <returns></returns> public static bool DeleteTable(IWorkspace pWorkspace,String tableName) { try { IFeatureWorkspace pFeatureworkspace = pWorkspace as IFeatureWorkspace; IFeatureClass pFeatureClass = pFeatureworkspace.OpenFeatureClass(tableName);//存在删除 if (pFeatureClass != null) { IDataset pDataset = pFeatureClass as IDataset; if (pDataset.CanDelete()) { pDataset.Delete(); return true;//删除成功 } } } catch { } return false;//删除失败 }
9、C#向Oracle的Blob字段插入值(引用自网络)
(1)先插入其它字段,BLOB字段初始化的时候,先初始化一个EMPTY_BLOB(),相当于一个BLOB对象的空壳,内部啥也没有,但是是一个对象。
(2)SELECT <BLOB字段> FROM <表名称> WHERE <关键字>=<插入关键值> FOR UPDATE;--FOR UPDATE是必须的。
(3)如果在程序中就直接得到一个BLOB对象的引用(相当于指针),如果过程中,上述修改为SELECT INTO到一个BLOB类型的变量中,其实也是BLOB对象的指针,然后对这个BLOB进行编辑,过程中对其进行编辑使用DBMS_LOB包来完成编辑工作,程序中将前端提交的内容(可能是图片或者上传文件直接可以转为byte[]数组、可能是文本字符串需要根据相应字符集转义为byte[]数组),通过java.sql.Blob接口对应的驱动实现类内部的setBytes(....)方法来完成写入。
(4)不论是程序还是过程,使用UPDATE <表名称> WHERE <关键字>=<插入关键值>; COMMIT;即可完成编辑过程。
static void Main(string[] args) { int nSize = 50000; byte[] bArray = new byte[nSize]; for (int i = 0; i < nSize; i++) { bArray[i] = 68; } /* * 须使用OracleClient命名空间 * 须安装支持OLEDB 的ORACLE 客户端 */ string sConn = "Data Source=192.168.0.5;User ID=hpbjjy;Unicode=True;Password=hpbjjy"; OracleConnection conn = new OracleConnection(sConn); OracleTransaction tra = null; try { conn.Open(); Console.WriteLine("打开成功!"); OracleCommand com = conn.CreateCommand(); tra = conn.BeginTransaction(); com.Transaction = tra; /* * 先使用查询获得该BLOB字段的对象 * 同时使用for update 锁定该字段,否则无法修改 */ string SQL = "select tag2 from sysconf where name='HotelName' for update"; // tag2字段类型为BLOB com.CommandText = SQL; OracleDataReader reader = com.ExecuteReader(); OracleLob lob = OracleLob.Null; reader.Read(); lob = reader.GetOracleLob(0); // 获取BLOB对象 lob.Write(bArray, 0, bArray.Length); // 将数据写入该对象 SQL = "update sysconf set tag2=:t where name='HotelName'"; com.CommandText = SQL; com.Parameters.Add("t", OracleType.Blob).Value = lob; com.ExecuteNonQuery(); tra.Commit(); Console.WriteLine("成功完成!"); } catch (Exception ex) { Console.WriteLine(ex.Message); if (tra != null) tra.Rollback(); } if (conn.State == ConnectionState.Open) conn.Close(); Console.Read(); }
10、Dev Treelist使用方法
右击节点信息
TreeListHitInfo hInfo = treeList1.CalcHitInfo(new Point(e.X, e.Y)); TreeListNode node = hInfo.Node; treeList1.FocusedNode = node;
代码初始化Treelist
DataTable dt = new DataTable(); DataColumn dcOID = new DataColumn("KeyFieldName", Type.GetType("System.Int32")); DataColumn dcParentOID = new DataColumn("ParentFieldName", Type.GetType("System.Int32")); DataColumn dcNodeName = new DataColumn("NodeName", Type.GetType("System.String")); DataColumn dcNodeCode = new DataColumn("NodeCode", Type.GetType("System.String")); dt.Columns.Add(dcOID); dt.Columns.Add(dcParentOID); dt.Columns.Add(dcNodeName); dt.Columns.Add(dcNodeCode); DataRow dr1 = dt.NewRow(); dr1["KeyFieldName"] = 1; dr1["ParentFieldName"] = 0; dr1["NodeName"] = "第三次农业普查"; dr1["NodeCode"] = "根节点编码"; dt.Rows.Add(dr1); DataRow dr2 = dt.NewRow(); dr2["KeyFieldName"] = 2; dr2["ParentFieldName"] = 1; dr2["NodeName"] = "农作物总播种面积"; dr2["NodeCode"] = "节点子节点编码2"; dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow(); dr3["KeyFieldName"] = 3; dr3["ParentFieldName"] = 1; dr3["NodeName"] = "主要农作物播种面积"; dr3["NodeCode"] = "节点子节点编码3"; dt.Rows.Add(dr3); treeList_SNP.BeginUnboundLoad(); treeList_SNP.KeyFieldName = "KeyFieldName"; treeList_SNP.ParentFieldName = "ParentFieldName"; treeList_SNP.DataSource = dt; treeList_SNP.EndUnboundLoad(); treeList_SNP.ExpandAll(); TreeList_SNP = treeList_SNP; treeList_SNP.Nodes.FirstNode.Nodes[0].Checked = true;
http://blog.163.com/china__xuhua/blog/static/199723169201203111653783/
http://www.dxper.net/thread-62-1-1.html
http://www.jb51.net/article/53337.htm
11、DEV XtraForm 皮肤设置
在启动的main函数里加上: BonusSkins.Register(); AppearanceObject.DefaultFont = new Font("微软雅黑", 9); UserLookAndFeel.Default.SetSkinStyle("标准风格"); SkinManager.EnableFormSkins(); 引用:using DevExpress.LookAndFeel; using DevExpress.Skins; using DevExpress.UserSkins; using DevExpress.Utils; using System.Drawing;
12、两个类之间实时传值(利用委托)
假设FormA窗体中有一个数据处理的ProcessBar需要实时更新状态,但是FormA中的数据处理方法在ClassA,这样,我们就行要根据ClassA中方法执行的状态, 实时给FormA中的ProcessBar传值; 在ClassA中定义如下: //委托 public delegate void ExecutingEeventHandler(int nodeIndex,int nodeCount); /// <summary> /// 传递processbar序号 /// </summary> public event ExecutingEeventHandler Executing; //事件触发函数 private void OnExcuting(int index, int nodeCount) { if (Executing != null) { Executing(index, nodeCount); } } 在ClassA的执行方法中加入事件触发函数:OnExcuting(index, catalogNodeLists.Count); 在FormA中把ProcessBar状态更新的函数注册到ExecutingEeventHandler中; classA.Executing += new ClassA.ExecutingEeventHandler(expOper_Executing); void expOper_Executing(int nodeIndex, int nodeCount) { _Processbar.SetProgress(nodeIndex, nodeCount); }
13、dev treelist 只允许同级拖拽,不变成子目录设置
private void treeList1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { TreeListNode dragNode, targetNode; TreeList tl = sender as TreeList; Point p = tl.PointToClient(new Point(e.X, e.Y)); dragNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode; targetNode = tl.CalcHitInfo(p).Node; tl.SetNodeIndex(dragNode, tl.GetNodeIndex(targetNode)); e.Effect = DragDropEffects.None; }
14、GridView 列对齐
col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
15、设置TableLayoutPanel等宽高(http://blog.csdn.net/langyuewu/article/details/38865423#),最好在代码中初始化TableLayoutPanel
private void InitLayoutDemo() { TableLayoutPanel demoLayoutPanel = new TableLayoutPanel(); demoLayoutPanel.Dock = DockStyle.Fill; this.Controls.Add(demoLayoutPanel); int row = 3, col = 3; DynamicLayout(demoLayoutPanel, row, col); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { Button btn = new Button(); btn.Text = string.Format("({0},{1})", i, j); btn.Dock = DockStyle.Fill; demoLayoutPanel.Controls.Add(btn); demoLayoutPanel.SetRow(btn, i); demoLayoutPanel.SetColumn(btn, j); } } } /// <summary> /// 动态布局 /// </summary> /// <param name="layoutPanel">布局面板</param> /// <param name="row">行</param> /// <param name="col">列</param> private void DynamicLayout(TableLayoutPanel layoutPanel, int row, int col) { layoutPanel.RowCount = row; //设置分成几行 for (int i = 0; i < row; i++) { layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F)); } layoutPanel.ColumnCount = col; //设置分成几列 for (int i = 0; i < col; i++) { layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F)); } }
15、XML操作
1 最常见的XML数据类型有:Element, Attribute,Comment, Text. 2 3 Element, 指形如<Name>Tom<Name>的节点。它可以包括:Element, Text, Comment, ProcessingInstruction, CDATA, and EntityReference. 4 5 Attribute, 指在<Employee >中的粗体部分。 6 7 Comment,指形如:<!-- my comment --> 的节点。 8 9 Text,指在<Name>Tom<Name>的粗体部分。 10 11 在XML中,可以用XmlNode对象来参照各种XML数据类型。 12 13 2.1 查询已知绝对路径的节点(集) 14 15 objNodeList = objDoc.SelectNodes(“Company/Department/Employees/Employee”) 16 17 或者 18 19 objNodeList = objNode.SelectNodes(“/Company/Department/Employees/Employee”) 20 21 以上两种方法可返回一个NodeList对象,如果要返回单个节点可使用SelectSingleNode方法,该方法如果查询到一个或多个节点,返回第一个节点;如果没有查询的任何节点返回 Nothing。例如: 22 23 objNode = objNode.SelectSingleNode(“/Company/Department/Employees/Employee”) 24 25 If Not (objNode is Nothing) then 26 27 ‘- Do process 28 29 End If 30 31 2.2 查询已知相对路径的节点(集) 32 33 可使用类似于文件路径的相对路径的方式来查询XML的数据 34 35 objNode = objDoc.SelectSingleNode(“Company/Department”) 36 37 objNodeList = objNode.SelectNodes(“../Department) 38 39 objNode = objNode.SelectNode(“Employees/Employee”) 40 41 2.3 查询已知元素名的节点(集) 42 43 在使用不规则的层次文档时,由于不知道中间层次的元素名,可使用//符号来越过中间的节点,查询其子,孙或多层次下的其他所有元素。例如: 44 45 objNodeList = objDoc.SelectNodes(“Company//Employee”) 46 47 2.4 查询属性(attribute)节点 48 49 以上的各种方法都返回元素(element)节点(集),返回属性(attribute),只需要采用相应的方法,在属性名前加一个@符号即可,例如: 50 51 objNodeList = objDoc.SelectNodes(“Company/Department/Employees/Employee/@id”) 52 53 objNodeList = objDoc.SelectNodes(“Company//@id”) 54 55 2.5 查询Text节点 56 57 使用text()来获取Text节点。 58 59 objNode = objDoc.SelectSingleNode(“Company/Department/Deparmt_Name/text()”) 60 61 2.6 查询特定条件的节点 62 63 使用[]符号来查询特定条件的节点。例如: 64 65 a. 返回id号为 10102的Employee节点 66 67 objNode = objDoc.SelectSingleNode(“Company/Department/Employees/Employee[@id=’10102’]”) 68 69 b. 返回Name为Zhang Qi的Name 节点 70 71 objNode = objDoc.SelectSingleNode(“Company/Department/Employees/Employee/Name[text()=’Zhang Qi’]”) 72 73 c. 返回部门含有职员22345的部门名称节点 74 75 objNode = objDoc.SelectSingleNode("Company/Department[Employees/Employee/@id='22345']/Department_Name") 76 77 2.7 查询多重模式的节点 78 79 使用 | 符号可以获得多重模式的节点。例如: 80 81 objNodeList = objDoc.SelectNodes(“Company/Department/Department_Name | Company/Department/Manager”) 82 83 2.8 查询任意子节点 84 85 使用*符号可以返回当前节点的所有子节点。 86 87 objNodeList = objDoc.SelectNodes(“Company/*/Manager) 88 89 或者 90 91 objNodeList = objNode.ChildNodes 92 93 94 95 3 XML数据的编辑 96 97 3.1 增加一个元素的属性(attribute)节点 98 99 Dim objNodeAttr As XmlNode 100 101 objNodeAttr = objDoc.CreateAttribute("id", Nothing) 102 103 objNodeAttr.InnerXml = "101" 104 105 objNode.Attributes.Append(objNodeAttr) 106 107 3.2 删除一个元素的属性 108 109 objNode.Attributes.Remove(objNodeAttr) 110 111 3.3 增加一个子元素(Element) 112 113 Dim objNodeChild As XmlNode 114 115 objNodeChild = objDoc.CreateElement(Nothing, "ID", Nothing) 116 117 objNodeChild.InnerXml = "101" 118 119 objNode.AppendChild(objNodeChild) 120 121 3.4 删除一个子元素 122 123 objNode.RemoveChild(objNodeChild) 124 125 3.5 替换一个子元素 126 127 objNOde.ReplaceChild(newChild,oldChild) 128 129 130 131 4 参考数据 132 133 <?xml version="1.0" encoding="UTF-8"?> 134 135 <Company> 136 137 <Department > 138 139 <Department_Name>Cai WuBu</Department_Name> 140 141 <Manager>Zhang Bin</Manager> 142 143 <Employees> 144 145 <Employee > 146 147 <Employee_ID>12345</Employee_ID> 148 149 <Name>Zhang Bin</Name> 150 151 <Gender>male</Gender> 152 153 </Employee> 154 155 <Employee > 156 157 <Employee_ID>10101</Employee_ID> 158 159 <Name>Zhang QI</Name> 160 161 <Gender>female</Gender> 162 163 </Employee> 164 165 <Employee > 166 167 <Employee_ID>10102</Employee_ID> 168 169 <Name>Zhang Xia</Name> 170 171 <Gender>male</Gender> 172 173 </Employee> 174 175 <Employee > 176 177 <Employee_ID>10201</Employee_ID> 178 179 <Name>ZhangChuang</Name> 180 181 <Gender>male</Gender> 182 183 </Employee> 184 185 <Employee > 186 187 <Employee_ID>10202</Employee_ID> 188 189 <Name>Zhang Jun</Name> 190 191 <Gender>male</Gender> 192 193 </Employee> 194 195 </Employees> 196 197 </Department> 198 199 <Department > 200 201 <Department_Name>KaiFa Bu</Department_Name> 202 203 <Manager>Wang Bin</Manager> 204 205 <Employees> 206 207 <Employee > 208 209 <Employee_ID>22345</Employee_ID> 210 211 <Name>Wang Bin</Name> 212 213 <Gender>male</Gender> 214 215 </Employee> 216 217 <Employee > 218 219 <Employee_ID>20101</Employee_ID> 220 221 <Name>Wang QI</Name> 222 223 <Gender>female</Gender> 224 225 </Employee> 226 227 <Employee > 228 229 <Employee_ID>20102</Employee_ID> 230 231 <Name>Wang Xia</Name> 232 233 <Gender>male</Gender> 234 235 </Employee> 236 237 <Employee > 238 239 <Employee_ID>20201</Employee_ID> 240 241 <Name>Wang Chuang</Name> 242 243 <Gender>male</Gender> 244 245 </Employee> 246 247 <Employee > 248 249 <Employee_ID>20201</Employee_ID> 250 251 <Name>Wang Jun</Name> 252 253 <Gender>male</Gender> 254 255 </Employee> 256 257 </Employees> 258 259 </Department> 260 261 </Company>
16、shp图层属性表读写效率
http://blog.csdn.net/freewaywalker/article/details/23703863
作者:jinqier
出处:http://www.cnblogs.com/jinqier/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。