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; 
        
View Code

 

 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
{
    ///
    ///目的:日志操作类
    ///创建人:jwh
    ///创建日期:2016/7/11
    ///修改描述:
    ///修改人:
    ///修改日期:
    ///备注:
    ///
    public class LogExport
    {
        private static object _lockerForLog = new object();
        public static string LOGPATH = Application.StartupPath + "\\log\\checklog";//日志文件夹

        /// 
        /// 记录日志
        /// 
        /// 
        /// 
        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
            {
            }
        }
    }
}
View Code

 

 3、获取数据库中的镶嵌数据集

/// 
        /// 获取界面上选择的镶嵌数据集
        /// 
        /// 
        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;
            }
        }
View Code

 

4、跨线程调用控件的属性和方法 

//定义两个委托
        delegate void SetTextValueCallback(Control oControl, string propName, object propValue);
        delegate void SetUCLogValueHandler(string log, EnumLogType enumLogType);     
        
        
        
        /// 
        /// 设置控件参数
        /// 
        /// 控件
        /// 参数名称
        /// 参数值
        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);
                    }
                }
            }
        }

        /// 
        /// 设置UCLog控件输出
        /// 
        /// 
        /// 
        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);
        
View Code

 

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)
            {
            }
        }

        ///     
        /// 创建节点    
        ///     
        ///   xml文档  
        /// 父节点    
        ///   节点名  
        ///   节点值  
        ///   
        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);
        }
View Code

 

6、我们在执行控制台应用程序或者其他程序时,有时候加了断点也无法调试,一个可能是我们设置了新的项目生成配置,而该配置默认的不生成.pdb文件,导致无法调试,解决方案是在“生成”页面的“高级”里把输出——>调试信息改成full。

 

7、查询用户job的运行状态

select job,what,failures,broken from user_jobs

 

8、arcengine删除表

        /// 
        /// 从工作空间中删除指定表
        /// 
        /// 
        /// 
        /// 
        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;//删除失败 
        }
View Code

 

9、C#向Oracle的Blob字段插入值(引用自网络)

 (1)先插入其它字段,BLOB字段初始化的时候,先初始化一个EMPTY_BLOB(),相当于一个BLOB对象的空壳,内部啥也没有,但是是一个对象。
 (2)SELECT  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();
}
View Code

 

10、Dev Treelist使用方法

右击节点信息

                TreeListHitInfo hInfo = treeList1.CalcHitInfo(new Point(e.X, e.Y));
                TreeListNode node = hInfo.Node;
                treeList1.FocusedNode = node;
View Code

代码初始化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;
View Code

 

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
View Code

 

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;
View Code

 

12、两个类之间实时传值(利用委托)

假设FormA窗体中有一个数据处理的ProcessBar需要实时更新状态,但是FormA中的数据处理方法在ClassA,这样,我们就行要根据ClassA中方法执行的状态,
实时给FormA中的ProcessBar传值;

在ClassA中定义如下:

        //委托
        public delegate void ExecutingEeventHandler(int nodeIndex,int nodeCount);

        /// 
        /// 传递processbar序号
        /// 
        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);
        }
        
View Code

 

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;
}
View Code

 

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);  
                }  
            }  
        }  
  
        ///   
        /// 动态布局  
        ///   
        /// 布局面板  
        ///   
        ///   
        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));  
            }  
        }  
View Code

 

15、XML操作

  1 最常见的XML数据类型有:Element, Attribute,Comment, Text.
  2 
  3    Element, 指形如Tom的节点。它可以包括:Element, Text, Comment, ProcessingInstruction, CDATA, and EntityReference.
  4 
  5    Attribute, 指在中的粗体部分。
  6 
  7    Comment,指形如: 的节点。
  8 
  9    Text,指在Tom的粗体部分。
 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    
134 
135    
136 
137    
138 
139    Cai WuBu
140 
141    Zhang Bin
142 
143    
144 
145    
146 
147    12345
148 
149    Zhang Bin
150 
151    male
152 
153    
154 
155    
156 
157    10101
158 
159    Zhang QI
160 
161    female
162 
163    
164 
165    
166 
167    10102
168 
169    Zhang Xia
170 
171    male
172 
173    
174 
175    
176 
177    10201
178 
179    ZhangChuang
180 
181    male
182 
183    
184 
185    
186 
187    10202
188 
189    Zhang Jun
190 
191    male
192 
193    
194 
195    
196 
197    
198 
199    
200 
201    KaiFa Bu
202 
203    Wang Bin
204 
205    
206 
207    
208 
209    22345
210 
211    Wang Bin
212 
213    male
214 
215    
216 
217    
218 
219    20101
220 
221    Wang QI
222 
223    female
224 
225    
226 
227    
228 
229    20102
230 
231    Wang Xia
232 
233    male
234 
235    
236 
237    
238 
239    20201
240 
241    Wang Chuang
242 
243    male
244 
245    
246 
247    
248 
249    20201
250 
251    Wang Jun
252 
253    male
254 
255    
256 
257    
258 
259    
260 
261    
View Code

 

16、shp图层属性表读写效率

http://blog.csdn.net/freewaywalker/article/details/23703863

转载于:https://www.cnblogs.com/jinqier/p/5720535.html

你可能感兴趣的:(操作系统,数据库,java)