Exemple #1
0
 /// <summary>
 /// 新增
 /// </summary>
 /// <typeparam name="TEntity"></typeparam>
 /// <param name="mapper"></param>
 /// <param name="entity"></param>
 /// <param name="enableLog"></param>
 /// <returns></returns>
 public static TEntity Add<TEntity>(ISqlMapper mapper, TEntity entity, bool enableLog = true) where TEntity : IEntity
 {
     var type = typeof(TEntity);
     string tableName = type.Name;
     var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
     DateTime now = DateTime.Now;
     foreach (var property in properties)
     {
         var primarykey = property.GetCustomAttribute<PrimaryKey>(true);
         if (primarykey != null)
         {
             object value = entity.TryGetValue(property.Name);
             if (value == null)
             {
                 IIDGenerator generator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);
                 value = generator.Generate();
                 entity.TrySetValue(property.Name, value);
             }
         }
         if ((property.Name.ToLower().Equals("createtime") || property.Name.ToLower().Equals("lastupdatetime")) && (property.PropertyType.Equals(typeof(DateTime)) || property.PropertyType.Equals(typeof(Nullable<DateTime>))))
         {
             entity.TrySetValue(property.Name, now);
         }
     }
     string action = tableName + ".Add";
     if (enableLog) WriteSqlLog(mapper, action, entity, mapper.GetSession());
     mapper.Insert(action, entity);
     return entity;
 }
        public SqlModel ObjectToSql(string tableName, IDictionary <string, object> o, IList <WhereClause> where, TableConfig config = null)
        {
            InsertMapper     insertMapper = new InsertMapper(Converter);
            UpdateByIDMapper updateMapper = new UpdateByIDMapper(Converter);
            StringBuilder    judgement    = new StringBuilder();
            SqlModel         model        = new SqlModel();


            judgement.AppendFormat(" EXISTS(SELECT 1 FROM {0} WHERE ", tableName);
            foreach (var key in o.Keys)
            {
                var column = config?.ColumnMapping?.Find(t => t.SourceColumn.ToLower().Equals(key.ToLower()));
                if (column != null && column.Ingore)
                {
                    continue;
                }
                if (column == null || !column.Primarykey)
                {
                    continue;
                }
                if (column != null && column.GenerateID && o[key] == null)
                {
                    IIDGenerator generator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);
                    o.SetValue(key, generator.Generate());
                }
                string columnName = Common.GetColumnName(key, column);
                if (string.IsNullOrEmpty(columnName))
                {
                    continue;
                }
                judgement.AppendFormat("{0}={1} AND ", Converter.FormatColumn(columnName), Converter.FormatParameter(columnName));
            }

            var insertModel = insertMapper.ObjectToSql(tableName, o, where, config);
            var updateModel = updateMapper.ObjectToSql(tableName, o, where, config);

            judgement.Remove(judgement.Length - 4, 4);
            judgement.Append(")");
            string sql = Converter.BuildIfElseStatement(judgement.ToString(), updateModel.SQL, insertModel.SQL);

            model.SQL        = sql;
            model.Parameters = updateModel.Parameters;
            return(model);
        }
Exemple #3
0
        private ConsumeConcurrentlyStatus Producer_ConsumeMessage(object obj, ConsumeEventArgs args)
        {
            IDBHelper helper = DBFactory.CreateDBHelper();
            //存储队列
            var generator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);

            foreach (var m in args.Messages)
            {
                try
                {
                    StringBuilder sql       = new StringBuilder();
                    string        ID        = generator.Generate();
                    string        body      = Encoding.UTF8.GetString(m.getBody());
                    string        tableName = m.getKeys();
                    string        tag       = m.getTags();

                    sql.Append("INSERT INTO MQCache([ID],[Key],[Tag],[Body],[CreateTime]) VALUES(@ID, @Key, @Tag, @Body, GETDATE())");
                    List <Parameter> parameters = new List <Parameter>
                    {
                        new Parameter("@ID", ID),
                        new Parameter("@Key", tableName),
                        new Parameter("@Tag", tag),
                        new Parameter("@Body", body),
                    };
                    lock (this)
                    {
                        helper.ExecNoneQueryWithSQL(sql.ToString(), parameters.ToArray());
                    }
                    _logger.Write("插入数据库成功,json:" + body);
                }
                catch (Exception ex)
                {
                    _logger.WriteException(ex);
                    throw ex;
                }
            }


            return(ConsumeConcurrentlyStatus.CONSUME_SUCCESS);
        }
