Newer
Older
GHFX_REFACTOR / Utility.cs
wxn on 2 Nov 2016 27 KB 提交
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using GeoScene.Data;
using GeoScene.Engine;
using GeoScene.Globe;
using System.IO;
using System.Windows.Forms;
using System.Collections;
using System.Data;
using System.Xml;
using System.Net.NetworkInformation;
using System.Net;
using System.Security.Cryptography;

namespace Cyberpipe
{
    public class Utility
    {
        //public static string ConnectionString;

        public static string dbdatabase;
        public static string userID;

        public static Hashtable Pipe_QueryFields;
        public static string DBPassword;
        public static string DBServer;
        public static string DBBackUp;
        public static string serverip;
        public static int serverport;
        //public static string localicenseserverip;
        //public static int localicenseserverport;
        public static GeoScene.Engine.GSODataSource dataSource;
        public static List<LayerChild> LayerChilds;
        public static ArrayList LayerLabels;
        public static ArrayList LayerNames;
        public static ArrayList TerrainsName;
        public static ArrayList LayerNamesList;
        public static Hashtable LayerLabel_LayerIDs;
        public static Hashtable Query_Fields = new Hashtable();
        public static Hashtable Query_Roads = new Hashtable();
        public static Hashtable Pipe_Code = new Hashtable();
        public static List<PipelineType> listPipelineType;
        public static string PicRootURL;
        public static string PicDefaultURL;
        public static double dFlyAboveLine = 2;
        public static string userName;
        public static string projectStr;
        public static string userRole;

        //数据配置
        public static List<databaseClass> listDb;
        public static string backupurl;
        public static string backuppath;
        //上传下载配置
        public static string udserviceurl;
        public static string uploadpath;

        //传感器配置
        public static string sensorConnectString;
        public static string sensorDatabase;
        public static List<MarkerLayer> sensorMarkerLayers;

        //管线类型
        public static string pipelinetype;
        //施工库配置
        public static string sgdbip;
        public static string sgdbname;
        public static string sgdbuser;
        public static string sgdbpwd;
        //规划库配置
        public static string ghdbip;
        public static string ghdbname;
        public static string ghdbuser;
        public static string ghdbpwd;
        public static List<Location> locationList;

        public static void SetBallons(GSOBalloon featureTooltip, GSOBalloonEx balloonEx)
        {
            featureTooltip.CacheFilePath = Application.StartupPath + "/GeoScene/Globe/Temp";

            featureTooltip.SetSize(EnumSizeIndex.ROUNDED_CX, 0);
            featureTooltip.SetSize(EnumSizeIndex.ROUNDED_CY, 0);
            featureTooltip.SetSize(EnumSizeIndex.MARGIN_CX, 3);
            featureTooltip.SetSize(EnumSizeIndex.MARGIN_CY, 3);
            featureTooltip.SetSize(EnumSizeIndex.ANCHOR_HEIGHT, 0);
            featureTooltip.SetSize(EnumSizeIndex.ANCHOR_WIDTH, 0);
            featureTooltip.SetSize(EnumSizeIndex.ANCHOR_MARGIN, 0);
            featureTooltip.SetSize(EnumSizeIndex.ANCHOR_OFFSET_CX, 1);
            featureTooltip.SetSize(EnumSizeIndex.ANCHOR_OFFSET_CY, -1);
            featureTooltip.SetDirection(EnumToolTipDirection.TD_BOTTOMEDGE_LEFT);

            featureTooltip.EscapeSequencesEnabled = true;
            featureTooltip.HyperlinkEnabled = true;
            featureTooltip.Opaque = 30;
            featureTooltip.MaxWidth = 300;
            featureTooltip.SetShadow(0, 0, 50, true, 0, 0);

            balloonEx.SetSize(EnumSizeIndexEx.CONTENT_CX, 500);
            balloonEx.SetSize(EnumSizeIndexEx.CONTENT_CY, 300);
            balloonEx.Opaque = 5;
            balloonEx.SetBorder(Color.White, 1, 1);
            balloonEx.SetColorBkType(EnumBkColorTypeEx.SKY);
        }

