• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#+ArcEngine常用方法(不定时更新)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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
{
    ///<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
            {
            }
        }
    }
}
View Code

 

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

 

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

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

 

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;//删除失败 
        }
View Code

 

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(....)方法来完成写入。

不论是程序还是过程,使用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.ogeek.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);

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

 

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’]”)

                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#------dataTable发布时间:2022-07-10
下一篇:
C# 扩展方法集发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap