예제 #1
0
        public DbContext CreateDbContex <TDbContext>(string connectionString, IIocResolve iocResolve) where TDbContext : DbContext
        {
            DbContext dbContext;

            ActiveTransactionInfo activeTransaction;

            activeTransaction = ActiveTransations.TryGetValue(connectionString, out activeTransaction)
                ? activeTransaction
                : default(ActiveTransactionInfo);
            if (activeTransaction == null)//没找到则ioc通过NamedParameter创建一个
            {
                dbContext = iocResolve.ResolveParameter <TDbContext>(new NamedParameter("nameOrConnectionString",
                                                                                        connectionString));
                var dbTransaction = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                activeTransaction = new ActiveTransactionInfo(dbTransaction, dbContext);
                ActiveTransations[connectionString] = activeTransaction;
            }
            else//找到了则通过ioc把DbConnection作为参数创建一个DbContext
            {
                dbContext = iocResolve.ResolveParameter <TDbContext>(new Parameter[] {
                    new NamedParameter("existingConnection", activeTransaction.DbContextTransaction.UnderlyingTransaction.Connection),
                    new NamedParameter("contextOwnsConnection", false)
                });                                                     //通过connection参数resolve一个dbcontext对象

                //dbContext = iocResolve.ResolveParameter<TDbContext>(new TypedParameter(typeof(DbConnection),
                //activeTransaction.DbContextTransaction.UnderlyingTransaction.Connection));
                dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.UnderlyingTransaction);
                activeTransaction.AttendedDbContexts.Add(dbContext);
            }
            DbContexts.Add(dbContext);
            return(dbContext);
        }
예제 #2
0
        public RemoveBooksDialog(params Account[] accounts)
        {
            _libraryBooks = DbContexts.GetLibrary_Flat_NoTracking();
            _accounts     = accounts;

            InitializeComponent();

            this.Load        += (_, _) => this.RestoreSizeAndLocation(Configuration.Instance);
            this.FormClosing += (_, _) => this.SaveSizeAndLocation(Configuration.Instance);

            _labelFormat = label1.Text;

            _dataGridView.CellContentClick      += (_, _) => _dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
            _dataGridView.CellValueChanged      += (_, _) => UpdateSelection();
            _dataGridView.BindingContextChanged += _dataGridView_BindingContextChanged;

            var orderedGridEntries = _libraryBooks
                                     .Select(lb => new RemovableGridEntry(lb))
                                     .OrderByDescending(ge => (DateTime)ge.GetMemberValue(nameof(ge.PurchaseDate)))
                                     .ToList();

            _removableGridEntries             = new SortableBindingList <RemovableGridEntry>(orderedGridEntries);
            gridEntryBindingSource.DataSource = _removableGridEntries;

            _dataGridView.Enabled = false;
        }
예제 #3
0
        /// <summary>
        ///     Dispose
        /// </summary>
        /// <param name="iocResolve"></param>
        public virtual void Dispose(IIocResolve iocResolve)
        {
            foreach (var activeTransaction in ActiveTransations.Values)
            {
                foreach (var attendedDbContext in activeTransaction.AttendedDbContexts)
                {
                    iocResolve.Release(attendedDbContext);
                }
                activeTransaction.DbContextTransaction.Dispose();
                iocResolve.Release(activeTransaction.StartDbContext);
            }

            //清除事务
            ActiveTransations.Clear();

            foreach (var dbContext in DbContexts)
            {
                iocResolve.Release(dbContext);
            }
            //清除DbContexts
            DbContexts.Clear();

            if (CurrentTransaction == null)
            {
                return;
            }
            CurrentTransaction.Dispose();
            CurrentTransaction = null;
        }
예제 #4
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            if (!_nested)
            {
                if (!_completed)
                {
                    SaveChanges();
                }

                DbContexts.Dispose();
            }

            RemoveAmbientScope();

            if (_parentScope != null)
            {
                if (!_parentScope._disposed)
                {
                    SetAmbientScope(_parentScope);
                }
            }

            _disposed = true;
        }
