最新发布 C#mongodb2.2 数据库操作

发布时间: 2022-12-30,浏览量:392
config中:

 <add name="MongoConnection" connectionString="mongodb://localhost:27017/SupportTicket"/>

引用mongodb2.2

using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using MongoDB.Driver;
 
using MongoDB.Bson;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;
using System.Reflection;
using Winsoft.IM.Admin.Website.Areas.GroupShare.Models;
using System.Security.Cryptography;
using System.Web.Configuration;
using System.Diagnostics;
using System.Linq.Expressions;
 
namespace Winsoft.IM.Admin.Website.Areas.GroupShare.Utilities
{
 
    public abstract class BaseDataProvider<T>
    {
        private string connStr;
 
        static string dbName = "SupportTicket";
 
        string collectionName;
 
        public BaseDataProvider(string collectionName)
        {
            this.collectionName = collectionName;
        }
 
        //public BaseDataProvider()
        //    : this("Files")
        //{
        //}
 
        public string ConnectionString
        {
            get
            {
                if (String.IsNullOrEmpty(connStr))
                {
                    throw new ArgumentNullException("Connection string did not specify!");
                }
                return connStr;
            }
        }
 
        public BaseDataProvider()
        {
            connStr = WebConfigurationManager.ConnectionStrings["MongoConnection"].ConnectionString;
        }
 
 
 
        void OpenCollection(Action<IMongoCollection<T>> action)
        {
            var mongo = new MongoClient(ConnectionString);
            try
            {
                //mongo.Connect();
 
                var database = mongo.GetDatabase(dbName);
 
                var collection = database.GetCollection<T>(collectionName);
 
                action(collection);
 
            }
            catch (Exception ex)
            {
                //log ex
#if DEBUG
                Debug.WriteLine(ex);
#endif
            }
            finally
            {
                //mongo.Disconnect();
            }
        }
 
        void Query(Action<IQueryable<T>> q)
        {
            OpenCollection(e => q(e.AsQueryable()));
        }
 
 
        public virtual IEnumerable<T> Find(Func<T, bool> query)
        {
 
            IEnumerable<T> result = null;
 
            this.Query((e) => result = e.Where(query));
 
            return result;
        }
 
        public virtual T FindOne(Func<T, bool> query)
        {
            T result = default(T);
            this.Query((e) => result = e.FirstOrDefault(query));
            return result;
        }
 
        public virtual void Insert(T doc)
        {
            if (doc == null)
                return;
            this.OpenCollection(e =>
            {
                e.InsertOne(doc);
            });
 
        }
 
        //public virtual void Delete<TValue>(Expression<Func<T, IEnumerable<TValue>>> memberExpression, TValue value)
        //{
        //    this.OpenCollection(e =>
        //    {
        //        var query = Query<T>.EQ(memberExpression, value);
        //        e.DeleteOne(query);
        //    });
        //}
 
 
        public virtual bool Exists(Func<T, bool> query)
        {
            bool result = false;
 
            this.Query((e) => result = e.Any(query));
 
            return result;
        }
 
        public virtual IEnumerable<T> GetPagedList<K>(out int total, int pageindex, int pagesize, Func<T, K> orderby, Func<T, bool> query)
        {
 
            IEnumerable<T> items = null;
 
            int t = 0;
 
            this.Query(e =>
            {
 
                var q = e.Where(query);
 
                t = q.Count();
 
                items = q.OrderByDescending(orderby).Skip((pageindex - 1) * pagesize).Take(pagesize);
 
            });
 
            total = t;
 
            return items;
 
        }
 
 
    }
 
 
    public class DocFileProvider : BaseDataProvider<DocFiles>
    {
        public DocFileProvider()
            : base("DocFiles")
        {
        }
 
    }
 
 
    public class DataProvider
    {
        private string connStr;
 
        static string dbName = "SupportTicket";
 
        static string collectionName = "Files";
 
