/// <summary>
        /// 带有参数的CreateOption
        /// </summary>
        /// <param name="strObjTag"></param>
        /// <param name="treeNode"></param>
        /// <param name="collectionName"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static Boolean CreateCollectionWithOptions(String strObjTag, TreeNode treeNode, String collectionName,
                                                          CollectionOptionsBuilder option)
        {
            //不支持中文 JIRA ticket is created : SERVER-4412
            //SERVER-4412已经在2013/03解决了
            //collection names are limited to 121 bytes after converting to UTF-8.
            Boolean       rtnResult  = false;
            MongoDatabase mongoDB    = GetMongoDBBySvrPath(strObjTag);
            String        strSvrPath = SystemManager.GetTagData(strObjTag);
            String        svrKey     = strSvrPath.Split("/".ToCharArray())[(int)PathLv.InstanceLV];
            String        ConKey     = strSvrPath.Split("/".ToCharArray())[(int)PathLv.ConnectionLV];

            if (mongoDB != null)
            {
                if (!mongoDB.CollectionExists(collectionName))
                {
                    mongoDB.CreateCollection(collectionName, option);
                    foreach (TreeNode item in treeNode.Nodes)
                    {
                        if (item.Tag.ToString().StartsWith(COLLECTION_LIST_TAG))
                        {
                            item.Nodes.Add(FillCollectionInfoToTreeNode(collectionName, mongoDB, ConKey + "/" + svrKey));
                        }
                    }
                    rtnResult = true;
                }
            }
            return(rtnResult);
        }
        /// <summary>
        /// 根据路径字符获得服务器
        /// </summary>
        /// <param name="strObjTag">[Tag:Connection/Host@Port/DBName/Collection]</param>
        /// <returns></returns>
        public static MongoServer GetMongoServerBySvrPath(String strObjTag)
        {
            String strSvrPath = SystemManager.GetTagData(strObjTag);

            String[] strPath = strSvrPath.Split("/".ToCharArray());
            if (strPath.Length == 1)
            {
                //[Tag:Connection
                if (_mongoConnSvrLst.ContainsKey(strPath[0]))
                {
                    return(_mongoConnSvrLst[strPath[0]]);
                }
            }
            if (strPath.Length > 1)
            {
                if (strPath[0] == strPath[1])
                {
                    //[Tag:Connection/Connection/DBName/Collection]
                    return(_mongoConnSvrLst[strPath[0]]);
                }
                else
                {
                    //[Tag:Connection/Host@Port/DBName/Collection]
                    String strInstKey = String.Empty;
                    strInstKey = strPath[(int)PathLv.ConnectionLV] + "/" + strPath[(int)PathLv.ServerLV];
                    if (_mongoInstanceLst.ContainsKey(strInstKey))
                    {
                        return(MongoServer.Create(_mongoInstanceLst[strInstKey].Settings));
                    }
                }
            }
            return(null);
        }
        /// <summary>
        /// Create Collection
        /// </summary>
        /// <param name="strObjTag"></param>
        /// <param name="treeNode"></param>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static Boolean CreateCollection(String strObjTag, TreeNode treeNode, String collectionName)
        {
            Boolean       rtnResult  = false;
            MongoDatabase mongoDB    = GetMongoDBBySvrPath(strObjTag);
            String        strSvrPath = SystemManager.GetTagData(strObjTag);
            String        svrKey     = strSvrPath.Split("/".ToCharArray())[(int)PathLv.ServerLV];
            String        ConKey     = strSvrPath.Split("/".ToCharArray())[(int)PathLv.ConnectionLV];

            if (mongoDB != null)
            {
                if (!mongoDB.CollectionExists(collectionName))
                {
                    mongoDB.CreateCollection(collectionName);
                    foreach (TreeNode item in treeNode.Nodes)
                    {
                        if (item.Tag.ToString().StartsWith(COLLECTION_LIST_TAG))
                        {
                            item.Nodes.Add(FillCollectionInfoToTreeNode(collectionName, mongoDB, ConKey + "/" + svrKey));
                        }
                    }
                    rtnResult = true;
                }
            }
            return(rtnResult);
        }
        /// <summary>
        ///     数据库操作
        /// </summary>
        /// <param name="strObjTag"></param>
        /// <param name="dbName"></param>
        /// <param name="func"></param>
        /// <param name="tr"></param>
        /// <returns></returns>
        public static String DataBaseOpration(String strObjTag, String dbName, Oprcode func, TreeNode tr)
        {
            String      rtnResult  = String.Empty;
            MongoServer mongoSvr   = GetMongoServerBySvrPath(strObjTag);
            String      strSvrPath = SystemManager.GetTagData(strObjTag);
            String      svrKey     = strSvrPath.Split("/".ToCharArray())[(int)PathLv.InstanceLv];
            var         result     = new CommandResult(new BsonDocument());

            if (mongoSvr != null)
            {
                switch (func)
                {
                case Oprcode.Create:
                    if (!mongoSvr.DatabaseExists(dbName))
                    {
                        //从权限上看,clusterAdmin是必须的
                        //但是能够建立数据库,不表示能够看到里面的内容!
                        //dbAdmin可以访问数据库。
                        //clusterAdmin能创建数据库但是不能访问数据库。
                        try
                        {
                            mongoSvr.GetDatabase(dbName);
                            tr.Nodes.Add(UIHelper.FillDataBaseInfoToTreeNode(dbName, mongoSvr, svrKey + "/" + svrKey));
                        }
                        catch (Exception ex)
                        {
                            //如果使用没有dbAdmin权限的clusterAdmin。。。。
                            SystemManager.ExceptionDeal(ex);
                        }
                    }
                    break;

                case Oprcode.Drop:
                    if (mongoSvr.DatabaseExists(dbName))
                    {
                        result = mongoSvr.DropDatabase(dbName);
                        if (tr != null)
                        {
                            tr.TreeView.Nodes.Remove(tr);
                        }
                        if (!result.Response.Contains("err"))
                        {
                            return(String.Empty);
                        }
                        return(result.Response["err"].ToString());
                    }
                    break;

                case Oprcode.Repair:
                    //其实Repair的入口不在这个方法里面
                    CommandHelper.ExecuteMongoDBCommand(CommandHelper.repairDatabase_Command, SystemManager.GetCurrentDataBase());
                    break;

                default:
                    break;
                }
            }
            return(rtnResult);
        }
        /// <summary>
        /// 通过路径获得数据集
        /// </summary>
        /// <param name="strObjTag">[Tag:Connection/Host@Port/DBName/Collection]</param>
        /// <returns></returns>
        public static MongoCollection GetMongoCollectionBySvrPath(String strObjTag)
        {
            MongoCollection rtnMongoCollection = null;
            MongoDatabase   mongoDB            = GetMongoDBBySvrPath(strObjTag);

            if (mongoDB != null)
            {
                String   strSvrPath   = SystemManager.GetTagData(strObjTag);
                String[] strPathArray = strSvrPath.Split("/".ToCharArray());
                rtnMongoCollection = mongoDB.GetCollection(strPathArray[(int)PathLv.CollectionLV]);
            }
            return(rtnMongoCollection);
        }
        /// <summary>
        /// 根据路径字符获得数据库
        /// </summary>
        /// <param name="strObjTag">[Tag:Connection/Host@Port/DBName/Collection]</param>
        /// <returns></returns>
        public static MongoDatabase GetMongoDBBySvrPath(String strObjTag)
        {
            MongoDatabase rtnMongoDB = null;
            MongoServer   mongoSvr   = GetMongoServerBySvrPath(strObjTag);

            if (mongoSvr != null)
            {
                String   strSvrPath   = SystemManager.GetTagData(strObjTag);
                String[] strPathArray = strSvrPath.Split("/".ToCharArray());
                if (strPathArray.Length > 1)
                {
                    rtnMongoDB = mongoSvr.GetDatabase(strPathArray[(int)PathLv.DatabaseLV]);
                }
            }
            return(rtnMongoDB);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static String GetCollectionzTreeJSON()
        {
            //获得数据
            WebDataViewInfo.LimitCnt = 100;
            List <BsonDocument> dataList   = GetDataList(ref WebDataViewInfo);
            String          collectionName = SystemManager.GetTagData(WebDataViewInfo.strDBTag).Split("/".ToCharArray())[(int)MongoDBHelper.PathLv.CollectionLV];
            int             SkipCnt        = WebDataViewInfo.SkipCnt;
            TreeViewColumns tree           = new TreeViewColumns();

            FillDataToTreeView(collectionName, tree, dataList, WebDataViewInfo.SkipCnt);
            BsonArray array = new BsonArray();

            foreach (TreeNode item in tree.TreeView.Nodes)
            {
                array.Add(ConvertTreeNodeTozTreeBsonDoc(item));
            }
            return(array.ToJson(SystemManager.JsonWriterSettings));;
        }
        /// <summary>
        /// 数据库操作
        /// </summary>
        /// <param name="strObjTag"></param>
        /// <param name="dbName"></param>
        /// <param name="func"></param>
        /// <param name="tr"></param>
        /// <returns></returns>
        public static Boolean DataBaseOpration(String strObjTag, String dbName, Oprcode func, TreeNode tr)
        {
            Boolean     rtnResult  = false;
            MongoServer mongoSvr   = GetMongoServerBySvrPath(strObjTag);
            String      strSvrPath = SystemManager.GetTagData(strObjTag);
            String      svrKey     = strSvrPath.Split("/".ToCharArray())[(int)PathLv.ServerLV];

            if (mongoSvr != null)
            {
                switch (func)
                {
                case Oprcode.Create:
                    if (!mongoSvr.DatabaseExists(dbName))
                    {
                        mongoSvr.GetDatabase(dbName);
                        tr.Nodes.Add(FillDataBaseInfoToTreeNode(dbName, mongoSvr, svrKey + "/" + svrKey));
                        rtnResult = true;
                    }
                    break;

                case Oprcode.Drop:
                    if (mongoSvr.DatabaseExists(dbName))
                    {
                        mongoSvr.DropDatabase(dbName);
                        if (tr != null)
                        {
                            tr.TreeView.Nodes.Remove(tr);
                        }
                        rtnResult = true;
                    }
                    break;

                case Oprcode.Repair:
                    //How To Compress?Run Command??
                    break;

                default:
                    break;
                }
            }
            return(rtnResult);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static void ImportAccessDataBase(Object obj)
        {
            ImportAccessPara parm     = (ImportAccessPara)obj;
            MongoServer      mongoSvr = GetMongoServerBySvrPath(parm.strSvrPathWithTag);

            String[]        fileName     = parm.accessFileName.Split(@"\".ToCharArray());
            String          fileMain     = fileName[fileName.Length - 1];
            String          insertDBName = fileMain.Split(".".ToCharArray())[0];
            MongoDatabase   mongoDB      = mongoSvr.GetDatabase(insertDBName);
            OleDbConnection conn         = new OleDbConnection(ACCESS_CONNECTION_STRING.Replace("@AccessPath", parm.accessFileName));

            try
            {
                conn.Open();
                int       err                = 0;
                DataTable tblTableList       = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                String    strCreateTableInfo = String.Empty;
                foreach (DataRow recTable in tblTableList.Rows)
                {
                    String strTableName = recTable[2].ToString();
                    try
                    {
                        //不支持UTF....,执行会失败,但是Collection已经添加了
                        String ErrMsg;
                        mongoDB.IsCollectionNameValid(strTableName, out ErrMsg);
                        if (ErrMsg != null)
                        {
                            strCreateTableInfo = strTableName + " Create Error " + System.Environment.NewLine + strCreateTableInfo;
                            OnActionDone(new ActionDoneEventArgs(strTableName + " IsCollectionNameValid Error "));
                            err++;
                            continue;
                        }
                        mongoDB.CreateCollection(strTableName);
                        strCreateTableInfo = strTableName + " Creating " + System.Environment.NewLine + strCreateTableInfo;
                        OnActionDone(new ActionDoneEventArgs(strTableName + " Creating "));
                    }
                    catch (Exception)
                    {
                        if (mongoDB.CollectionExists(strTableName))
                        {
                            mongoDB.DropCollection(strTableName);
                        }
                        strCreateTableInfo = strTableName + " Create Error " + System.Environment.NewLine + strCreateTableInfo;
                        OnActionDone(new ActionDoneEventArgs(strTableName + " Creating Error "));
                        err++;
                        continue;
                    }
                    MongoCollection             mongoCollection = mongoDB.GetCollection(strTableName);
                    DataTable                   tblSchema       = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, strTableName, null });
                    Dictionary <String, String> colPro          = new Dictionary <String, String>();
                    List <String>               colName         = new List <String>();
                    foreach (DataRow item in tblSchema.Rows)
                    {
                        long columnWidth;
                        switch ((long)item["COLUMN_FLAGS"])
                        {
                        case 122:
                            columnWidth = -1;
                            break;

                        case 90:
                            //AutoNumber
                            columnWidth = -2;
                            break;

                        default:
                            if (item["CHARACTER_MAXIMUM_LENGTH"] is DBNull)
                            {
                                columnWidth = -3;
                            }
                            else
                            {
                                columnWidth = (long)item["CHARACTER_MAXIMUM_LENGTH"];
                            }
                            break;
                        }
                        colName.Add(item["COLUMN_NAME"].ToString());
                        colPro.Add(item["COLUMN_NAME"].ToString(), GetDataType((int)item["DATA_TYPE"], columnWidth,
                                                                               item["NUMERIC_PRECISION"] is DBNull ? 0 : (int)item["NUMERIC_PRECISION"],
                                                                               item["NUMERIC_SCALE"] is DBNull ? 0 : (int)item["NUMERIC_SCALE"]));
                    }
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.Connection  = conn;
                    cmd.CommandText = "Select * from " + strTableName;
                    OleDbDataAdapter adapter = new OleDbDataAdapter();
                    DataSet          dateSet = new DataSet();
                    adapter.SelectCommand = cmd;
                    adapter.Fill(dateSet, strTableName);
                    DataTable tblAccessData = dateSet.Tables[0];
                    foreach (DataRow itemRow in tblAccessData.Rows)
                    {
                        BsonDocument insertDoc = new BsonDocument();
                        for (int i = 0; i < colName.Count; i++)
                        {
                            if (!(itemRow[colName[i]] is DBNull))
                            {
                                switch (colPro[colName[i]])
                                {
                                case "VARCHAR":
                                    insertDoc.Add(colName[i], new BsonString(itemRow[colName[i]].ToString()), true);
                                    break;

                                case "BIT":
                                    //System.Boolean Can't Cast To BSonBoolean....
                                    //O,My LadyGaga
                                    if ((bool)itemRow[colName[i]])
                                    {
                                        insertDoc.Add(colName[i], BsonBoolean.True, true);
                                    }
                                    else
                                    {
                                        insertDoc.Add(colName[i], BsonBoolean.False, true);
                                    }
                                    break;

                                case "DATETIME":
                                    //O,My LadyGaga
                                    insertDoc.Add(colName[i], new BsonDateTime((DateTime)itemRow[colName[i]]), true);
                                    break;

                                case "Integer":
                                    Int32 i32 = Convert.ToInt32(itemRow[colName[i]]);
                                    insertDoc.Add(colName[i], (BsonInt32)i32, true);
                                    break;

                                case "Long":
                                    //itemRow[ColName[i]] the default is Int32 without convert
                                    long lng = Convert.ToInt64(itemRow[colName[i]]);
                                    insertDoc.Add(colName[i], (BsonInt64)lng, true);
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        mongoCollection.Insert <BsonDocument>(insertDoc);
                    }
                }
                String strSvrPath = SystemManager.GetTagData(parm.strSvrPathWithTag);
                String strKey     = strSvrPath.Split("/".ToCharArray())[(int)MongoDBHelper.PathLv.ConnectionLV] + "/" +
                                    strSvrPath.Split("/".ToCharArray())[(int)MongoDBHelper.PathLv.ServerLV];
                parm.currentTreeNode.Nodes.Add(FillDataBaseInfoToTreeNode(insertDBName, mongoSvr, strKey));
                MyMessageBox.ShowMessage("Import Message", (tblTableList.Rows.Count - err).ToString() + "Created   " + err + "failed", strCreateTableInfo, true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="SubNode"></param>
        /// <returns></returns>
        private static BsonDocument ConvertTreeNodeTozTreeBsonDoc(TreeNode SubNode)
        {
            BsonDocument SingleNode = new BsonDocument();

            SingleNode.Add("name", SubNode.Text + GetTagText(SubNode));
            if (SubNode.Nodes.Count == 0)
            {
                SingleNode.Add("icon", "MainTreeImage" + String.Format("{0:00}", SubNode.ImageIndex) + ".png");
            }
            else
            {
                BsonArray ChildrenList = new BsonArray();
                foreach (TreeNode item in SubNode.Nodes)
                {
                    ChildrenList.Add(ConvertTreeNodeTozTreeBsonDoc(item));
                }
                SingleNode.Add("children", ChildrenList);
                SingleNode.Add("icon", "MainTreeImage" + String.Format("{0:00}", SubNode.ImageIndex) + ".png");
            }
            if (SubNode.IsExpanded)
            {
                SingleNode.Add("open", "true");
            }
            if (SubNode.Tag != null)
            {
                SingleNode.Add("click", "ShowData('" + SystemManager.GetTagType(SubNode.Tag.ToString()) + "','" + SystemManager.GetTagData(SubNode.Tag.ToString()) + "')");
            }
            return(SingleNode);
        }