예제 #5
0
 /// <summary>
 /// 保存数据
 /// </summary>
 public void SaveImportData(IEnumerable <Spl_Person> personList)
 {
     try
     {
         DbContexts db = new DbContexts();
         foreach (var model in personList)
         {
             Spl_Person entity = new Spl_Person();
             entity.KEY_Id     = ResultHelper.NewId;
             entity.Name       = model.Name;
             entity.Sex        = model.Sex;
             entity.Age        = model.Age;
             entity.IDCard     = model.IDCard;
             entity.Phone      = model.Phone;
             entity.Email      = model.Email;
             entity.Address    = model.Address;
             entity.CreateTime = ResultHelper.NowTime.ToString("yyyy-MM-dd HH:mm:ss");
             entity.Region     = model.Region;
             entity.Category   = model.Category;
             db.Spl_Person.Add(entity);
         }
         db.SaveChanges();
     }
     catch (Exception ex)
     {
         throw;
     }
 }
        public virtual DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver)
            where TDbContext : DbContext
        {
            var dbContext = dbContextResolver.Resolve <TDbContext>(connectionString);

            DbContexts.Add(dbContext);
            return(dbContext);
        }
예제 #7
0
        //保存头像
        public int bao(DTO.UserInfoDto du)
        {
            var ui = DbContexts.UserInfo.Find(du.Id);

            ui.UserHeadPortrait = du.UserHeadPortrait;

            return(DbContexts.SaveChanges());
        }
        /// <summary>
        /// 我的微博删除微博
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Remove(int id)
        {
            var RemoveMymicrobolg = DbContexts.MicroBlog.Find(id);

            DbContexts.MicroBlog.Remove(RemoveMymicrobolg);

            return(DbContexts.SaveChanges());
        }
예제 #9
0
 public IGenericEFRepository <TEntity> Repository <TContext, TEntity>()
     where TContext : DbContext
     where TEntity : class
 {
     return((IGenericEFRepository <TEntity>)_repositories.GetOrAdd(
                typeof(TEntity),
                t => _repositoryFactory.Get <TEntity>(DbContexts.Get <TContext>())
                ));
 }
예제 #10
0
        public static LibraryBook GetSingleLibraryBook(string productId)
        {
            using var context = DbContexts.GetContext();
            var libraryBook = context
                              .Library
                              .GetLibrary()
                              .SingleOrDefault(lb => lb.Book.AudibleProductId == productId);

            return(libraryBook);
        }
예제 #11
0
파일: Form1.cs 프로젝트: tanitall/Libation
        private void setBackupCounts(object _, object __)
        {
            var books = DbContexts.GetContext()
                        .GetLibrary_Flat_NoTracking()
                        .Select(sp => sp.Book)
                        .ToList();

            setBookBackupCounts(books);
            setPdfBackupCounts(books);
        }
 public ClientService(UserManager <CustomIdentityUser> usermanager, IEMailService mailService, ICartRepo CartService,
                      IConfiguration configurations, IHttpContextAccessor httpContextAccessor, IMapper mapper, DbContexts dbContexts)
 {
     _UserManager    = usermanager;
     _CartRepo       = CartService;
     _Configurations = configurations;
     _mailService    = mailService;
     _mapper         = mapper;
     _DbContext      = dbContexts;
 }
예제 #13
0
        /// <summary>
        /// 找回密码方法
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public int ForgetThePwd(DTO.UserInfoDto Uidto)
        {
            //根据邮箱修改密码
            var ForgetThePwdEntity = DbContexts.UserInfo.Where(p => p.UserEmail == Uidto.UserEmail).First();

            ForgetThePwdEntity.UserPassword = Uidto.UserPassword;
            int i = DbContexts.SaveChanges();

            return(i);
        }
예제 #14
0
        protected static async Task RunAsync(Processable Processable)
        {
            foreach (var libraryBook in Processable.GetValidLibraryBooks(DbContexts.GetLibrary_Flat_NoTracking()))
            {
                await ProcessOneAsync(Processable, libraryBook, false);
            }

            var done = "Done. All books have been processed";

            Console.WriteLine(done);
            Serilog.Log.Logger.Information(done);
        }
예제 #15
0
        //保存资料
        public int update(DTO.UserInfoDto du)
        {
            var ui = DbContexts.UserInfo.Find(du.Id);

            ui.UserName      = du.UserName;
            ui.UserEmail     = du.UserEmail;
            ui.UserAutograph = du.UserAutograph;
            ui.UserSex       = du.UserSex;
            ui.UserRegion    = du.UserRegion;
            ui.UserBirthday  = du.UserBirthday;
            return(DbContexts.SaveChanges());
        }