        public string ConnectionString
        {
            get
            {
                if (String.IsNullOrEmpty(connStr))
                {
                    throw new ArgumentNullException("Connection string did not specify!");
                }
                return connStr;
            }
        }
 
        public DataProvider()
        {
            connStr = WebConfigurationManager.ConnectionStrings["MongoConnection"].ConnectionString;
        }
 
        public DataProvider(string connectionString)
        {
            this.connStr = connectionString;
        }
 
        MongoClient GetMongoServer()
        {
            return new MongoClient(ConnectionString);
        }
 
 
        void OpenCollection(Action<IMongoCollection<DocFiles>> action)
        {
            var mongo = GetMongoServer();
 
            try
            {
 
 
                var database = mongo.GetDatabase(dbName);
 
                var collection = database.GetCollection<DocFiles>(collectionName);
 
                action(collection);
 
            }
            catch (Exception ex)
            {
                //log ex
#if DEBUG
                Debug.WriteLine(ex);
#endif
            }
            finally
            {
                //mongo.Disconnect();
            }
        }
 
        void Query(Action<IQueryable<DocFiles>> q)
        {
            OpenCollection(e => q(e.AsQueryable()));
        }
 
 
        public List<DocFiles> Find(Func<DocFiles, bool> query)
        {
 
            List<DocFiles> result = null;
 
            this.Query((e) => result = e.Where(query).ToList());
 
            return result;
        }
 
        public DocFiles FindOne(Func<DocFiles, bool> query)
        {
            DocFiles result = null;
 
            this.Query((e) => result = e.FirstOrDefault(query));
 
            return result;
        }
 
        public void Insert(DocFiles doc)
        {
            if (doc == null)
                return;
            this.OpenCollection(e =>
            {
                e.InsertOne(doc);
            });
        }
        public void UpdateTimes(string id)
        {
            this.OpenCollection(e =>
            {
                var doc = FindOne(t => t.FileID == id);
                var query = Builders<DocFiles>.Filter.Eq(f => f.FileID, id);
                var update = Builders<DocFiles>.Update.Set("DownTimes", doc.DownTimes + 1);
                e.UpdateOne(query, update);
            });
        }
 
 
        public long GetTotalLength(Func<DocFiles, bool> query, Func<DocFiles, decimal> selector)
        {
 
            decimal result = 0;
 
            this.Query((e) => result = e.Where(query).Sum(selector));
 
            return (long)(result);
        }
 
 
        public void Delete(string id)
        {
            this.OpenCollection(e =>
            {
                ObjectId oid;
                if (ObjectId.TryParse(id, out oid))
                {
                    var query = Builders<DocFiles>.Filter.Eq(f => f._id, oid);
                    e.DeleteOne(query);
                }
            });
        }
 
 
        public bool Exists(Func<DocFiles, bool> query)
        {
            bool result = false;
 
            this.Query((e) => result = e.Any(query));
 
            return result;
 
        }
 
        public List<DocFiles> GetPagedList(out int total, int pageindex, int pagesize, Func<DocFiles, bool> query)
        {
 
            List<DocFiles> items = null;
 
            int t = 0;
 
            this.Query(e =>
            {
 
                var q = e.Where(query);
 
                t = q.Count();
 
                items = q.OrderByDescending(f => f.CreateDate).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
 
            });
 
            total = t;
 
            return items;
 
        }
 
 
 
        #region gridfs
 