Exemple #4
0
        public override int InsertOrUpdate(IDictionary <string, object> o)
        {
            SelectByIDMapper existsMapper = new SelectByIDMapper(Factory.CreateConverter(_helper.DBType));
            var configs = _config.ColumnMapping?.FindAll(t => t.GenerateID);

            if (configs != null && configs.Count > 0)
            {
                configs.ForEach(t =>
                {
                    var value = o[t.SourceColumn];
                    if (value == null)
                    {
                        IIDGenerator generator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);
                        o[t.SourceColumn]      = generator.Generate();
                    }
                });
            }
            string tableName   = Common.GetTableName(_key, _config.Owner, o.GetType(), _config, o);
            var    existsModel = existsMapper.ObjectToSql(tableName, o, null, _config);
            int    result      = 0;

            result = Execute(tableName, o, existsModel);
            return(result);
        }
Exemple #5
0
        static void Main(string[] args)
        {
            var h  = DBFactory.CreateDBHelper(@"Data Source=E:\git\memberManager\db\membermanager.db;Version=3;", DBType.SQLite);
            var tb = h.GetTableWithSQL("SELECT NAME FROM sqlite_master WHERE type='table'");

            #region id generator
            IIDGenerator  iDGenerator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);
            List <string> idlist      = new List <string>();
            for (int i = 0; i < 10000; i++)
            {
                idlist.Add(iDGenerator.Generate());
            }

            #endregion

            TestClass tc = new TestClass
            {
                tc = new TestClass
                {
                    a  = "hello",
                    b  = "word",
                    tc = new TestClass
                    {
                        a = "deep",
                    }
                },
                test = new List <TestClass>
                {
                    new TestClass
                    {
                        a = "<",
                    }
                },
            };
            #region xml testing
            TestRequest req = new TestRequest
            {
                c = new TestClass
                {
                    a  = "a",
                    b  = "b",
                    d  = "d",
                    dt = DateTime.Now,
                }
            };
            ISerializable serial = new XmlSerializor();
            var           xml    = serial.Serialize(req);

            var obj = serial.Deserialize <TestRequest>(xml);

            Dictionary <string, object> arg = new Dictionary <string, object>();
            arg["a"] = "a";
            arg["b"] = 3;
            arg["c"] = req;
            xml      = serial.Serialize(arg);
            var dicobj = serial.Deserialize <Dictionary <string, object> >(xml);
            #endregion
            //string jsonstring = "{\"Buyers\":[{\"ID\":\"395f7ce8de8340eda2dfd22098c81290\",\"Name\":\"爱的色放\",\"CardType\":\"1\",\"IdentityCode\":\"4444444444\",\"Phone\":\"123123123123\",\"Gender\":\"1\",\"Marrage\":\"1\",\"Address\":\"啊都是法师打发而且额外人\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"1\",\"WorkUnit\":\"\",\"Quotient\":\"222\"},{\"ID\":\"\",\"Name\":\"阿萨法 \",\"CardType\":\"1\",\"IdentityCode\":\"986799283948723984\",\"Phone\":\"123123\",\"Gender\":\"2\",\"Marrage\":\"1\",\"Address\":\"三个地方集团研究研究\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"\",\"WorkUnit\":\"\",\"Quotient\":\"333\"},{\"ID\":\"712feaff6c034244ab3f066268b9fe5a\",\"Name\":\"阿斯顿飞\",\"CardType\":\"1\",\"IdentityCode\":\"12312312312323\",\"Phone\":\"123123123\",\"Gender\":\"1\",\"Marrage\":\"1\",\"Address\":\"嘎达嗦嘎多个地方十多个地方各个\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"1\",\"WorkUnit\":\"\",\"Quotient\":\"222\"}],\"Sellers\":[{\"ID\":\"55b71c225dc841a7b99ead4cecc601c5\",\"Name\":\"aeeboo\",\"CardType\":\"1\",\"IdentityCode\":\"234234235235\",\"Phone\":\"324234234234\",\"Gender\":\"1\",\"Marrage\":\"2\",\"Address\":\"的方式购房合同和投入和\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"2\",\"WorkUnit\":\"\",\"Quotient\":\"111\"},{\"ID\":\"\",\"Name\":\"阿萨德飞44\",\"CardType\":\"1\",\"IdentityCode\":\"237856234\",\"Phone\":\"34234234\",\"Gender\":\"1\",\"Marrage\":\"1\",\"Address\":\"然后统一集团研究与\",\"OrignalName\":\"\",\"OrignalIdentityCode\":\"\",\"BankCode\":\"\",\"BankType\":\"\",\"WorkUnit\":\"\",\"Quotient\":\"123\"}],\"Assets\":[{\"ID\":\"\",\"Code\":\"44444444\",\"Usage\":\"1\",\"Position\":\"2\",\"Address\":\"景田西路八个道路\",\"Area\":\"123\",\"RegPrice\":\"44232\"},{\"ID\":\"\",\"Code\":\"1412412132\",\"Usage\":\"1\",\"Position\":\"1\",\"Address\":\"水电费个人个人高\",\"Area\":\"234324\",\"RegPrice\":\"123123\"}],\"Project\":{\"Source\":\"1\",\"AgentName\":\"213213\",\"CertificateData\":\"2015-08-05\",\"AgentContact\":\"\",\"Rebater\":\"\",\"RebateAccount\":\"\",\"OtherRebateInfo\":\"\",\"OrignalMortgageBank\":\"1\",\"OrignalMortgageBranch\":\"阿斯顿发顺丰\",\"OrignalFundCenter\":\"1\",\"OrignalFundBranch\":\"\",\"SupplyCardCopy\":\"\",\"OrignalCreditPI\":\"123123\",\"OrignalCreditCommerceMoney\":\"123\",\"OrignalCreditFundMoney\":\"123\",\"AssetRansomCustomerManager\":\"124142\",\"AssetRansomContactPhone\":\"24124\",\"NewCreditBank\":\"1\",\"NewCreditBranch\":\"2r323\",\"ShortTermAssetRansomBank\":\"1\",\"ShortTermAssetRansomBranch\":\"\",\"GuaranteeMoney\":\"123\",\"GuaranteeMonth\":\"1231\",\"BuyerCreditCommerceMoney\":\"213\",\"BuyerCreditFundMoney\":\"2\",\"LoanMoney\":\"123123\",\"DealMoney\":\"123123\",\"EarnestMoney\":\"123123\",\"SupervisionMoney\":\"123123\",\"SupervisionBank\":\"12123\",\"AssetRansomMoney\":\"122323\",\"CustomerPredepositMoney\":\"323232\",\"CreditReceiverName\":\"23123\",\"CreditReceiverBank\":\"2323\",\"CreditReceiverAccount\":\"2323\",\"TrusteeshipAccount\":\"\",\"AssetRansomPredictMoney\":\"2323\",\"AssetRansomer\":\"232323\",\"AssetRansomType\":\"1\",\"PredictDays\":\"2323\",\"ChargeType\":\"1\",\"CheckNumbersAndLimit\":\"123123\",\"Stagnationer\":\"\"},\"token\":\"0cbbd08b6b694428a30afe52098e5f7a\"}";
            //var json = JsonHelper.Deserialize<AddProjectServiceForm>(jsonstring);
            #region domain
            //AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
            //AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve1;
            //AppDomainSetup info = new AppDomainSetup();
            //info.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory + "Modules";
            //AppDomain domain = AppDomain.CreateDomain("mydomain", null, info);
            //Console.WriteLine(domain.BaseDirectory);
            //var allass = domain.GetAssemblies();
            //var ass = domain.Load(new AssemblyName("Controller"));
            //allass = domain.GetAssemblies();
            //var type = ass.GetType("SOAFramework.Library.HttpServer");
            //var instance = Activator.CreateInstance(type, null);
            //var start = type.GetMethod("Start");
            //start.Invoke(instance, new object[] { new string[] { "http://10.1.50.195:8094/c" } });
            //domain.AssemblyLoad += Domain_AssemblyLoad;
            #endregion

            #region http server
            Console.WriteLine("begin");
            NodeServer nodeserver = new NodeServer("http://10.1.50.195:8094/");
            nodeserver.Start();
            Console.ReadLine();
            //nodeserver.Close();

            HttpServer server = new HttpServer(new string[] { "http://10.1.50.195:8094/a" });
            server.Executing += new HttpExecutingHandler((a, b) =>
            {
                StreamReader reder = new StreamReader(b.Request.InputStream, System.Text.Encoding.UTF8);
                string post        = reder.ReadToEnd();
                Console.WriteLine("key:" + post);
                return("");
            });
            server.Start();

            //HttpServer server2 = new HttpServer(new string[] { "http://10.1.50.195:8094/b" });
            //server2.Start();
            Console.ReadLine();

            string[] prefix = new string[] { "http://*****:*****@"http://localhost/Service/Execute/SOAFramework.Service.Server.DefaultService/DiscoverService", data);
            testresult = ZipHelper.UnZip(testresult);
            List <ServiceInfo>          serviceList   = JsonHelper.Deserialize <List <ServiceInfo> >(testresult);
            string                      path          = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + @"\Templates\SDKRequest.cst";
            Dictionary <string, object> argsCodeSmith = new Dictionary <string, object>();
            argsCodeSmith["RequestNameSpace"] = "a.b.c";
            argsCodeSmith["ServiceInfo"]      = serviceList[0];
            string render = CodeSmithHelper.GenerateString(path, argsCodeSmith);

            string  fileName = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\SOAFramework.Library.CodeSmithConsole.exe ";
            Process p        = new Process();
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.FileName               = fileName;
            p.StartInfo.Arguments              = " " + path.Replace(@"\\", @"\" + " ") + " " + JsonHelper.Serialize(argsCodeSmith).Replace("\"", "\\\"") + " ";
            p.StartInfo.RedirectStandardInput  = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();
            p.WaitForExit();
            return;

            #endregion

            #region razor
            //string strr = File.ReadAllText("Temp.txt");
            //Dictionary<string, object> dicargs = new Dictionary<string, object>();
            //dicargs["a"] = "22222";
            //string r = Razor.Parse(strr, dicargs);
            #endregion

            #region json tester
            //List<TestClass> list = new List<TestClass>();
            //for (int i = 0; i < 10; i++)
            //{
            //    TestClass c = new TestClass
            //    {
            //        a = "a" + i.ToString(),
            //        b = "b" + i.ToString(),
            //        dic = new Dictionary<string, string>(),
            //    };
            //    c.dic["dic1"] = "dic1" + i.ToString();
            //    c.dic["dic2"] = "dic2" + i.ToString();
            //    c.dic["dic3"] = "dic3" + i.ToString();
            //    c.test = new List<TestClass>();
            //    c.test.Add(new TestClass { a = "aa" + i.ToString(), b = "bb" + i.ToString() });
            //    c.test.Add(new TestClass { a = "cc" + i.ToString(), b = "dd" + i.ToString() });
            //    list.Add(c);
            //}
            //watch.Start();
            //string strjson = JsonHelper.Serialize(list, false);
            //watch.Stop();
            //Console.WriteLine("序列化:{0}", watch.ElapsedMilliseconds);
            //watch.Reset();
            //watch.Start();
            //List<TestClass> list1 = JsonHelper.Deserialize<List<TestClass>>(strjson);
            //watch.Stop();
            //Console.WriteLine("反序列化:{0}", watch.ElapsedMilliseconds);
            //TestResponse re = JsonHelper.Deserialize<TestResponse>("{\"IsError\":false,\"Data\":[{\"InterfaceName\":\"SOAFramework.Service.Server.DefaultService.DiscoverService\"}]}");
            #endregion

            #region custom wcf binding
            //string baseAddress = "Http://localhost/Service";
            //ServiceHost host = new WebServiceHost(typeof(SOAService), new Uri(baseAddress));
            //host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "soap");
            //WebHttpBinding webBinding = new WebHttpBinding();
            //webBinding.ContentTypeMapper = new MyRawMapper();
            //host.AddServiceEndpoint(typeof(IService), webBinding, "json").Behaviors.Add(new NewtonsoftJsonBehavior());
            //Console.WriteLine("Opening the host");
            //host.Open();

            //ChannelFactory<IService> factory = new ChannelFactory<IService>(new BasicHttpBinding(), new EndpointAddress(baseAddress + "/soap"));
            //IService proxy = factory.CreateChannel();
            //byte[] newdata;
            //TestClass c1 = new TestClass();
            //c1.a = "a";
            //List<TestClass> list1 = new List<TestClass>();
            //list1.Add(c1);
            //string strnewdata = JsonHelper.Serialize(list1);
            //newdata = Encoding.UTF8.GetBytes(strnewdata);
            //string newtestresult = HttpHelper.Post(@"http://localhost/Service/SOAFramework.Service.Server.DefaultService/DiscoverService", newdata);

            //Console.WriteLine("Now using the client formatter");
            //ChannelFactory<IService> newFactory = new ChannelFactory<IService>(webBinding, new EndpointAddress(baseAddress + "/json"));
            //newFactory.Endpoint.Behaviors.Add(new NewtonsoftJsonBehavior());
            //IService newProxy = newFactory.CreateChannel();

            //Console.WriteLine("Press ENTER to close");
            //Console.ReadLine();
            //host.Close();
            //Console.WriteLine("Host closed");
            #endregion

            #region wcf host
            WebServiceHost newhost = new WebServiceHost(typeof(SOAService));
            newhost.Open();
            newhost.Ping();
            #endregion

            #region zip tester
            string zip    = "i am a string, to be zipped!";
            string zipped = ZipHelper.Zip(zip, System.Text.Encoding.Default);
            zip = ZipHelper.UnZip(zipped);
            #endregion

            #region orm
            //string abc = Model.Users.Mapping.ColumnsMapping["PK_UserID"].ToString();
            //a c = new a();
            //c.b = "haha ";
            //c.t = new a();
            //c.t.b = "aaaaaa";
            //string str1 = JsonHelper.Serialize(c);

            //c = JsonHelper.Deserialize<a>(str1);

            //FTPClient f = new FTPClient();
            //f.FtpUrl = "ftp://localhost/";
            //f.FileName = "ha.txt";
            //f.UserName = "******";
            //f.Password = "******";
            //f.BufferSize = 10;
            //f.LocalFilePath = "e:";
            //f.Download();

            //sw.Stop();
            //Console.WriteLine("linq:" + sw.ElapsedTicks);
            //Model.Users objUser = new Model.Users();
            //Hashtable htArgs = new Hashtable();
            //htArgs["str"] = "ok";
            //WebServiceCaller wsCaller = new WebServiceCaller();
            //wsCaller.Action = "PostTest";
            //wsCaller.Args = htArgs;
            //wsCaller.Action = "GetTest";
            //wsCaller.WSUrl = @"http://*****:*****@"F:\TestOut.docx";
            //List<MethodArg> lstArg = new List<MethodArg>();
            //lstArg.Add(new MethodArg("there"));
            //cr.RequestData.MethodArgs = lstArg.ToArray();
            //cr.RequestType = WSDataType.JSON;
            //string str = cr.GetRequestString();
            //cr.ResponseType = WSDataType.JSON;
            //string strReturn = cr.SendRequest();
            //ServerResponse response = cr.GetResponse();
            //byte[] bytTemp = response.ResponseData;
            //Stream sw = File.Open(strFileName, FileMode.OpenOrCreate, FileAccess.Write);
            //sw.Write(bytTemp, 0, bytTemp.Length);
            //sw.Close();

            //Model.Users u = new Model.Users();
            //Model.Customer_AutoIncrease t = new Model.Customer_AutoIncrease();
            #endregion

            #region soa tester

            //testresult = HttpUtility.Get("http://localhost/Service/GetTest");

            argslist.Add(new SOAFramework.Service.SDK.Core.PostArgItem {
                Key = "url", Value = "http://localhost/"
            });
            //argslist.Add(new PostArgItem { Key = "usage", Value = "1.00" });
            strData = JsonHelper.Serialize("http://localhost/");
            //strData = "\"" + strData + "\"";
            data       = System.Text.Encoding.UTF8.GetBytes(strData);
            testresult = HttpHelper.Post(@"http://*****:*****@"http://localhost/Service/Execute/SOAFramework.Service.Server.DefaultService/DiscoverService", data);
            testresult = ZipHelper.UnZip(testresult);
            watch.Stop();
            Console.WriteLine("发现服务测试耗时{0}", watch.ElapsedMilliseconds);


            watch.Restart();
            argslist.Clear();
            strData    = JsonHelper.Serialize(argslist);
            data       = System.Text.Encoding.UTF8.GetBytes(strData);
            testresult = HttpHelper.Post(@"http://localhost/Service/Execute/SOAFramework.Service.Server.DefaultService/BigDataTest", data);
            watch.Stop();
            Console.WriteLine("大数据测试耗时{0}", watch.ElapsedMilliseconds);

            watch.Restart();
            //download test
            string filename = "预付款类型批量导入.xls";
            testresult = HttpHelper.Get(@"http://localhost/Service/Download/" + filename);
            //testresult = ZipHelper.UnZip(testresult);
            testresult.ToFile("D:\\" + filename);
            watch.Stop();
            Console.WriteLine("下载测试耗时{0}", watch.ElapsedMilliseconds);

            watch.Restart();
            //uploadtest
            string   uploadFileName = "D:\\预付款类型批量导入.xls";
            FileInfo file           = new FileInfo(uploadFileName);
            string   fileString     = file.FileToString();
            data       = System.Text.Encoding.UTF8.GetBytes(fileString);
            testresult = HttpHelper.Post(@"http://localhost/Service/Upload/" + file.Name, data);
            watch.Stop();
            Console.WriteLine("上传测试耗时{0}", watch.ElapsedMilliseconds);

            watch.Restart();
            int count = 10000;
            //for (int i = 0; i < count; i++)
            //{
            //    List<SOAFramework.Service.SDK.Core.PostArgItem> list = new List<SOAFramework.Service.SDK.Core.PostArgItem>();
            //    list.Add(new SOAFramework.Service.SDK.Core.PostArgItem { Key = "a", Value = JsonHelper.Serialize("hello world") });
            //    list.Add(new SOAFramework.Service.SDK.Core.PostArgItem { Key = "b", Value = JsonHelper.Serialize(new TestClass { a = "a", b = "b" }) });
            //    //list.Add(new PostArgItem { Key = "a", Value = "hello world" });
            //    //list.Add(new PostArgItem { Key = "b", Value = new TestClass { a = "a", b = "b" } });
            //    strData = JsonHelper.Serialize(list);
            //    data = System.Text.Encoding.UTF8.GetBytes(strData);
            //    //testresult = HttpHelper.Post(@"http://localhost/Service/Execute/SOAFramework.Service.Server.SOAService/Test", data);
            //    testresult = ZipHelper.UnZip(testresult);

            //    PerformanceRequest prequest = new PerformanceRequest();
            //    prequest.a = "hello world";
            //    prequest.b = new TestClass { a = "a", b = "b" };
            //    PerformanceResponse presponse = SDKFactory.Client.Execute(prequest);
            //}
            watch.Stop();
            Console.WriteLine("{1}次测试耗时{0}", watch.ElapsedMilliseconds, count);
            #endregion

            #region sdk testing
            //TestRequest request = new TestRequest();
            //TestResponse reseponse = SDKFactory.Client.Execute(request);
            #endregion

            Console.ReadLine();
        }
Exemple #6
0
        public SqlModel ObjectToSql(string tableName, IDictionary <string, object> o, IList <WhereClause> where, TableConfig config = null)
        {
            SqlModel         model        = new SqlModel();
            StringBuilder    prefix       = new StringBuilder();
            StringBuilder    whereBuilder = new StringBuilder();
            StringBuilder    sql          = new StringBuilder();
            List <Parameter> list         = new List <Parameter>();

            if (where == null)
            {
                where = new List <WhereClause>();
            }

            prefix.AppendFormat("UPDATE {0} SET ", tableName);
            foreach (var key in o.Keys)
            {
                if (key.StartsWith("__"))
                {
                    continue;
                }
                var column = config?.ColumnMapping?.Find(p => p.SourceColumn.ToLower().Equals(key.ToLower()));
                if (column != null && column.Ingore)
                {
                    continue;
                }
                var value = o[key];
                if (column != null && column.GenerateID)
                {
                    IIDGenerator generator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);
                    value = generator.Generate();
                }

                string columnName = Common.GetColumnName(key, column);
                if (string.IsNullOrEmpty(columnName))
                {
                    continue;
                }
                //生成配置在updatecolumn属性的列
                if (config != null && !string.IsNullOrEmpty(config.UpdateColumns))
                {
                    var updateColumnArr = config.UpdateColumns.Split(',');
                    if (!updateColumnArr.Any(p => p.ToLower().Equals(columnName.ToLower())))
                    {
                        continue;
                    }
                }
                //生成parameter
                Type t = null;
                if (value != null)
                {
                    t = Common.GetType(column?.DataType, value.GetType(), value);
                }
                if (column != null && column.Primarykey)
                {
                    try
                    {
                        if (value == null)
                        {
                            where.Add(new WhereClause {
                                ColumnName = columnName, Seperator = "=", Value = DBNull.Value, DataType = typeof(DBNull)
                            });
                        }
                        else
                        {
                            where.Add(new WhereClause {
                                ColumnName = columnName, Seperator = "=", Value = value.ChangeTypeTo(t), DataType = t
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        SimpleLogger logger = new SimpleLogger();
                        logger.Error(key);
                        throw ex;
                    }
                }
                else
                {
                    if (value == null)
                    {
                        prefix.AppendFormat("{0}=NULL,", Converter.FormatColumn(columnName));
                    }
                    else
                    {
                        try
                        {
                            if (string.IsNullOrEmpty(column?.FromSQL))
                            {
                                prefix.AppendFormat("{0}={1},", Converter.FormatColumn(columnName), Converter.FormatParameter(columnName));
                            }
                            else
                            {
                                prefix.AppendFormat("{0}=({1}),", Converter.FormatColumn(columnName), Converter.BuildTopN(column.FromSQL, 1));
                            }
                        }
                        catch (Exception ex)
                        {
                            SimpleLogger logger = new SimpleLogger();
                            logger.Write(key);
                            throw ex;
                        }
                        list.Add(new Parameter {
                            Name = Converter.FormatParameter(columnName), Value = value.ChangeTypeTo(t), Type = t
                        });
                    }
                }
            }
            //去掉最后一个逗号
            prefix.Remove(prefix.Length - 1, 1);
            var whereModel = Common.BuildWhere(where, Converter);

            sql.Append(prefix);
            if (!string.IsNullOrEmpty(whereModel.SQL))
            {
                sql.Append(" WHERE ");
            }
            sql.Append(whereModel.SQL);
            model.Parameters = Common.MergeParameter(list, whereModel.Parameters);
            model.SQL        = sql.ToString();
            return(model);
        }
Exemple #7
0
        public LoginResult Login(string userName, string password)
        {
            var             mapper   = Common.GetMapper();
            UserDao         userdao  = new UserDao(mapper);
            TokenDao        tokendao = new TokenDao(mapper);
            UserPasswordDao updao    = new UserPasswordDao(mapper);

            var ups = updao.Query(new UserPasswordQueryForm {
                UserName = userName, Password = password
            });

            if (ups == null || ups.Count == 0)
            {
                throw new XinLuClubException(102, "账号或者密码错误");
            }
            var users = userdao.Query(new UserQueryForm {
                Name = userName
            });

            if (users == null || users.Count == 0)
            {
                throw new XinLuClubException(103, "账号信息不存在");
            }
            var user   = users[0];
            var userid = user.ID;

            var tokens = tokendao.Query(new TokenQueryForm {
                UserID = userid
            });
            IIDGenerator generator   = IDGeneratorFactory.Create(GeneratorType.GUID);
            string       tokenstring = generator.Generate();
            Token        token       = null;

            if (tokens == null || tokens.Count == 0)
            {
                token = new Token
                {
                    ExpiredTime = DateTime.Now.AddHours(expiredHours),
                    UserID      = userid,
                    AccessToken = tokenstring,
                };
                tokendao.Add(token);
            }
            else
            {
                token             = tokens[0];
                token.ExpiredTime = DateTime.Now.AddHours(expiredHours);
                token.AccessToken = tokenstring;
                tokendao.Update(new TokenUpdateForm
                {
                    Entity = new Token
                    {
                        AccessToken = token.AccessToken,
                        ExpiredTime = token.ExpiredTime,
                    },
                    QueryForm = new TokenQueryForm
                    {
                        ID = token.ID,
                    }
                });
            }
            SaveMe(user);
            LoginResult result = new LoginResult
            {
                Token = token,
                User  = user,
            };

            return(result);
        }
Exemple #8
0
        public SqlModel ObjectToSql(string tableName, IDictionary <string, object> o, IList <WhereClause> where, TableConfig config = null)
        {
            SqlModel      model  = new SqlModel();
            StringBuilder sql    = new StringBuilder();
            StringBuilder prefix = new StringBuilder();
            StringBuilder values = new StringBuilder();

            List <Parameter> list = new List <Parameter>();

            prefix.AppendFormat("INSERT INTO {0} (", tableName);
            values.Append(" VALUES(");
            foreach (var key in o.Keys)
            {
                if (key.StartsWith("__"))
                {
                    continue;
                }
                var column = config?.ColumnMapping?.Find(p => p.SourceColumn.ToLower().Equals(key.ToLower()));
                if (column != null && column.Ingore)
                {
                    continue;
                }
                string columnName = Common.GetColumnName(key, column);
                if (string.IsNullOrEmpty(columnName))
                {
                    continue;
                }
                var value = o[key];
                if (column != null && column.GenerateID && value == null)
                {
                    IIDGenerator generator = IDGeneratorFactory.Create(GeneratorType.SnowFlak);
                    value = generator.Generate();
                }
                if (value == null)
                {
                    continue;
                }
                prefix.AppendFormat("{0},", Converter.FormatColumn(columnName));
                if (string.IsNullOrEmpty(column?.FromSQL))
                {
                    values.AppendFormat("{0},", Converter.FormatParameter(columnName));
                }
                else
                {
                    values.AppendFormat("({0}),", Converter.BuildTopN(column.FromSQL, 1));
                }
                Parameter param;
                Type      t = Common.GetType(column?.DataType, value.GetType(), value);
                try
                {
                    param = new Parameter {
                        Name = string.Format("{0}", Converter.FormatParameter(columnName)), Value = value.ChangeTypeTo(t), Type = t
                    };
                }
                catch (Exception ex)
                {
                    SimpleLogger logger = new SimpleLogger();
                    logger.Error(key);
                    throw ex;
                }
                list.Add(param);
            }
            //去掉最后一个逗号
            prefix.Remove(prefix.Length - 1, 1);
            values.Remove(values.Length - 1, 1);

            prefix.Append(")");
            values.Append(")");
            sql.Append(prefix.ToString()).Append(values.ToString());
            model.SQL        = sql.ToString();
            model.Parameters = list;
            return(model);
        }