        public static GSOFeature FindFeatureByUserID(GSOFeatureDataset featdataset, string fieldname, string value)
        {
            GSOFeatures feats = featdataset.GetAllFeatures();
            for (int i = 0; i < feats.Length; i++)
            {
                GSOFeature feat = feats[i];
                if (feat.GetFieldAsString(fieldname) == value)
                {
                    return feat;
                }
            }
            return null;
        }
        
        public static GeoScene.Data.GSOPoint2d XYZ_2_Latlon(double x, double y)
        {
            int id = GeoScene.Data.GSOProjectManager.AddProject(Utility.projectStr);
            //  GeoScene.Data.GSOProjectManager.SetCurProject(id);

            GeoScene.Data.GSOPoint2d pt2d = new GeoScene.Data.GSOPoint2d(x, y);
            GeoScene.Data.GSOPoint2d result = GeoScene.Data.GSOProjectManager.Inverse(pt2d, id);
            return result;
        }

        public static GeoScene.Data.GSOPoint2d Latlon_2_XYZ(double lon, double lat)
        {
            int id = GeoScene.Data.GSOProjectManager.AddProject(Utility.projectStr);

            GeoScene.Data.GSOPoint2d pt2d = new GeoScene.Data.GSOPoint2d(lon, lat);
            GeoScene.Data.GSOPoint2d result = GeoScene.Data.GSOProjectManager.Forward(pt2d, id);
            return result;
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="pToEncrypt">要加密字符串</param>
        /// <returns></returns>
        public static string MD5Encrypt(string pToEncrypt)
        {
            string sKey = "12345678";//默认8位加密密匙
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }
        //
        //MD5加密
        //
        public static string MD5Encrypt2(string pToEncrypt)
        {
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(inputByteArray);
            
            string ret = BitConverter.ToString(output).Replace("-", "");
            ret = ret.ToLower();
            return ret;
        }

        public static GSOFeatures Table2Features(DataTable table, string currentQueryLayer, GeoScene.Globe.GSOGlobeControl globeControl1)
        {
            GSOFeatures features = new GSOFeatures();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow row = table.Rows[i];

                string featureName = row["编号"].ToString();
                featureName = featureName.Trim();

                //GSOLayer layer = globeControl1.Globe.Layers.GetLayerByID((int)(Utility.LayerLabel_LayerIDs[currentQueryLayer]));
                GSOLayer layer = globeControl1.Globe.Layers.GetLayerByCaption(currentQueryLayer);
                GSOFeatures tempfeatures = layer.GetFeatureByName(featureName, false);
                if (tempfeatures.Length > 0)
                {
                    features.Add(tempfeatures[0]);
                }
            }
            return features;
        }