예제 #16
0
        public List <UserView> GetRoleListByUser(string roleId, string depId)
        {
            String sql = "select a.Id,a.UserName,a.TrueName,ISNULL(b.SysUserId, '0') as Flag from SysUser a left join SysRoleSysUser b on cast(a.Id as varchar) = b.SysUserId and b.SysRoleId = @SysRoleId Where  a.DepId =  @DepId order by b.SysUserId desc";

            SqlParameter[] sqlParameters = { new SqlParameter {
                                                 ParameterName = "SysRoleId", Value = roleId
                                             }, new SqlParameter{
                                                 ParameterName = "DepId", Value = depId
                                             } };
            DbContexts     DbContext = new DbContexts();

            return(DbContext.Database.SqlQuery <UserView>(sql, sqlParameters).ToList());
        }
예제 #17
0
        /// <summary>
        /// 注册方法
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public int AddRegister(DTO.UserInfoDto Uidto)
        {
            //return DbContext.UserInfo.Where(whereLambda).AsQueryable();
            Models.UserInfo Userlist = new Models.UserInfo()
            {
                UserName     = Uidto.UserName,
                UserEmail    = Uidto.UserEmail,
                UserPassword = Uidto.UserPassword
            };
            DbContexts.UserInfo.Add(Userlist);
            int i = DbContexts.SaveChanges();

            return(i);
        }
예제 #18
0
        private static LibraryBook getNextValidBook(this IProcessable processable)
        {
            var libraryBooks = DbContexts.GetContext().GetLibrary_Flat_NoTracking();

            foreach (var libraryBook in libraryBooks)
            {
                if (processable.Validate(libraryBook))
                {
                    return(libraryBook);
                }
            }

            return(null);
        }
예제 #19
0
 public override void Commit()
 {
     DbContexts.ForEach(dtx =>
     {
         var CurrentTransaction = dataBaseTransactions.FirstOrDefault(t => t.dbContext == dtx);
         if (CurrentTransaction != null)
         {
             CurrentTransaction.Transaction.Commit();
             CurrentTransaction.isCommit = true;
             CurrentTransaction.Transaction.Dispose();
         }
     }
                        );
 }
예제 #20
0
 /// <summary>
 /// 发布微博
 /// </summary>
 /// <param name="Uid"></param>
 /// <param name="Mbd"></param>
 /// <returns></returns>
 public int PublishWeibo(DTO.UserInfoDto Uid, DTO.MicroBlogsDto Mbd)
 {
     Models.MicroBlog Mb = new Models.MicroBlog()
     {
         UserID        = Uid.Id,
         Title         = Mbd.Title,
         Content_text  = Mbd.Content_text,
         Content_img   = Mbd.Content_img,
         Points_number = 0,
         Place         = Mbd.Place,
         Cansee_states = 0
     };
     DbContexts.MicroBlog.Add(Mb);
     return(DbContexts.SaveChanges());
 }
        public virtual void Dispose(IIocResolver iocResolver)
        {
            foreach (var dbContext in DbContexts)
            {
                iocResolver.Release(dbContext);
            }

            DbContexts.Clear();

            if (CurrentTransaction != null)
            {
                CurrentTransaction.Dispose();
                CurrentTransaction = null;
            }
        }
예제 #22
0
        public void Display()
        {
            if (hasBeenDisplayed)
            {
                return;
            }
            hasBeenDisplayed = true;

            //
            // transform into sorted GridEntry.s BEFORE binding
            //
            context = DbContexts.GetContext();
            var lib = context.GetLibrary_Flat_WithTracking();

            // if no data. hide all columns. return
            if (!lib.Any())
            {
                for (var i = dataGridView.ColumnCount - 1; i >= 0; i--)
                {
                    dataGridView.Columns.RemoveAt(i);
                }
                return;
            }

            var orderedGridEntries = lib
                                     .Select(lb => new GridEntry(lb)).ToList()
                                     // default load order
                                     .OrderByDescending(ge => ge.Purchase_Date)
                                     //// more advanced example: sort by author, then series, then title
                                     //.OrderBy(ge => ge.Authors)
                                     //    .ThenBy(ge => ge.Series)
                                     //    .ThenBy(ge => ge.Title)
                                     .ToList();

            //
            // BIND
            //
            gridEntryBindingSource.DataSource = orderedGridEntries.ToSortableBindingList();

            //
            // FILTER
            //
            filter();

            BackupCountsChanged?.Invoke(this, EventArgs.Empty);
        }
