/// <summary>
        /// Updates the station's assigned bitmap ID and version
        /// </summary>
        /// <param name="newBitmapId"></param>
        /// <param name="logo"></param>
        /// <returns></returns>
        public async Task <int> UpdateChannelBitmap(int newBitmapId, Image logo)
        {
            int retVal = 0;

            using (var connection = await DapperFactory.GetOpenConnectionAsync())
                using (var trans = connection.BeginTransaction())
                {
                    try
                    {
                        retVal += await updateBitmapDTO(connection, trans, newBitmapId, logo);

                        retVal += await updateBitmapVersionDTO(connection, trans, newBitmapId, logo);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                    trans.Commit();
                }

            return(retVal);
        }
Example #2
0
        public async Task <List <ColumnDto> > GetParentsAsync(long parentId)
        {
            using (var dapper = DapperFactory.Create())
            {
                var list = new List <Column>();
                async Task GetWhithParentAsync(long pid)
                {
                    var model = await dapper.QueryOneAsync <Column>(new { Id = pid });

                    if (model != null)
                    {
                        if (model.ParentId.HasValue)
                        {
                            await GetWhithParentAsync(model.ParentId.Value);
                        }
                        list.Add(model);
                    }
                }

                await GetWhithParentAsync(parentId);

                return(Mapper.Map <List <ColumnDto> >(list));
            }
        }
Example #3
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(ColumnDto dto)
        {
            Column model = Mapper.Map <Column>(dto);

            if (model.Id == 0)
            {
                //新增
                model.Id         = ID.NewID();
                model.CreateTime = DateTime.Now;
                model.IsDeleted  = false;
                model.Tags       = "|" + string.Join("|", model.Tags.SplitRemoveEmpty(',')) + "|";
                using (var dapper = DapperFactory.Create())
                {
                    await dapper.InsertAsync(model);
                }
            }
            else
            {
                //更新
                using (var dapper = DapperFactory.Create())
                {
                    var item = new
                    {
                        model.Name,
                        model.Title,
                        model.OrderIndex,
                        model.Tag,
                        Tags = "|" + string.Join("|", model.Tags.SplitRemoveEmpty(',')) + "|"
                    };
                    await dapper.UpdateAsync <Column>(item, new { model.Id });
                }
            }

            //清除缓存
            await _cache.RemoveAsync(CacheKeyDefinition.ContentColumnList);
        }
Example #4
0
        /// <summary>
        /// 绑定(第三方登录)
        /// </summary>
        public async Task OAuthBindAsync(long userId, EmUserLoginType type, string openId)
        {
            if (openId.IsNullOrEmpty())
            {
                throw new KuArgNullException("OpenId不能为空!");
            }

            using (var _dapper = DapperFactory.Create())
            {
                switch (type)
                {
                case EmUserLoginType.QQ:
                    await _dapper.UpdateAsync <User>(new { QQOpenId = openId }, new { Id = userId });

                    break;

                case EmUserLoginType.Weixin:
                    break;

                default:
                    break;
                }
            }
        }
 /// <summary>
 /// 添加操作
 /// </summary>
 /// <param name="stuinfo"></param>
 /// <returns></returns>
 public ActionResult AddStuinfo(Stuinfo stuinfo)
 {
     if (ModelState.IsValid)
     {
         string sql = "insert into Stuinfo(Name,Sex,Age,Email,CId,AddTime) VALUES(:Name,:Sex,:Age,:Email,:CId,:AddTime)";
         using (OracleConnection conn = DapperFactory.CrateOracleConnection())
         {
             stuinfo.AddTime = DateTime.Now;
             if (conn.Execute(sql, stuinfo) > 0)
             {
                 return(RedirectToAction("Index"));
             }
             else
             {
                 ViewBag.Msg = "添加失败!";
                 return(View(stuinfo));
             }
         }
     }
     else
     {
         return(HttpNotFound());
     }
 }
Example #6
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(WxQrcodeDto dto)
        {
            WxQrcode model = Mapper.Map <WxQrcode>(dto);

            if (model.Id == 0)
            {
                //新增
                model.Id         = ID.NewID();
                model.CreateTime = DateTime.Now;
                model.IsDeleted  = false;

                //取得新场景值
                using (var dapper = DapperFactory.Create())
                {
                    var count = await dapper.QueryCountAsync <WxQrcode>(new { model.AccountId, model.PeriodType });

                    if (model.PeriodType == EmWxPeriodType.Temp)
                    {
                        model.SceneId = 100000 + count + 1;
                    }
                    else
                    {
                        model.SceneId = count + 1;
                    }

                    //取得微信AccessToken
                    var token = await _wxAccountService.GetAccessToken(model.AccountId);

                    //远程创建
                    if (model.PeriodType == EmWxPeriodType.Temp)
                    {
                        var rsp = await _wcQrcodeTool.CreateTemp(token, model.SceneId, model.ExpireSeconds);

                        if (rsp.ErrCode != 0)
                        {
                            throw new KuArgNullException(rsp.ToString());
                        }
                        model.Url           = rsp.Data.Url;
                        model.Ticket        = rsp.Data.Ticket;
                        model.ExpireSeconds = model.ExpireSeconds;
                    }
                    else
                    {
                        var rsp = await _wcQrcodeTool.Create(token, model.SceneId);

                        if (rsp.ErrCode != 0)
                        {
                            throw new KuArgNullException(rsp.ToString());
                        }
                        model.Url    = rsp.Data.Url;
                        model.Ticket = rsp.Data.Ticket;
                    }

                    await dapper.InsertAsync(model);
                }
            }
            else
            {
                //更新
                using (var dapper = DapperFactory.Create())
                {
                    var item = new
                    {
                        //这里进行赋值
                        model.EventKey,
                        model.Purpose
                    };
                    await dapper.UpdateAsync <WxQrcode>(item, new { model.Id });
                }
            }
        }
Example #7
0
        public override async Task Run(IJobExecutionContext context)
        {
            await Console.Out.WriteLineAsync("开始处理短信事务...");

            var count = 0;

            //取得待发送列表
            using (var dapper = DapperFactory.Create())
            {
                var builder = new QueryBuilder().Select <SmsQueue>().Concat <Sms>().Concat <SmsTemplet>().Concat <SmsAccount>()
                              .From <SmsQueue>()
                              .InnerJoin <Sms>().On(new ConditionBuilder().Equal <SmsQueue, Sms>(m => m.SmsId, s => s.Id))
                              .InnerJoin <SmsTemplet>().On(new ConditionBuilder().Equal <Sms, SmsTemplet>(s => s.SmsTempletId, t => t.Id))
                              .InnerJoin <SmsAccount>().On(new ConditionBuilder().Equal <SmsTemplet, SmsAccount>(t => t.SmsAccountId, a => a.Id))
                              .Where(new ConditionBuilder().Equal <SmsQueue>(m => m.Status, EmSmsQueueStatus.WaitSend)
                                     .And().Equal <SmsQueue>(m => m.IsDeleted, false)
                                     .And().Equal <Sms>(s => s.IsDeleted, false)
                                     .And().Equal <SmsTemplet>(t => t.IsDeleted, false)
                                     .And().Equal <SmsAccount>(a => a.IsDeleted, false))
                ;

                var items = await dapper.QueryListAsync <SmsQueue, Sms, SmsTemplet, SmsAccount, SmsQueue>(builder, (m, s, t, a) =>
                {
                    m.Sms        = s;
                    s.SmsTemplet = t;
                    t.SmsAccount = a;
                    return(m);
                }, splitOn : "Id");

                foreach (var item in items)
                {
                    using (var trans = dapper.BeginTrans())
                    {
                        if (item.ExpireTime < DateTime.Now)
                        {
                            //已过期
                            item.Status = EmSmsQueueStatus.Expired;
                            await dapper.UpdateAsync <SmsQueue>(new { item.Status }, new { item.Id });
                        }
                        else
                        {
                            //发送短信
                            var account = item.Sms.SmsTemplet.SmsAccount;
                            var sms     = new SmsObject
                            {
                                Mobile     = item.Sms.Mobile,
                                Signature  = item.Sms.SmsTemplet.Signature,
                                TempletKey = item.Sms.SmsTemplet.TempletKey,
                                Data       = JsonConvert.DeserializeObject <IDictionary <string, string> >(item.Sms.Data),
                                OutId      = item.Id.ToString()
                            };

                            var dict            = JsonConvert.DeserializeObject <IDictionary <string, string> >(account.ParameterConfig);
                            var accessKeyId     = dict["AccessKeyId"];
                            var accessKeySecret = dict["AccessKeySecret"];

                            (bool success, string response)res;
                            switch (account.Type)
                            {
                            case EmSmsAccountType.Aliyun:
                                res = await new AliyunSmsSender(accessKeyId, accessKeySecret).Send(sms);
                                break;

                            default:
                                res = (false, "短信账户功能未实现");
                                break;
                            }

                            item.Response = res.response.Substr(0, 1000);
                            item.Status   = res.success ? EmSmsQueueStatus.Sent : EmSmsQueueStatus.Error;
                            item.SendTime = DateTime.Now;

                            await dapper.UpdateAsync <SmsQueue>(new { item.Status, item.SendTime, item.Response }, new { item.Id });

                            count++;
                        }
                        trans.Commit();
                    }
                }
            }

            await Console.Out.WriteLineAsync($"共发送{count}条短信");

            await Console.Out.WriteLineAsync("结束处理短信事务...");
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(DeliveryTempletDto dto)
        {
            DeliveryTemplet model = Mapper.Map <DeliveryTemplet>(dto);

            if (model.Id == 0)
            {
                //新增
                model.Id            = ID.NewID();
                model.CreateTime    = DateTime.Now;
                model.IsDeleted     = false;
                model.IsSnapshot    = false;
                model.SnapshotCount = 0;
                model.OriginId      = null;
                model.EffectiveTime = DateTime.Now;
                using (var dapper = DapperFactory.Create())
                {
                    await dapper.InsertAsync(model);
                }
            }
            else
            {
                //更新
                using (var dapper = DapperFactory.Create())
                {
                    var item = new
                    {
                        //这里进行赋值
                    };
                    await dapper.UpdateAsync <DeliveryTemplet>(item, new { model.Id });
                }

                //using (var trans = await _repository.BeginTransactionAsync())
                //{
                //    //生成快照
                //    if (item.ChargeMode != model.ChargeMode
                //        || !item.ChargeConfig.Equals(model.ChargeConfig))
                //    {
                //        DeliveryTemplet snapshot = new DeliveryTemplet();
                //        snapshot.Id = ID.NewID();
                //        snapshot.IsDeleted = false;
                //        snapshot.CreateTime = DateTime.Now;
                //        snapshot.Name = item.Name;
                //        snapshot.Description = item.Description;
                //        snapshot.IsEnable = item.IsEnable;
                //        snapshot.ChargeConfig = item.ChargeConfig;
                //        snapshot.ChargeMode = item.ChargeMode;
                //        snapshot.SnapshotCount = item.SnapshotCount;
                //        snapshot.EffectiveTime = item.EffectiveTime;
                //        snapshot.ExpireTime = DateTime.Now;
                //        snapshot.IsSnapshot = true;
                //        snapshot.OriginId = item.OriginId;

                //        await _repository.InsertAsync(snapshot);

                //        item.ChargeMode = model.ChargeMode;
                //        item.ChargeConfig = model.ChargeConfig;
                //        item.EffectiveTime = DateTime.Now;
                //        item.SnapshotCount = item.SnapshotCount + 1;
                //    }
                //    item.Name = model.Name;
                //    item.Description = model.Description;
                //    item.IsEnable = model.IsEnable;

                //    _repository.Update(item);
                //    await _repository.SaveAsync();

                //    trans.Commit();
                //}
            }
        }
Example #9
0
 public CommonService(DatabaseType databaseType = DatabaseType.SqlServer, string connectionName = "DefaultConnection")
 {
     this.dataAccess = DapperFactory.GetDataAccess(databaseType, connectionName);
 }
Example #10
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(WxUserTagDto dto)
        {
            WxUserTag model = Mapper.Map <WxUserTag>(dto);

            if (model.Id == 0)
            {
                //新增
                model.Id         = ID.NewID();
                model.Count      = 0;
                model.CreateTime = DateTime.Now;

                //远程添加

                //取得AccessToken
                var token = await wxAccountService.GetAccessToken(model.AccountId);

                var rsp = await wcUserTool.CreateUserTag(token, model.Name);

                if (rsp.ErrCode != 0)
                {
                    throw new KuDataNotFoundException(rsp.ToString());
                }

                model.TagId = rsp.Data.Tag.Id;

                using (var dapper = DapperFactory.Create())
                {
                    await dapper.InsertAsync(model);
                }
            }
            else
            {
                //更新
                using (var dapper = DapperFactory.Create())
                {
                    var item = await dapper.QueryOneAsync <WxUserTag>(new { model.Id });

                    if (item == null)
                    {
                        throw new KuDataNotFoundException("无法取得微信用户标签数据!");
                    }
                    if (item.Name.Equals(model.Name))
                    {
                        //没有变动
                        return;
                    }
                    //远程更新
                    //取得AccessToken
                    var token = await wxAccountService.GetAccessToken(item.AccountId);

                    var rsp = await wcUserTool.UpdateUserTag(token, item.TagId, model.Name);

                    if (rsp.ErrCode != 0)
                    {
                        throw new KuDataNotFoundException(rsp.ToString());
                    }

                    await dapper.UpdateAsync <WxUserTag>(new { model.Name }, new { model.Id });
                }
            }
        }
Example #11
0
        static void Main(string[] args)
        {
            Dictionary <string, object> dic = new Dictionary <string, object>();
            //sql server
            {
                //Random rand = new Random();
                //using (IDbConnection db = DapperFactory.GetConnection(Enums.MyDbType.SqlServer, "Data Source=localhost;Initial Catalog=test;Integrated Security=True"))
                //{
                //    int effectRows;
                //    string id = rand.Next(1, 2000000000).ToString();
                //    Student stu = new Student { ID = id, NAME = "春夏之交", AGE = 25, TIME = DateTime.Now };
                //    //单个插入
                //    {
                //        effectRows = db.Execute("insert into Student(ID,NAME,TIME) values(@ID,@NAME,@TIME)", stu);
                //    }
                //    //多个插入
                //    {
                //        var stuList = Enumerable.Range(0, 5).Select(i => new Student()
                //        {
                //            ID = rand.Next(1, 2147483647).ToString(),
                //            NAME = "安徽",
                //            AGE = i,
                //            TIME = DateTime.Now
                //        });
                //        var result = db.Execute("insert into Student(ID,NAME,TIME,AGE) values(@ID,@NAME,@TIME,@AGE)", stuList);
                //    }

                //    //字典参数插入
                //    {
                //        dic["ID"] = id + "1";
                //        dic["NAME"] = "陈兆杰" + DateTime.Now.ToString();
                //        dic["TIME"] = DateTime.Now;
                //        dic["AGE"] = 25;
                //        effectRows = db.Execute("insert into Student(ID,NAME,TIME,AGE) values(@ID,@NAME,@TIME,@AGE)", dic);
                //    }

                //    //更新
                //    {
                //        var stu1 = db.QuerySingleOrDefault<Student>("select * from Student where ID=@ID", new Student { ID = id });
                //        stu1.NAME = "陈兆杰";

                //        effectRows = db.Execute("UPDATE Student SET NAME=@NAME WHERE ID =@ID", stu1);
                //    }

                //    //删除
                //    {
                //        dic["ID"] = id;
                //        effectRows = db.Execute("DELETE FROM Student WHERE ID = @ID", dic);
                //    }

                //    //事务
                //    {
                //        db.Open();
                //        var tran = db.BeginTransaction();
                //        try
                //        {
                //            Dictionary<string, object> dicParam = new Dictionary<string, object>();
                //            dicParam["ID"] = Guid.NewGuid().ToString();
                //            dicParam["NAME"] = "陈兆杰";
                //            dicParam["TIME"] = DateTime.Now;
                //            effectRows = db.Execute("insert into Student(ID,NAME,TIME) values(@ID,@NAME,@TIME)", dicParam, tran);

                //            tran.Commit();
                //        }
                //        catch (Exception ex)
                //        {
                //            tran.Rollback();
                //        }
                //    }

                //    //多结果查询(Read表顺序,要与sql语句表的顺序一致,不然会有问题)
                //    {
                //        string sql = @"
                //            select * from Student where ID = @ID;
                //            select * from Course;";
                //        using (var multi = db.QueryMultiple(sql, new { id = "1" }))
                //        {
                //            var orders = multi.Read<Student>().ToList();
                //            var customer = multi.Read<Course>().FirstOrDefault();

                //        }
                //    }

                //    //单个查询
                //    {
                //        //var stu4 = db.QuerySingle<Student>("select * from Student where ID=@ID", new { ID = "1" });//数据超过一条会报错,没有数据会报错
                //        //var stu5 = db.QuerySingleOrDefault<Student>("select * from Student where ID=@ID", new { ID = "1" });//数据超过一条会报错,没有数据是默认为null
                //        //var stu6 = db.QueryFirstOrDefault<Student>("select * from Student where ID=@ID", new { ID = "1" });//没有数据时默认为null
                //        //var stu7 = db.QueryFirst<Student>("select * from Student where ID=@ID", new { ID = "1" });//没有数据会报错

                //    }

                //    //多个查询
                //    {
                //        var list = db.Query<Student>("SELECT * FROM Student").ToList();
                //        list = db.Query<Student>("SELECT * FROM Student where ID in @IDS", new { IDS = new String[] { "1786863176", "1963140912" } }).ToList();
                //    }

                //    //多表查询
                //    {


                //        string sql = @"select s.*,c.ID,c.CourseName from Student s,Course c where s.ID =c.ID and s.ID=@ID";

                //        //方法1:
                //        var list2 = db.Query<Student, Course, StudentDto>(sql, (student, course) =>
                //       {
                //           StudentDto stuDto = new StudentDto();
                //           stuDto.NAME = student.NAME;
                //           stuDto.ID = student.ID;
                //           course.ID = student.ID;
                //           stuDto.Course = course;
                //           return stuDto;

                //       }, new { ID = "1786863176" }, splitOn: "ID,CourseName").ToList();

                //        //方法2:
                //        var dynamic = db.Query(sql, new { ID = "1786863176" }).ToList();

                //    }

                //    //调用存储过程
                //    {
                //        var param = new DynamicParameters();
                //        param.Add("@StuId", "859713145");
                //        param.Add("@Name", dbType: DbType.String, direction: ParameterDirection.Output, size: 50);//输出值需要赋值size
                //        param.Add("@result", dbType: DbType.String, direction: ParameterDirection.ReturnValue, size: 50);//输出值需要赋值size

                //        db.Execute("TestProc", param, commandType: CommandType.StoredProcedure);
                //        string Name = param.Get<string>("Name");
                //        int? ReturnValue = param.Get<int>("@result");
                //    }


                //}
            }
            //oracle 存储过程
            {
                using (IDbConnection db = DapperFactory.GetConnection(Enums.MyDbType.Oracle, @"User ID=czj;Password=123456;Data Source=(DESCRIPTION = (ADDRESS_LIST= (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))) (CONNECT_DATA = (SERVICE_NAME = orcl)))"))
                {
                    //ado原生调用存储过程
                    {
                        db.Open();
                        var command = (OracleCommand)db.CreateCommand();
                        command.BindByName = true;
                        string returnValue = "";
                        List <OracleParameter> paraList = new List <OracleParameter>
                        {
                            new OracleParameter("spassword", OracleDbType.Varchar2, "123456", ParameterDirection.Input),

                            new OracleParameter("id", OracleDbType.Varchar2, Guid.NewGuid().ToString(), ParameterDirection.Input),

                            new OracleParameter("smobilephone", OracleDbType.Varchar2, "15298506403", ParameterDirection.Input),

                            new OracleParameter("semail", OracleDbType.Varchar2, "*****@*****.**", ParameterDirection.Input),

                            new OracleParameter("returnValue", OracleDbType.Varchar2, 1000, returnValue, ParameterDirection.Output)
                        };

                        command.CommandText = "proTest1";
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddRange(paraList.ToArray());
                        var effectRows = command.ExecuteScalar();
                    }

                    //dapper调用存储过程
                    {
                        //var param = new DynamicParameters();
                        //param.Add("returnValue", null, DbType.String, ParameterDirection.Output, 1000);
                        //param.Add("id", "1234569499", DbType.String,  ParameterDirection.Input);
                        //param.Add("smobilephone", "15298506403", DbType.String, ParameterDirection.Input);
                        //param.Add("semail", "*****@*****.**", DbType.String, ParameterDirection.Input);
                        //param.Add("spassword", "123456", DbType.String, ParameterDirection.Input);

                        //param.AddDynamicParams(new OracleParameter(":spassword", OracleDbType.NVarchar2, "123456", ParameterDirection.Input));
                        //param.AddDynamicParams(new OracleParameter(":smobilephone", OracleDbType.NVarchar2, "15298506403", ParameterDirection.Input));
                        //param.AddDynamicParams(new OracleParameter(":semail", OracleDbType.NVarchar2, "*****@*****.**", ParameterDirection.Input));
                        //param.AddDynamicParams(new OracleParameter(":returnValue", OracleDbType.NVarchar2, ParameterDirection.Output).Size = 1000);

                        //var obj=db.ExecuteScalar("PROTEST1", param, commandType: CommandType.StoredProcedure);
                    }
                }
            }

            //DapperExtensions.dll
            {
                Random rand = new Random();
                using (IDbConnection db = DapperFactory.GetConnection(Enums.MyDbType.SqlServer, "Data Source=localhost;Initial Catalog=test;Integrated Security=True"))
                {
                    string  id  = rand.Next(1, 2000000000).ToString();
                    Student stu = new Student {
                        ID = id, NAME = "陈兆杰", AGE = 25, TIME = DateTime.Now
                    };
                    //Insert
                    {
                        var effectRows = db.Insert(stu);//返回主键值
                    }

                    //Update
                    {
                        stu.TIME = DateTime.Now;
                        if (db.Update(stu))
                        {
                            //成功
                        }
                        else
                        {
                            //失败
                        }
                    }

                    //删除
                    {
                        //方法一
                        {
                            //if (db.Delete(stu))
                            //{
                            //    //成功
                            //}
                            //else
                            //{
                            //    //失败
                            //}
                        }

                        //方法二
                        {
                            var filedPred = Predicates.Field <Student>(o => o.ID, Operator.Eq, stu.ID);
                            if (db.Delete <Student>(filedPred))
                            {
                                //成功
                            }
                            else
                            {
                                //失败
                            }
                        }

                        //查询list
                        {
                            IList <ISort> sortlist = new List <ISort>();
                            sortlist.Add(new Sort {
                                PropertyName = "ID", Ascending = false
                            });                                                               //排序条件 降序

                            IList <IPredicate> preList = new List <IPredicate>();
                            preList.Add(Predicates.Field <Student>(o => o.ID, Operator.Eq, "1786863176")); //搜索条件,Operator有很多种的类型如eq是等于、like相当于是sql的like用法还有Lt、Le等

                            BetweenValues betweenValues = new BetweenValues();                             //搜索条件,between搜索两个值之间的数据
                            betweenValues.Value1 = "1786863176";
                            betweenValues.Value2 = "9786863176";
                            preList.Add(Predicates.Between <Student>(o => o.ID, betweenValues));

                            IPredicateGroup predGroup = Predicates.Group(GroupOperator.And, preList.ToArray());//确认多个搜索条件的连接方式AND 或者 OR
                            var             list      = db.GetList <Student>(predGroup, sortlist).ToList();
                        }
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        /// 同步数据
        /// </summary>
        public async Task SyncAsync(long accountId)
        {
            //取得微信AccessToken
            var token = await _wxAccountService.GetAccessToken(accountId);

            //开始同步用户标签
            var tagsRsp = await wcUserTool.GetUserTagListAsync(token);

            if (tagsRsp.ErrCode != 0)
            {
                throw new KuDataNotFoundException(tagsRsp.ToString());
            }
            var tags = tagsRsp.Data.Tags;

            using (var dapper = DapperFactory.CreateWithTrans())
            {
                //取得当前所有标签
                var localTags = await dapper.QueryListAsync <WxUserTag>(new { AccountId = accountId });

                var deltags = new List <long>();
                foreach (var item in localTags)
                {
                    //判断是否还有该数据
                    var newTag = tags.FirstOrDefault(x => x.Id == item.TagId);
                    if (newTag == null)
                    {
                        //远端已删除
                        deltags.Add(item.Id);
                        //await wxUserTagRepository.DeleteAsync(item.Id);
                    }
                    else
                    {
                        //更新本地数据
                        if (!item.Name.Equals(newTag.Name) || item.Count != newTag.Count)
                        {
                            item.Name  = newTag.Name;
                            item.Count = newTag.Count;
                            await dapper.UpdateAsync <WxUserTag>(new { newTag.Name, newTag.Count }, new { item.Id });
                        }
                        tags.Remove(newTag);
                    }
                }

                if (deltags.Any())
                {
                    await dapper.DeleteAsync <WxUserTag>(new DapperSql("Id IN @Ids", new { Ids = deltags.ToArray() }));
                }

                //保存新的标签
                var newTags = tags.Select(item => new WxUserTag
                {
                    Id        = ID.NewID(),
                    AccountId = accountId,
                    TagId     = item.Id,
                    Name      = item.Name,
                    Count     = item.Count
                });
                await dapper.InsertAsync(newTags);

                //保存
                dapper.Commit();
            }

            using (var dapper = DapperFactory.Create())
            {
                //开始同步用户
                string nextOpenId = null;
                do
                {
                    var rsp = await wcUserTool.GetUserListAsync(token, nextOpenId);

                    if (rsp.ErrCode != 0)
                    {
                        throw new KuArgNullException(rsp.ToString());
                    }
                    if (rsp.Data.Data.Openid == null ||
                        rsp.Data.Data.Openid.Length == 0)
                    {
                        break;
                    }

                    //处理数据
                    foreach (var openid in rsp.Data.Data.Openid)
                    {
                        await SyncOneOpenidAsync(dapper, token, accountId, openid);
                    }

                    nextOpenId = rsp.Data.Data.NextOpenid;
                    if (nextOpenId.IsNullOrEmpty())
                    {
                        break;
                    }
                } while (true);
            }

            //结束同步
        }
Example #13
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(WxMenuDto dto)
        {
            WxMenu model = Mapper.Map <WxMenu>(dto);

            if (model.Id == 0)
            {
                //新增
                model.Id         = ID.NewID();
                model.CreateTime = DateTime.Now;
                model.IsDeleted  = false;
                if (!model.IsIndividuation)
                {
                    model.MatchRuleTagId    = null;
                    model.MatchRuleSex      = null;
                    model.MatchRuleClient   = null;
                    model.MatchRuleCountry  = null;
                    model.MatchRuleProvince = null;
                    model.MatchRuleCity     = null;
                    model.MatchRuleLanguage = null;
                }
                using (var dapper = DapperFactory.Create())
                {
                    await dapper.InsertAsync(model);
                }
            }
            else
            {
                ////更新
                //var item = await _repository.GetByIdAsync(model.Id);
                //if (item == null)
                //{
                //    throw new VinoDataNotFoundException("无法取得微信菜单数据!");
                //}

                ////TODO:这里进行赋值
                //item.Name = model.Name;
                //item.MenuData = model.MenuData;
                //item.IsIndividuation = model.IsIndividuation;
                //if (!model.IsIndividuation)
                //{
                //    model.MatchRule = new WxMenuMatchRule
                //    {
                //        TagId = "",
                //        Sex = "",
                //        Client = "",
                //        Country = "",
                //        Province = "",
                //        City = "",
                //        Language = "",
                //    };
                //}

                //if (item.MatchRule != null)
                //{
                //    item.MatchRule.TagId = model.MatchRule.TagId;
                //    item.MatchRule.Sex = model.MatchRule.Sex;
                //    item.MatchRule.Client = model.MatchRule.Client;
                //    item.MatchRule.Country = model.MatchRule.Country;
                //    item.MatchRule.Province = model.MatchRule.Province;
                //    item.MatchRule.City = model.MatchRule.City;
                //    item.MatchRule.Language = model.MatchRule.Language;
                //}
                //else
                //{
                //    item.MatchRule = new WxMenuMatchRule
                //    {
                //        TagId = model.MatchRule.TagId,
                //        Sex = model.MatchRule.Sex,
                //        Client = model.MatchRule.Client,
                //        Country = model.MatchRule.Country,
                //        Province = model.MatchRule.Province,
                //        City = model.MatchRule.City,
                //        Language = model.MatchRule.Language,
                //    };
                //}
                //_repository.Update(item);
            }
        }
Example #14
0
        /// <summary>
        /// 注册
        /// </summary>
        public async Task <UserDto> RegisterAsync(string mobile, string password)
        {
            if (mobile.IsNullOrEmpty())
            {
                throw new KuArgNullException("手机号不能为空!");
            }

            if (password.IsNullOrEmpty())
            {
                throw new KuArgNullException("密码不能为空!");
            }

            //新增
            using (var dapper = DapperFactory.Create())
            {
                var model = new User {
                    Account  = mobile,
                    Password = password,
                    Mobile   = mobile,
                    Sex      = Domain.Enum.EmSex.Secret,
                    NickName = "手机用户" + mobile.Substring(7)
                };

                //格式
                if (!model.Mobile.IsMobile())
                {
                    throw new KuException("手机号格式不正确!");
                }
                //是否重复
                var count = await dapper.QueryCountAsync <User>(new { Mobile = model.Mobile });

                if (count > 0)
                {
                    throw new KuException("该手机号已被注册!");
                }

                //检查账户是否重复
                count = await dapper.QueryCountAsync <User>(new { Account = model.Account });

                if (count > 0)
                {
                    throw new KuException("该手机号已被注册!");
                }

                model.Id         = ID.NewID();
                model.CreateTime = DateTime.Now;
                model.IsDeleted  = false;
                model.Factor     = new Random().Next(9999);
                //密码加密处理
                model.EncryptPassword();

                using (var trans = dapper.BeginTrans())
                {
                    await dapper.InsertAsync(model);

                    trans.Commit();
                }

                var dto = Mapper.Map <UserDto>(model);
                dto.Password = "";
                return(dto);
            }
        }
Example #15
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(ArticleDto dto)
        {
            Article model = Mapper.Map <Article>(dto);

            if (model.Id == 0)
            {
                //新增
                model.Id         = ID.NewID();
                model.Keyword    = model.Keyword.R(",", ",");
                model.CreateTime = DateTime.Now;
                model.Visits     = 0;
                model.Praises    = 0;
                model.Collects   = 0;
                model.Comments   = 0;
                model.Tags       = "|" + string.Join("|", model.Tags.SplitRemoveEmpty(',')) + "|";
                if (model.IsPublished && !model.PublishedTime.HasValue)
                {
                    model.PublishedTime = DateTime.Now;
                }
                model.IsDeleted = false;

                using (var dapper = DapperFactory.CreateWithTrans())
                {
                    await dapper.InsertAsync(model);

                    if (model.AlbumId.HasValue)
                    {
                        var cnt = await dapper.QueryCountAsync <Article>(new { AlbumId = model.AlbumId.Value, IsPublished = true });

                        await dapper.UpdateAsync <Album>(new { Videos = cnt }, new { id = model.AlbumId.Value });
                    }

                    dapper.Commit();
                }
            }
            else
            {
                //更新
                using (var dapper = DapperFactory.CreateWithTrans())
                {
                    var entity = await dapper.QueryOneAsync <Article>(new { model.Id });

                    if (entity == null)
                    {
                        throw new KuDataNotFoundException("无法取得相关数据!");
                    }

                    dynamic item = new ExpandoObject();
                    item.Title       = model.Title;
                    item.Author      = model.Author;
                    item.Provenance  = model.Provenance;
                    item.CoverData   = model.CoverData;
                    item.OrderIndex  = model.OrderIndex;
                    item.Keyword     = model.Keyword.R(",", ",");
                    item.SubTitle    = model.SubTitle;
                    item.IsPublished = model.IsPublished;
                    item.Content     = model.Content;
                    item.ContentType = model.ContentType;
                    item.Intro       = model.Intro;
                    item.Duration    = model.Duration;
                    item.Tags        = "|" + string.Join("|", model.Tags.SplitRemoveEmpty(',')) + "|";
                    if (model.IsPublished && !model.PublishedTime.HasValue)
                    {
                        model.PublishedTime = DateTime.Now;
                    }
                    item.PublishedTime = model.PublishedTime;

                    await dapper.UpdateAsync <Article>(item, new { model.Id });

                    if (entity.AlbumId.HasValue)
                    {
                        var cnt = await dapper.QueryCountAsync <Article>(new { AlbumId = entity.AlbumId.Value, IsPublished = true });

                        await dapper.UpdateAsync <Album>(new { Videos = cnt }, new { id = entity.AlbumId.Value });
                    }

                    dapper.Commit();
                }
            }

            //清除缓存
        }
Example #16
0
        /// <summary>
        /// 权限认证
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="authCode"></param>
        /// <returns></returns>
        public async Task <bool> CheckUserAuthAsync(long userId, string authCode)
        {
            if (authCode.IsNullOrEmpty())
            {
                return(true);
            }
            var key       = string.Format(CacheKeyDefinition.UserAuthCode, userId);
            var authcodes = await _cache.GetAsync <List <string> >(key);

            if (authcodes == null)
            {
                //取得用户所有权限码
                List <string> codes = new List <string>();
                //取得所有角色
                IEnumerable <UserRole> roles = null;
                using (var dapper = DapperFactory.Create())
                {
                    var sql = "SELECT t1.*, t2.* FROM usercenter_user_role t1 INNER JOIN usercenter_role t2 ON t1.RoleId=t2.Id AND t2.IsEnable=@IsEnable WHERE t1.UserId=@UserId";
                    roles = await dapper.QueryAsync <UserRole, Role, UserRole>(sql, (t1, t2) =>
                    {
                        t1.Role = t2;
                        return(t1);
                    }, param : new { IsEnable = true, UserId = userId }, buffered : true, splitOn : "Id");

                    authcodes = new List <string>();
                    if (roles != null && roles.Any(x => x.Role.NameEn.Equals("ku.developer")))
                    {
                        authcodes.Add("ku.develop");
                    }
                    else if (roles != null)
                    {
                        foreach (var role in roles)
                        {
                            var cds = await GetRoleAuthCodesAsync(dapper, role.RoleId);

                            codes.AddRange(cds);
                        }
                        //去重
                        authcodes = codes.Distinct().ToList();
                    }

                    //缓存
                    await _cache.SetAsync(key, authcodes);
                }
            }
            if (authcodes.Contains("ku.develop"))
            {
                return(true);
            }
            //验证
            //去除空格
            string tagnobk = authCode.Replace(" ", "");
            //去除括号和操作符
            string tagnofh = tagnobk.Replace("(", ",").Replace(")", ",").Replace("&&", ",").Replace("||", ",");

            //取得所有code
            string[] codeSplits = tagnofh.Split(',');
            if (codeSplits.Length == 1)
            {
                return(authcodes.Contains(codeSplits[0]));
            }
            //TODO:以后扩展
            //foreach (var cd in codeSplits)
            //{
            //    if (cd.IsNullOrEmpty())
            //    {
            //        continue;
            //    }

            //    bool auth = authcodes.Contains(cd);
            //    if (auth)
            //    {
            //        Regex reg = new Regex(cd);
            //        tagnobk = reg.Replace(tagnobk, "true", 1);
            //    }
            //    else
            //    {
            //        Regex reg = new Regex(cd);
            //        tagnobk = reg.Replace(tagnobk, "false", 1);
            //    }
            //}

            return(authcodes.Contains(authCode));
        }
Example #17
0
        public override async Task Run(IJobExecutionContext context)
        {
            logger.Info("开始处理图片素材事务...");
            await Console.Out.WriteLineAsync("开始处理图片素材事务...");

            var count = 0;

            IImageCompressor             imageCompressor = _provider.GetService <IImageCompressor>();
            IMaterialCenterConfigService _configService  = _provider.GetService <IMaterialCenterConfigService>();
            MaterialCenterConfig         config          = await _configService.GetAsync();

            //var folder = Path.Combine(config.PictureSavePath, oppositePath);
            //if (config != null && !string.IsNullOrEmpty(config.PictureSavePath))
            //{
            //    folder = Path.Combine(config.PictureSavePath, oppositePath);
            //}

            //取得待压缩列表
            using (var dapper = DapperFactory.Create())
            {
                var builder = new QueryBuilder().Select <Picture>().From <Picture>()
                              .Where(new ConditionBuilder().Equal <Picture>(m => m.IsCompressed, false)
                                     .And().Equal <Picture>(m => m.IsDeleted, false));

                var items = await dapper.QueryListAsync <Picture>(builder);

                foreach (var item in items)
                {
                    //判断文件是否存在,如果不存在则自动删除该条数据
                    if (!File.Exists(Path.Combine(config.PictureSavePath, item.FilePath)))
                    {
                        await dapper.DeleteAsync <Picture>(new { item.Id });

                        continue;
                    }
                    if ("png".EqualOrdinalIgnoreCase(item.FileType) ||
                        "jpg".EqualOrdinalIgnoreCase(item.FileType) ||
                        "jpeg".EqualOrdinalIgnoreCase(item.FileType))
                    {
                        var fileName = item.Id + "." + item.FileType;
                        var filePath = item.Folder + fileName;
                        try
                        {
                            //压缩图片
                            await imageCompressor.Compress(Path.Combine(config.PictureSavePath, item.FilePath),
                                                           Path.Combine(config.PictureSavePath, filePath));

                            //缩略图
                            var thumbPath = item.Folder + item.Id + "_thumb." + item.FileType;
                            await imageCompressor.Resize(Path.Combine(config.PictureSavePath, item.FilePath),
                                                         Path.Combine(config.PictureSavePath, thumbPath),
                                                         new { method = "fit", width = 320, height = 320 });

                            var fileInfo = new FileInfo(Path.Combine(config.PictureSavePath, item.FilePath));

                            var model = new {
                                FilePath     = filePath,
                                FileName     = fileName,
                                ThumbPath    = thumbPath,
                                IsCompressed = true,
                                FileSize     = fileInfo.Length
                            };
                            await dapper.UpdateAsync <Picture>(model, new { item.Id });
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            await Console.Out.WriteLineAsync(ex.ToString());
                        }
                    }
                    else
                    {
                        await dapper.UpdateAsync <Picture>(new { IsCompressed = true, ThumbPath = item.FilePath }, new { item.Id });
                    }
                    count++;
                }
            }

            logger.Info($"共处理{count}张照片");
            await Console.Out.WriteLineAsync($"共处理{count}张照片");

            logger.Info($"结束处理图片素材事务...");
            await Console.Out.WriteLineAsync("结束处理图片素材事务...");
        }
Example #18
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(UserDto dto, long[] userRoles)
        {
            User model = Mapper.Map <User>(dto);

            if (model.Id == 0)
            {
                //新增
                using (var dapper = DapperFactory.Create())
                {
                    //检查账户是否重复
                    var count = await dapper.QueryCountAsync <User>(new { Account = model.Account });

                    if (count > 0)
                    {
                        throw new KuException("账户名重复!");
                    }

                    //检查手机号
                    if (model.Mobile.IsNotNullOrEmpty())
                    {
                        //格式
                        if (!model.Mobile.IsMobile())
                        {
                            throw new KuException("手机号格式不正确!");
                        }
                        //是否重复
                        count = await dapper.QueryCountAsync <User>(new { Mobile = model.Mobile });

                        if (count > 0)
                        {
                            throw new KuException("手机号重复!");
                        }
                    }

                    model.Id         = ID.NewID();
                    model.CreateTime = DateTime.Now;
                    model.IsDeleted  = false;
                    model.Factor     = new Random().Next(9999);
                    //密码加密处理
                    model.EncryptPassword();

                    if (!model.IsAdmin)
                    {
                        userRoles = new long[] { };
                    }
                    //角色处理
                    var roles = userRoles?.Select(x => new UserRole {
                        UserId = model.Id, RoleId = x
                    });

                    using (var trans = dapper.BeginTrans())
                    {
                        await dapper.InsertAsync(model);

                        await dapper.InsertAsync <UserRole>(roles);

                        trans.Commit();
                    }
                }
            }
            else
            {
                //更新
                using (var dapper = DapperFactory.Create())
                {
                    var user = await dapper.QueryOneAsync <User>(new { model.Id });

                    if (user == null)
                    {
                        throw new KuDataNotFoundException("无法取得用户数据!");
                    }
                    if (!user.Account.Equals(model.Account))
                    {
                        //检查账户是否重复
                        var count = await dapper.QueryCountAsync <User>(new { Account = model.Account });

                        if (count > 0)
                        {
                            throw new KuException("账户名重复!");
                        }
                    }
                    if (!string.IsNullOrEmpty(model.Mobile) && !model.Mobile.Equals(user.Mobile))
                    {
                        //检查手机号
                        //格式
                        if (!model.Mobile.IsMobile())
                        {
                            throw new KuException("手机号格式不正确!");
                        }
                        //是否重复
                        var count = await dapper.QueryCountAsync <User>(new { Mobile = model.Mobile });

                        if (count > 0)
                        {
                            throw new KuException("手机号重复!");
                        }
                    }
                    dynamic item = new ExpandoObject();
                    item.Account   = model.Account;
                    item.NickName  = model.NickName;
                    item.RealName  = model.RealName;
                    item.Mobile    = model.Mobile;
                    item.Email     = model.Email;
                    item.Sex       = model.Sex;
                    item.HeadImage = model.HeadImage;
                    item.IsEnable  = model.IsEnable;
                    item.Remarks   = model.Remarks;
                    item.IsAdmin   = model.IsAdmin;
                    if (!model.Password.EqualOrdinalIgnoreCase("********************"))
                    {
                        model.EncryptPassword();
                        item.Password = model.Password;
                    }
                    if (!model.IsAdmin)
                    {
                        userRoles = new long[] { };
                    }
                    var roles = userRoles?.Select(x => new UserRole {
                        UserId = model.Id, RoleId = x
                    });

                    using (var trans = dapper.BeginTrans())
                    {
                        await dapper.UpdateAsync <User>(item, new { model.Id });

                        //删除所有用户角色数据
                        await dapper.DeleteAsync <UserRole>(new { UserId = model.Id });

                        await dapper.InsertAsync <UserRole>(roles);

                        trans.Commit();
                    }
                }
            }
        }
Example #19
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(PaymentDto dto)
        {
            Payment model = Mapper.Map <Payment>(dto);

            if (model.Id == 0)
            {
                //新增
                model.Id            = ID.NewID();
                model.CreateTime    = DateTime.Now;
                model.IsDeleted     = false;
                model.IsSnapshot    = false;
                model.SnapshotCount = 0;
                model.OriginId      = null;
                model.EffectiveTime = DateTime.Now;
                using (var dapper = DapperFactory.Create())
                {
                    await dapper.InsertAsync(model);
                }
            }
            else
            {
                //更新
                using (var dapper = DapperFactory.Create())
                {
                    var item = new
                    {
                        //TODO:这里进行赋值
                    };
                    await dapper.UpdateAsync <Payment>(item, new { model.Id });
                }

                //var item = await _repository.GetByIdAsync(model.Id);
                //if (item == null)
                //{
                //    throw new VinoDataNotFoundException("无法取得支付方式数据!");
                //}
                //using (var trans = await _repository.BeginTransactionAsync())
                //{
                //    //生成快照
                //    if (item.PaymentMode != model.PaymentMode
                //        || !item.PaymentConfig.Equals(model.PaymentConfig))
                //    {
                //        Payment snapshot = new Payment();
                //        snapshot.Id = ID.NewID();
                //        snapshot.IsDeleted = false;
                //        snapshot.CreateTime = DateTime.Now;
                //        snapshot.Name = item.Name;
                //        snapshot.Description = item.Description;
                //        snapshot.IsEnable = item.IsEnable;
                //        snapshot.IsMobile = item.IsMobile;
                //        snapshot.PaymentConfig = item.PaymentConfig;
                //        snapshot.PaymentMode = item.PaymentMode;
                //        snapshot.SnapshotCount = item.SnapshotCount;
                //        snapshot.EffectiveTime = item.EffectiveTime;
                //        snapshot.ExpireTime = DateTime.Now;
                //        snapshot.IsSnapshot = true;
                //        snapshot.OriginId = item.OriginId;

                //        await _repository.InsertAsync(snapshot);

                //        item.PaymentMode = model.PaymentMode;
                //        item.PaymentConfig = model.PaymentConfig;
                //        item.EffectiveTime = DateTime.Now;
                //        item.SnapshotCount = item.SnapshotCount + 1;
                //    }
                //    item.Name = model.Name;
                //    item.Description = model.Description;
                //    item.IsEnable = model.IsEnable;
                //    item.IsMobile = model.IsMobile;

                //    _repository.Update(item);
                //    await _repository.SaveAsync();

                //    trans.Commit();
                //}
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            DapperFactory.CreateInstance().ConfigureServices(service =>
            {
                service.AddDapperForSQLite();
            }).ConfigureContainer(container =>
            {
                container.AddDapperForSQLite("Sqlite2", "sqlite2");
            }).ConfigureConfiguration(builder =>
            {
                builder.SetBasePath(Directory.GetCurrentDirectory());
                builder.AddJsonFile("appsettings.json");
            }).Build();

            DapperFactory.Step(dapper =>
            {
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            var result7 = DapperFactory.Step(dapper => { return(dapper.Query("select * from Contact;")); });

            Console.WriteLine(JsonConvert.SerializeObject(result7));

            DapperFactory.StepAsync(async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            var result8 = DapperFactory.StepAsync(async dapper => await dapper.QueryAsync("select * from Contact;")).Result;

            Console.WriteLine(JsonConvert.SerializeObject(result8));


            DapperFactory.Step("sqlite2", dapper =>
            {
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            var result9 = DapperFactory.Step("sqlite2", dapper => { return(dapper.Query("select * from Contact;")); });

            Console.WriteLine(JsonConvert.SerializeObject(result9));

            DapperFactory.StepAsync("sqlite2", async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            var result10 = DapperFactory.StepAsync("sqlite2", async dapper => await dapper.QueryAsync("select * from Contact;")).Result;

            Console.WriteLine(JsonConvert.SerializeObject(result10));



            DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                var query  = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            DapperFactory.StepAsync(async context =>
            {
                var dapper     = context.ResolveDapper();
                var queryAsync = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(queryAsync));
            }).Wait();

            DapperFactory.Step((context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            DapperFactory.StepAsync(async(context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            DapperFactory.Step("sqlite2", (context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            });

            DapperFactory.StepAsync("sqlite2", async(context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Console.WriteLine(JsonConvert.SerializeObject(query));
            }).Wait();

            var result1 = DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                return(dapper.Query("select * from Contact;"));
            });

            Console.WriteLine(JsonConvert.SerializeObject(result1));

            var result2 = DapperFactory.StepAsync(context =>
            {
                var dapper = context.ResolveDapper();
                return(dapper.QueryAsync("select * from Contact;"));
            }).Result;

            Console.WriteLine(JsonConvert.SerializeObject(result2));

            var result3 = DapperFactory.Step((context, dapper) => dapper.Query("select * from Contact;"));

            Console.WriteLine(JsonConvert.SerializeObject(result3));

            var result4 = DapperFactory.StepAsync(async(context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;

            Console.WriteLine(JsonConvert.SerializeObject(result4));

            var result5 = DapperFactory.Step("sqlite2", (context, dapper) => dapper.Query("select * from Contact;"));

            Console.WriteLine(JsonConvert.SerializeObject(result5));

            var result6 = DapperFactory.StepAsync("sqlite2", async(context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;

            Console.WriteLine(JsonConvert.SerializeObject(result6));

            Console.ReadKey();
        }
Example #21
0
        public override async Task Run(IJobExecutionContext context)
        {
            logger.Info("开始处理视频素材事务...");
            await Console.Out.WriteLineAsync("开始处理视频素材事务...");

            var count = 0;

            IImageCompressor             imageCompressor = _provider.GetService <IImageCompressor>();
            IMaterialCenterConfigService _configService  = _provider.GetService <IMaterialCenterConfigService>();
            MaterialCenterConfig         config          = await _configService.GetAsync();

            //var folder = Path.Combine(config.PictureSavePath, oppositePath);
            //if (config != null && !string.IsNullOrEmpty(config.PictureSavePath))
            //{
            //    folder = Path.Combine(config.PictureSavePath, oppositePath);
            //}

            //取得待压缩列表
            using (var dapper = DapperFactory.Create())
            {
                var builder = new QueryBuilder().Select <Video>().From <Video>()
                              .Where(new ConditionBuilder().IsNullOrEmpty <Video>(x => x.ThumbPath)
                                     .And().Equal <Video>(m => m.IsDeleted, false));

                var items = await dapper.QueryListAsync <Video>(builder);

                foreach (var item in items)
                {
                    //判断文件是否存在
                    if (!File.Exists(Path.Combine(config.PictureSavePath, item.FilePath)))
                    {
                        continue;
                    }

                    try
                    {
                        //缩略图
                        var thumbPath = item.Folder + item.Id + "_thumb.jpg";
                        var thumb     = VideoHelper.GetPreviewImage(Path.Combine(config.PictureSavePath, item.FilePath),
                                                                    Path.Combine(config.PictureSavePath, thumbPath), 320, 180, 1);
                        if (thumb != null)
                        {
                            thumb = thumbPath;
                        }
                        //时长
                        var duration = VideoHelper.GetVideoDuration(Path.Combine(config.PictureSavePath, item.FilePath));

                        await dapper.UpdateAsync <Video>(new { ThumbPath = thumb, Duration = duration }, new { item.Id });
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        await Console.Out.WriteLineAsync(ex.ToString());
                    }
                    count++;
                }
            }

            logger.Info($"共处理{count}个视频");
            await Console.Out.WriteLineAsync($"共处理{count}个视频");

            logger.Info($"结束处理视频素材事务...");
            await Console.Out.WriteLineAsync("结束处理视频素材事务...");
        }
Example #22
0
        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync(ProductDto dto, List <ProductSkuDto> skus)
        {
            Product           model   = Mapper.Map <Product>(dto);
            List <ProductSku> skuList = Mapper.Map <List <ProductSku> >(skus);

            if (skuList == null || skuList.Count == 0)
            {
                throw new VinoDataNotFoundException("至少添加一项商品SKU!");
            }
            if (model.Id == 0)
            {
                //新增
                model.Id            = ID.NewID();
                model.CreateTime    = DateTime.Now;
                model.Sales         = 0;
                model.Visits        = 0;
                model.IsDeleted     = false;
                model.IsSnapshot    = false;
                model.SnapshotCount = 0;
                model.OriginId      = null;
                model.EffectiveTime = DateTime.Now;

                foreach (var item in skuList)
                {
                    item.ProductId  = model.Id;
                    item.CreateTime = DateTime.Now;
                    item.IsDeleted  = false;
                    item.Sales      = 0;
                    if (item.PointsGainRule != EmPointsGainRule.ProductSku)
                    {
                        item.GainPoints = 0;
                    }
                }
                model.Stock = skuList.Sum(x => x.Stock);
                var maxPrice = skuList.Max(x => x.Price);
                var minPrice = skuList.Min(x => x.Price);
                if (maxPrice == minPrice)
                {
                    model.PriceRange = maxPrice + "";
                }
                else
                {
                    model.PriceRange = minPrice + "~" + maxPrice;
                }
                using (var dapper = DapperFactory.CreateWithTrans())
                {
                    await dapper.InsertAsync(model);

                    await dapper.InsertAsync <ProductSku>(skuList);

                    dapper.Commit();
                }
            }
            else
            {
                ////更新
                //var item = await _repository.GetByIdAsync(model.Id);
                //if (item == null || item.IsDeleted)
                //{
                //    throw new VinoDataNotFoundException("无法取得商品数据!");
                //}
                //if (item.IsSnapshot)
                //{
                //    throw new VinoDataNotFoundException("快照数据无法修改!");
                //}

                //using (var trans = await _repository.BeginTransactionAsync())
                //{
                //    //生成快照
                //    Product snapshot = item.Copy();
                //    snapshot.Id = ID.NewID();
                //    snapshot.IsDeleted = false;
                //    snapshot.CreateTime = DateTime.Now;
                //    snapshot.ExpireTime = DateTime.Now;
                //    snapshot.IsSnapshot = true;
                //    snapshot.OriginId = item.OriginId;
                //    await _repository.InsertAsync(snapshot);

                //    //var search = new ProductSkuSearch { ProductId = item.Id };
                //    //包含已删除数据
                //    var skuItems = await _skuRepository.QueryAsync((x=>x.ProductId == item.Id), null, null);
                //    var snapshotSkus = new List<ProductSku>();
                //    foreach (var sku in skuItems)
                //    {
                //        ProductSku snapshotSku = sku.Copy();
                //        snapshotSku.Id = ID.NewID();
                //        snapshotSku.ProductId = snapshot.Id;
                //        snapshotSkus.Add(snapshotSku);
                //    }
                //    await _skuRepository.InsertRangeAsync(snapshotSkus);
                //    //end

                //    model.Stock = skuList.Sum(x => x.Stock);
                //    var maxPrice = skuList.Max(x => x.Price);
                //    var minPrice = skuList.Min(x => x.Price);
                //    if (maxPrice == minPrice)
                //    {
                //        model.PriceRange = maxPrice + "";
                //    }
                //    else
                //    {
                //        model.PriceRange = minPrice + "~" + maxPrice;
                //    }

                //    item.Status = model.Status;
                //    item.Name = model.Name;
                //    item.Title = model.Title;
                //    item.Intro = model.Intro;
                //    item.ImageData = model.ImageData;
                //    item.ContentType = model.ContentType;
                //    item.Content = model.Content;
                //    item.PriceRange = model.PriceRange;
                //    item.Stock = model.Stock;
                //    item.OrderIndex = model.OrderIndex;
                //    item.Properties = model.Properties;
                //    item.CategoryId = model.CategoryId;

                //    item.SnapshotCount = item.SnapshotCount + 1;
                //    item.EffectiveTime = DateTime.Now;

                //    //var search = new ProductSkuSearch { ProductId = item.Id };
                //    //var skuItems = await _skuRepository.QueryAsync(search.GetExpression(), null);

                //    //新增
                //    var newSkus = skuList.Where(x => x.ModifyStatus == Domain.Enum.EmEntityModifyStatus.Insert);
                //    foreach (var sku in newSkus)
                //    {
                //        sku.ProductId = item.Id;
                //        sku.CreateTime = DateTime.Now;
                //        sku.IsDeleted = false;
                //        sku.Sales = 0;
                //        if (sku.PointsGainRule != EmPointsGainRule.ProductSku)
                //        {
                //            sku.GainPoints = 0;
                //        }
                //    }
                //    await _skuRepository.InsertRangeAsync(newSkus.ToList());

                //    //删除
                //    foreach (var sku in skuList.Where(x => x.ModifyStatus == Domain.Enum.EmEntityModifyStatus.Delete))
                //    {
                //        await _skuRepository.DeleteAsync(sku.Id);
                //    }
                //    //更新
                //    foreach (var sku in skuList.Where(x => x.ModifyStatus == Domain.Enum.EmEntityModifyStatus.Update))
                //    {
                //        var skuItem = _skuRepository.GetById(sku.Id);
                //        if (skuItem == null || skuItem.IsDeleted)
                //        {
                //            trans.Rollback();
                //            throw new VinoDataNotFoundException("SKU数据无法取得!");
                //        }
                //        skuItem.Title = sku.Title;
                //        skuItem.CoverImage = sku.CoverImage;
                //        skuItem.Price = sku.Price;
                //        skuItem.MarketPrice = sku.MarketPrice;
                //        skuItem.Stock = sku.Stock;
                //        skuItem.OrderIndex = sku.OrderIndex;
                //        skuItem.PointsGainRule = sku.PointsGainRule;
                //        skuItem.GainPoints = sku.GainPoints;
                //        if (skuItem.PointsGainRule != EmPointsGainRule.ProductSku)
                //        {
                //            skuItem.GainPoints = 0;
                //        }
                //        _skuRepository.Update(skuItem);
                //    }

                //    _repository.Update(item);
                //    await _repository.SaveAsync();
                //    trans.Commit();
                //}
            }
        }
        public void Test()
        {
            DapperFactory.Step(dapper =>
            {
                var query = dapper.Query("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            });

            var result7 = DapperFactory.Step(dapper => { return(dapper.Query("select * from Contact;")); });

            Assert.NotNull(result7);
            Assert.True(result7.Any());

            DapperFactory.StepAsync(async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            }).Wait();

            var result8 = DapperFactory.StepAsync(async dapper => await dapper.QueryAsync("select * from Contact;")).Result;

            Assert.NotNull(result8);
            Assert.True(result8.Any());


            DapperFactory.Step("sqlite2", dapper =>
            {
                var query = dapper.Query("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            });

            var result9 = DapperFactory.Step("sqlite2", dapper => { return(dapper.Query("select * from Contact;")); });

            Assert.NotNull(result9);
            Assert.True(result9.Any());

            DapperFactory.StepAsync("sqlite2", async dapper =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            }).Wait();

            var result10 = DapperFactory.StepAsync("sqlite2", async dapper => await dapper.QueryAsync("select * from Contact;")).Result;

            Assert.NotNull(result10);
            Assert.True(result10.Any());


            DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                var query  = dapper.Query("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            });

            DapperFactory.StepAsync(async context =>
            {
                var dapper     = context.ResolveDapper();
                var queryAsync = await dapper.QueryAsync("select * from Contact;");
                Assert.NotNull(queryAsync);
                Assert.True(queryAsync.Any());
            }).Wait();

            DapperFactory.Step((context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            });

            DapperFactory.Step(context =>
            {
                var master = context.ResolveDapper("master_slave");
                var rows   = master.Execute("update COMPANY set name=@name where id=@id;", new { name = Guid.NewGuid().ToString(), id = 1 });
                Assert.True(rows > 0);
                Output.WriteLine("Master:" + master.Conn.Value.ConnectionString);


                var slave = context.ResolveDapper("master_slave", true);
                var read  = slave.Query("select * from company;");
                Assert.NotNull(read);
                Assert.True(read.Any());
                Output.WriteLine("Slave:" + slave.Conn.Value.ConnectionString);
            });

            DapperFactory.StepAsync(async(context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            }).Wait();

            DapperFactory.Step("sqlite2", (context, dapper) =>
            {
                var query = dapper.Query("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            });

            DapperFactory.StepAsync("sqlite2", async(context, dapper) =>
            {
                var query = await dapper.QueryAsync("select * from Contact;");
                Assert.NotNull(query);
                Assert.True(query.Any());
            }).Wait();

            var result1 = DapperFactory.Step(context =>
            {
                var dapper = context.ResolveDapper();
                return(dapper.Query("select * from Contact;"));
            });

            Assert.NotNull(result1);
            Assert.True(result1.Any());

            var result2 = DapperFactory.StepAsync(context =>
            {
                var dapper = context.ResolveDapper();
                return(dapper.QueryAsync("select * from Contact;"));
            }).Result;

            Assert.NotNull(result2);
            Assert.True(result2.Any());

            var result3 = DapperFactory.Step((context, dapper) => dapper.Query("select * from Contact;"));

            Assert.NotNull(result3);
            Assert.True(result3.Any());

            var result4 = DapperFactory.StepAsync(async(context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;

            Assert.NotNull(result4);
            Assert.True(result4.Any());

            var result5 = DapperFactory.Step("sqlite2", (context, dapper) => dapper.Query("select * from Contact;"));

            Assert.NotNull(result5);
            Assert.True(result5.Any());

            var result6 = DapperFactory.StepAsync("sqlite2", async(context, dapper) => await dapper.QueryAsync("select * from Contact;")).Result;

            Assert.NotNull(result6);
            Assert.True(result6.Any());
        }