        public static string filename = Application.StartupPath + "\\Config.xml";
        public static string filenameSensor = Application.StartupPath + "\\sensorConfig.xml";
        public static string filenamePipelineType = Application.StartupPath + "\\PipelineType.xml";
        public static string filenameDbconfig = Application.StartupPath + "\\databaseConfig.xml";
        public static string filenameLocation = Application.StartupPath + "\\Location.xml";
        //程序启动的时候读取配置文件
        public static void SetParams()
        {
            #region 读取 filename "Config.xml"
            Utility.LayerChilds = new List<LayerChild>();
            Utility.LayerLabels = new System.Collections.ArrayList();
            Utility.TerrainsName = new System.Collections.ArrayList();
            Utility.LayerNames = new System.Collections.ArrayList();
            Utility.LayerNamesList = new System.Collections.ArrayList();
            Utility.LayerLabel_LayerIDs = new System.Collections.Hashtable();
            if (File.Exists(filename))
            {
                XmlTextReader XmlReader = new XmlTextReader(filename);
                try
                {
                    while (XmlReader.Read())
                    {
                        if (XmlReader.Name == "database")
                        {
                            Utility.dbdatabase = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "dbpassword")
                        {
                            Utility.DBPassword = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "user")
                        {
                            Utility.userID = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "locaserverip")
                        {
                            Utility.serverip = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "locaserverport")
                        {
                            Utility.serverport = Convert.ToInt32(XmlReader.ReadElementString());
                        }
                        //else if (XmlReader.Name == "localicenseserverip")
                        //{
                        //    Utility.localicenseserverip = XmlReader.ReadElementString();
                        //}
                        //else if (XmlReader.Name == "localicenseserverport")
                        //{
                        //    Utility.localicenseserverport = Convert.ToInt32(XmlReader.ReadElementString());
                        //}
                        else if (XmlReader.Name == "dbbackuppath")
                        {
                            Utility.DBBackUp = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "layerchild")
                        {
                            LayerChild child = new LayerChild();
                            child.attriLabel = XmlReader["label"].Trim();
                            child.attriLayer = XmlReader["layer"].Trim();
                            child.attriType = XmlReader["type"].Trim();
                            Utility.LayerChilds.Add(child);
                            Utility.LayerLabels.Add(XmlReader["label"].Trim());
                            Utility.LayerNames.Add(XmlReader["layer"].Trim());

                            string layername = XmlReader["layer"].Trim();
                            if (layername.EndsWith("管线"))
                            {
                                Utility.LayerNamesList.Add(layername.Substring(0, layername.Length - 2));
                            }
                        }

                        else if (XmlReader.Name == "Terrain")
                        {
                            Utility.TerrainsName.Add(XmlReader.ReadElementString());
                        }
                        else if (XmlReader.Name == "dbserver")
                        {
                            Utility.DBServer = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "rooturl")
                        {
                            Utility.PicRootURL = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "defaultimgurl")
                        {
                            Utility.PicDefaultURL = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "queryfield")
                        {
                            Utility.Query_Fields.Add(XmlReader["label"], XmlReader.ReadElementString());
                        }
                        else if (XmlReader.Name == "location")
                        {
                            Utility.Query_Roads.Add(XmlReader["label"], XmlReader.ReadElementString());
                        }
                        else if (XmlReader.Name == "pipelineCode")
                        {
                            Utility.Pipe_Code.Add(XmlReader["label"], XmlReader.ReadElementString());
                            
                        }
                        else if (XmlReader.Name == "projectStr")
                        {
                            Utility.projectStr = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "backupserverurl")
                        {
                            Utility.backupurl = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "backuppath")
                        {
                            Utility.backuppath = XmlReader.ReadElementString();
                        }
                        //else if (XmlReader.Name == "uploadpath")
                        //{
                        //    Utility.uploadpath = XmlReader.ReadElementString();
                        //}
                        //else if (XmlReader.Name == "udserviceurl")
                        //{
                        //    Utility.udserviceurl = XmlReader.ReadElementString();
                        //}
                        else if (XmlReader.Name == "pipelinetype")
                        {
                            Utility.pipelinetype = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "shdbip")
                        {
                            Utility.sgdbip = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "shdbname")
                        {
                            Utility.sgdbname = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "shdbuser")
                        {
                            Utility.sgdbuser = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "shdbpwd")
                        {
                            Utility.sgdbpwd = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "ghdbip")
                        {
                            Utility.ghdbip = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "ghdbname")
                        {
                            Utility.ghdbname = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "ghdbuser")
                        {
                            Utility.ghdbuser = XmlReader.ReadElementString();
                        }
                        else if (XmlReader.Name == "ghdbpwd")
                        {
                            Utility.ghdbpwd = XmlReader.ReadElementString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogError.PublishError(ex);
                }
                finally
                {
                    XmlReader.Close();
                }
            }
            else
            {
                MessageBox.Show("配置文件" + filename + "不存在!", "提示");
            }
            #endregion

            #region 读取 filenameSensor "sensorConfig.xml"
            sensorMarkerLayers = new List<MarkerLayer>();
            if (File.Exists(filenameSensor))
            {
                XmlTextReader XmlReader = new XmlTextReader(filenameSensor);
                try
                {
                    while (XmlReader.Read())
                    {
                        if (XmlReader.Name == "ConnectString")
                        {
                            string dbserver = XmlReader["dbserver"].Trim();
                            string dbserverport = XmlReader["dbserverport"].Trim();
                            string database = XmlReader["database"].Trim();
                            string username = XmlReader["username"].Trim();
                            string password = XmlReader["password"].Trim();
                            Utility.sensorDatabase = database;
                            Utility.sensorConnectString = "Server=" + dbserver + ";Port=" + dbserverport + ";Database=" + database + ";Uid=" + username + ";Pwd=" + password + "";
                        }
                        else if (XmlReader.Name == "MarkerLayer")
                        {
                            MarkerLayer markerLayer = new MarkerLayer();
                            string layerName = XmlReader["layerName"].Trim();
                            string tableName = XmlReader["tableName"].Trim();
                            markerLayer.layerName = layerName;
                            markerLayer.tableName = tableName;
                            Dictionary<string, string> fields = new Dictionary<string, string>();
                            XmlReader.ReadSubtree();
                            while (XmlReader.Read())
                            {
                                if (XmlReader.Name == "field")
                                {
                                    string name = XmlReader["name"].Trim();
                                    string label = XmlReader["label"].Trim();
                                    fields.Add(name, label);
                                }
                                else if (XmlReader.Name == "MarkerLayer")
                                {
                                    break;
                                }
                            }
                            markerLayer.fields = fields;
                            sensorMarkerLayers.Add(markerLayer);
                        }                       
                    }
                }
                catch (Exception ex)
                {
                    //LogError.PublishError(ex);
                }
                finally
                {
                    XmlReader.Close();
                }
            }
            else
            {
                MessageBox.Show("配置文件" + filenameSensor + "不存在!", "提示");
            }
            #endregion

            #region 读取 filenamePipelineType "PipelineType.xml"
            listPipelineType = new List<PipelineType>();
            if (File.Exists(filenamePipelineType))
            {
                XmlTextReader XmlReader = new XmlTextReader(filenamePipelineType);
                try
                {
                    while (XmlReader.Read())
                    {
                        if (XmlReader.Name == "PipelineCode")
                        {
                            string pipelinecode = XmlReader["code"] == null ? null : XmlReader["code"].Trim();
                            string pipelinename = XmlReader["name"] == null ? null : XmlReader["name"].Trim();
                            string pipelinetype = XmlReader["type"] == null ? null : XmlReader["type"].Trim();
                            if (pipelinecode != null && pipelinename != null && pipelinetype != null)
                            {
                                PipelineType pipelineType = new PipelineType(pipelinecode, pipelinename, pipelinetype);
                                if (listPipelineType.Contains(pipelineType) == false)
                                {
                                    listPipelineType.Add(pipelineType);
                                }
                            }
                        }                       
                    }
                }
                catch (Exception ex)
                {
                    //LogError.PublishError(ex);
                }
                finally
                {
                    XmlReader.Close();
                }
            }
            else
            {
                MessageBox.Show("配置文件" + filenamePipelineType + "不存在!", "提示");
            }
            #endregion

            #region 读取 database "databaseConfig.xml"
            listDb = new List<databaseClass>();
            if (File.Exists(filenameDbconfig))
            { 
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(filenameDbconfig);

                    XmlNode xn = doc.SelectSingleNode("Database");
                    // 得到根节点的所有子节点
                    XmlNodeList xnl = xn.ChildNodes;
                    foreach (XmlNode xn1 in xnl)
                    {
                        databaseClass model = new databaseClass();
                        XmlElement xe = (XmlElement)xn1;// 将节点转换为元素,便于得到节点的属性值
                        model.title = xe.GetAttribute("title");
                        // 得到database节点的所有子节点
                        XmlNodeList xnl0 = xe.ChildNodes;
                        model.dbip = xnl0.Item(0).InnerText;
                        model.database = xnl0.Item(1).InnerText;
                        model.dbuser = xnl0.Item(2).InnerText;
                        model.dbpassword = xnl0.Item(3).InnerText;

                        listDb.Add(model);
                    }
                }
                catch (Exception ex)
                {
                    //LogError.PublishError(ex);
                }
                //finally
                //{
                //    doc.Close();
                //}
            }
            else
            {
                MessageBox.Show("配置文件" + filenameDbconfig + "不存在!", "提示");
            }
            #endregion

            #region
            XmlTextReader XmlReaderLocation = null;
            try
            {
                if (File.Exists(filenameLocation))
                {
                    locationList = new List<Location>();
                    locationList.Add(new Location("", "", "", ""));
                    XmlReaderLocation = new XmlTextReader(filenameLocation);
                    while (XmlReaderLocation.Read())
                    {
                        if (XmlReaderLocation.Name == "location")
                        {
                            string name = XmlReaderLocation["name"] == null ? null : XmlReaderLocation["name"].Trim();
                            string x = XmlReaderLocation["x"] == null ? null : XmlReaderLocation["x"].Trim();
                            string y = XmlReaderLocation["y"] == null ? null : XmlReaderLocation["y"].Trim();
                            string z = XmlReaderLocation["z"] == null ? null : XmlReaderLocation["z"].Trim();

                            if (name != null)
                            {
                                locationList.Add(new Location(name, x, y, z));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //LogError.PublishError(ex);
            }
            finally
            {
                if (null != XmlReaderLocation)
                {
                    XmlReaderLocation.Close();
                }
            }


            #endregion
        }

        /*
        //判断网络是否连接
        public static bool isNetworkConnectionSuccess(string ipAdress)
        {
            //return true;
            if (ipAdress == null)
            {
                return false;
            }
            if (ipAdress.Contains("\\"))
            {
                ipAdress = ipAdress.Substring(0, ipAdress.LastIndexOf('\\'));
            }
            if (ipAdress.Trim() == "localhost" || ipAdress.Trim() == "127.0.0.1" || ipAdress.Trim() == Dns.GetHostName())
            {
                return true;
            }
            Ping ping = new Ping();
            try
            {
                PingReply pr = ping.Send(ipAdress.Trim(), 3000);
                if (pr.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogError.PublishError(ex);
                return false;
            }
        }
        */

        ////根据图层中的对象特征来划分内容
        public static string getCodeByName(string name)
        {
            string code = "";
            if (Utility.listPipelineType != null)
            {
                List<PipelineType> list = Utility.listPipelineType;

                for (int i = 0; i < list.Count; i++)
                {
                    PipelineType pipelineType = Utility.listPipelineType[i];
                    if (name == pipelineType.name)
                    {
                        code = pipelineType.code;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            return code;
        }
        //根据附属物图层名字得到里面含有的附属物
        public static string[] getAccStrsByLayer(string layername)
        {
            string[] accStrs = null;
            string sql = "select 附属物名称 from " + layername + " group by 附属物名称";
            //DataTable table = OledbHelper.QueryTable(sql);
            DataSet dataset = OledbHelper.getDataSet(sql, layername);
            if (dataset != null)
            {
                accStrs = new string[dataset.Tables[0].Rows.Count];
                for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
                {
                    accStrs[i] = dataset.Tables[0].Rows[i][0].ToString();
                }
                return accStrs;
            }
            else
            {
                return accStrs;
            }


        }
        //删除内存图层中指定名称的feature
        public static void RemoveFeatureFromName(GSOGlobeControl globeControl1, string featureName)
        {
            GSOFeatures features = globeControl1.Globe.MemoryLayer.GetFeatureByName(featureName, true);
            if (features != null)
            {
                for (int i = features.Length - 1; i >= 0; i--)
                {
                    GSOFeature feature = features[i];
                    if (feature != null)
                    {
                        globeControl1.Globe.MemoryLayer.RemoveFeatureByID(feature.ID);
                    }
                }
            }
            globeControl1.Refresh();
        }
    }
}