        /// <summary>
        /// 保存文件返回ID
        /// </summary>
        /// <param name=”tag”>Tag(用于在GridFS中显示的文件类别,如:banner,logo,test,便于清理)</param>
        /// <param name=”byteFile”>byte[]</param>
        /// <param name=”sourcename”>原文件名</param>
        /// <returns>返回文件编号(ObjectId)</returns>
        public string GridFsSave(string tag, byte[] byteFile, string sourceName)
        {
 
            var client = new MongoClient(ConnectionString);
            IMongoDatabase database = client.GetDatabase(dbName);
 
            var bucket = new GridFSBucket(database);
 
            var options = new GridFSUploadOptions
            {
 
                ChunkSizeBytes = 262144, // 63KB
 
                Metadata = new BsonDocument
                {
                    { "ContentType", tag },
                    {"UploadDate",DateTime.Now.ToUniversalTime()}
                }
            };
            var id = bucket.UploadFromBytes(sourceName, byteFile, options);
 
            return id.ToString();
 
        }
 
        //  获取文件
        /// <summary>
        /// 根据Id读取文件
        /// </summary>
        /// <param name=”sourcename”>返回原文件名</param>
        /// <param name=”fileId”>文件编号(ObjectId)</param>
        /// <returns></returns>
        public byte[] GridFsRead(out string sourcename, string fileId)
        {
            var client = new MongoClient(ConnectionString);
            IMongoDatabase database = client.GetDatabase(dbName);
 
            var bucket = new GridFSBucket(database);
 
            var id = ObjectId.Parse(fileId);
            sourcename = "";
            //var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Id, id);
            //var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);           
 
            //using (var cursor = bucket.Find(filter))
            //{
            //    var fileInfo = cursor.ToList().FirstOrDefault();
            //    sourcename = fileInfo.Filename;
 
            //    // fileInfo either has the matching file information or is null
            //}
            var bytes = bucket.DownloadAsBytes(ObjectId.Parse(fileId));
            return bytes;
 
        }
 
        /// <summary>
        /// 根据Id删除文件
        /// </summary>
        /// <param name=”fileId”>文件编号(ObjectId)</param>
        public void GridFsDelete(string fileId)
        {
            var client = new MongoClient(ConnectionString);
            IMongoDatabase database = client.GetDatabase(dbName);
 
            var bucket = new GridFSBucket(database);
            bucket.Delete(fileId);
        }
 
        public byte[] StreamToBytes(Stream stream)
        {
 
 
            byte[] bytes = new byte[stream.Length];
 
            stream.Read(bytes, 0, bytes.Length);
 
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
 
            return bytes;
        }
        public void DownLoad(string fileid, string filename)
        {
            string fname = "";
 
            byte[] b = GridFsRead(out fname, fileid);
 
            StreamDownLoad(b, filename);
        }
 
        public void StreamDownLoad(byte[] b, string filename)
        {
            string fileName = filename;//客户端保存的文件名           
            //以字符流的形式下载文件
            byte[] bytes = b;
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
            //string fileName = "";//客户端保存的文件名
            //string filePath = Server.MapPath("DownLoad/aaa.txt");//路径
            ////以字符流的形式下载文件
            //FileStream fs = new FileStream(filePath, FileMode.Open);
            //byte[] bytes = new byte[(int)fs.Length];
            //fs.Read(bytes, 0, bytes.Length);
            //fs.Close();
            //Response.ContentType = "application/octet-stream";
            ////通知浏览器下载文件而不是打开
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            //Response.BinaryWrite(bytes);
            //Response.Flush();
            //Response.End();
        }
 
        public void FileDownload(string FullFileName)
        {
            FileInfo DownloadFile = new FileInfo(FullFileName);
            HttpResponseBase Response = null;
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
            Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            Response.WriteFile(DownloadFile.FullName);
            Response.Flush();
            Response.End();
        }
        public string GetMd5(Stream stream)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
 
            byte[] bytesHash = md5.ComputeHash(stream);
 
            md5.Clear();
 
            string sTemp = "";
 
            for (int i = 0; i < bytesHash.Length; i++)
            {
                sTemp += bytesHash[i].ToString("X").PadLeft(2, '0');
            }
            return sTemp.ToLower();
        }
 
 
        #endregion
    }
}

热门文章 经典语录

热门文章 热门文章

查看更多