예제 #23
0
        /// <summary>
        /// 加入异常日志
        /// </summary>
        /// <param name="ex">异常</param>
        public static void WriteException(Exception ex)
        {
            SysConfigModel siteConfig = new SysConfigBLL().loadConfig(Utils.GetXmlMapPath("Configpath"));

            //后台异常开启
            if (siteConfig.exceptionstatus == 1)
            {
                try
                {
                    using (DbContexts db = new DbContexts())
                    {
                        SysException model = new SysException()
                        {
                            ExceptionId = ResultHelper.NewId,
                            HelpLink    = ex.HelpLink,
                            Message     = ex.Message,
                            Source      = ex.Source,
                            StackTrace  = ex.StackTrace,
                            TargetSite  = ex.TargetSite.ToString(),
                            Data        = ex.Data.ToString(),
                            CreateTime  = ResultHelper.NowTime.ToString()
                        };
                        db.SysException.Add(model);
                        db.SaveChanges();
                    }
                }
                catch (Exception ep)
                {
                    string subFold  = DateTime.Now.Year + DateTime.Now.Month.ToString("D2");
                    string fileName = subFold + DateTime.Now.Day.ToString("D2") + ".txt";
                    string path     = System.Web.HttpContext.Current.Server.MapPath("~/LogFile/") + subFold;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string wholePath = path + "\\" + fileName;
                    using (StreamWriter sw = new StreamWriter(wholePath, true, Encoding.UTF8))
                    {
                        sw.WriteLine((ex.Message + "|" + ex.StackTrace + "|" + ep.Message + "|" + DateTime.Now.ToString()).ToString());
                        sw.Dispose();
                        sw.Close();
                    }
                    return;
                }
            }
        }
 /// <summary>
 /// 删除发送者的全部消息(非物理删除)
 /// </summary>
 /// <param name="sender"></param>
 public void DeleteMessageAllNotBySender(string sender)
 {
     using (DbContexts db = new DbContexts())
     {
         IQueryable <MIS_WebIM_Message> entityList = from r in db.MIS_WebIM_Message
                                                     where r.Sender == sender
                                                     select r;
         if (entityList == null)
         {
             return;
         }
         foreach (var entity in entityList)
         {
             entity.State = "true";
         }
         db.SaveChanges();
     }
 }
예제 #25
0
        public void Display()
        {
            if (hasBeenDisplayed)
            {
                return;
            }
            hasBeenDisplayed = true;

            //
            // transform into sorted GridEntry.s BEFORE binding
            //
            var lib = DbContexts.GetLibrary_Flat_NoTracking();

            // if no data. hide all columns. return
            if (!lib.Any())
            {
                for (var i = _dataGridView.ColumnCount - 1; i >= 0; i--)
                {
                    _dataGridView.Columns.RemoveAt(i);
                }
                return;
            }

            var orderedGridEntries = lib
                                     .Select(lb =>
            {
                var entry        = new GridEntry(lb);
                entry.Committed += (_, __) => Filter();
                return(entry);
            }).ToList()
                                     // default load order
                                     .OrderByDescending(ge => (DateTime)ge.GetMemberValue(nameof(ge.PurchaseDate)))
                                     //// more advanced example: sort by author, then series, then title
                                     //.OrderBy(ge => ge.Authors)
                                     //    .ThenBy(ge => ge.Series)
                                     //    .ThenBy(ge => ge.Title)
                                     .ToList();

            // BIND
            gridEntryBindingSource.DataSource = new SortableBindingList <GridEntry>(orderedGridEntries);

            // FILTER
            Filter();
        }
예제 #26
0
        /// <summary>
        /// 增加点赞数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Points"></param>
        public int Points_number(int id)
        {
            var PreviewBlogEntity = (from mb in DbContexts.MicroBlog where mb.Id == id select new { mb.Points_number });
            int num = 0;

            foreach (var item in PreviewBlogEntity)
            {
                num = item.Points_number;
            }
            num += 1;
            var dd = DbContexts.MicroBlog.Find(id);

            dd.Points_number = num;
            return(DbContexts.SaveChanges());

            //Models.MicroBlog mbs = new Models.MicroBlog() {
            //    Points_number=num
            //};
        }
 /// <summary>
 /// 返回接收者一个消息
 /// </summary>
 /// <param name="receiver"></param>
 /// <param name="id"></param>
 /// <returns></returns>
 public MIS_WebIM_MessageRecModel GetMessageByReceiver(string receiver, string id)
 {
     using (DbContexts db = new DbContexts())
     {
         var model = (from m in db.MIS_WebIM_Message
                      join r in db.MIS_WebIM_Message_Rec on m.Id.ToString() equals r.MessageId
                      where m.Id.ToString() == id
                      where r.receiver == receiver
                      select new MIS_WebIM_MessageRecModel
         {
             Id = m.Id,
             Message = m.Message,
             Sender = m.Sender,
             receiver = r.receiver,
             State = r.State,
             SendDt = m.SendDt,
             RecDt = r.RecDt
         }).SingleOrDefault();
         return(model);
     }
 }
예제 #28
0
 public static string GetJobExecuteTime(string id)
 {
     using (DbContexts db = new DbContexts())
     {
         ////定义trigger名称
         //string triggerName="Trigger_"+id;
         //ObjectResult<P_QRTZ_GetJobExecuteTime_Result> result = db.P_QRTZ_GetJobExecuteTime(triggerName);
         //if (result == null)
         //{
         //    return "";
         //}
         //var tigResult = result.SingleOrDefault();
         //if (tigResult == null)
         //{
         //    return "";
         //}
         long           starttime = tigResult.START_TIME;
         TimeSpan       t         = new TimeSpan(0);
         DateTimeOffset df        = new DateTimeOffset(starttime, t);
         return(df.DateTime.ToLocalTime().ToString());
     }
 }
예제 #29
0
        /// <summary>Process the first valid product. Create default context</summary>
        /// <returns>Returns either the status handler from the process, or null if all books have been processed</returns>
        public static async Task <StatusHandler> ProcessSingleAsync(this IProcessable processable, string productId)
        {
            using var context = DbContexts.GetContext();
            var libraryBook = context
                              .Library
                              .GetLibrary()
                              .SingleOrDefault(lb => lb.Book.AudibleProductId == productId);

            if (libraryBook == null)
            {
                return(null);
            }
            if (!processable.Validate(libraryBook))
            {
                return new StatusHandler {
                           "Validation failed"
                }
            }
            ;

            return(await processBookAsync(processable, libraryBook));
        }
예제 #30
0
        public List <UserView> GetMatchingListByUser(string matchingId, string depId, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                name = string.Empty;
            }
            if (string.IsNullOrEmpty(depId))
            {
                depId = string.Empty;
            }
            //String sql = "select a.Id,a.UserName,a.TrueName,ISNULL(b.OTM, '0') as Flag from SysUser a left join FIX_MatchingModel b on cast(a.Id as varchar) = b.OTM and b.Id = @matchingId Where a.DepId =  @DepId and a.TrueName = '@name' order by b.OTM desc";
            String sql = "select a.Id,a.UserName,a.TrueName,ISNULL(b.OTM, '0') as Flag from SysUser a left join FIX_MatchingModel b on cast(a.Id as varchar) = b.OTM and b.Id = @matchingId Where a.DepId =  @DepId order by b.OTM desc";

            //SqlParameter[] sqlParameters = { new SqlParameter { ParameterName = "matchingId", Value = matchingId }, new SqlParameter { ParameterName = "DepId", Value = depId }, new SqlParameter { ParameterName = "name", Value = name } };
            SqlParameter[] sqlParameters = { new SqlParameter {
                                                 ParameterName = "matchingId", Value = matchingId
                                             }, new SqlParameter{
                                                 ParameterName = "DepId", Value = depId
                                             } };
            DbContexts     DbContext = new DbContexts();

            return(DbContext.Database.SqlQuery <UserView>(sql, sqlParameters).ToList());
        }