예제 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="requestinterval">请求次数时间间隔</param>
        /// <param name="successtype">返回成功类型</param>
        /// <param name="successinterval">返回成功时间间隔</param>
        /// <param name="errortype">返回失败类型</param>
        /// <param name="errorinterval">返回失败时间间隔</param>
        /// <returns></returns>
        private string GetServiceState(string requestinterval, string successtype, string successinterval, string errortype, string errorinterval)
        {
            Hashtable map = new Hashtable();

            try
            {
                DataTable       dtTable1 = new DataTable();
                DataTable       dtTable2 = new DataTable();
                DataTable       dtTable3 = new DataTable();
                SqlserverHelper helper   = new SqlserverHelper();
                dtTable1 = helper.GetRequestNumber(requestinterval);
                dtTable2 = helper.GetSuccessResponseNumber(successtype, successinterval);
                dtTable3 = helper.GetErrorResponseNumber(errortype, errorinterval);
                Hashtable datamap = new Hashtable();
                datamap.Add("country", dtTable1);
                datamap.Add("province", dtTable2);
                datamap.Add("county", dtTable3);
                map.Add("data", datamap);
                map.Add("state", "成功");
                map.Add("msg", "");
            }
            catch (Exception ex)
            {
                Log4Helper.Debug(ex.Message, ex);
                map.Add("state", "失败");
                map.Add("msg", ex.Message);
            }
            string json = JsonConvert.SerializeObject(map);

            return(json);
        }
예제 #2
0
 private void ThreadSqlHelper()//请求写入数据库
 {
     while (true)
     {
         try
         {
             long result1 = SqlserverHelper.OnlineRequest(requestnumber);
             long result2 = SqlserverHelper.FailResponse(rediserrorlist, "redis");
             long result3 = SqlserverHelper.FailResponse(foldererrorlist, "folder");
             long result4 = SqlserverHelper.FailResponse(weberrorlist, "web");
             long result5 = SqlserverHelper.SuccessResponse(redissuccesslist, "redis");
             long result6 = SqlserverHelper.SuccessResponse(foldersuccesslist, "folder");
             long result7 = SqlserverHelper.SuccessResponse(websuccesslist, "web");
             if (result1 < 1)
             {
                 Log4Helper.WriteLog("统计在线请求插入失败," + DateTime.Now);
             }
             if (result2 < 1)
             {
                 Log4Helper.WriteLog("redis失败请求插入失败," + DateTime.Now);
             }
             if (result3 < 1)
             {
                 Log4Helper.WriteLog("folder失败请求插入失败," + DateTime.Now);
             }
             if (result4 < 1)
             {
                 Log4Helper.WriteLog("web失败请求插入失败," + DateTime.Now);
             }
             if (result5 < 1)
             {
                 Log4Helper.WriteLog("redis成功请求插入失败," + DateTime.Now);
             }
             if (result6 < 1)
             {
                 Log4Helper.WriteLog("folder成功请求插入失败," + DateTime.Now);
             }
             if (result7 < 1)
             {
                 Log4Helper.WriteLog("web成功请求插入失败," + DateTime.Now);
             }
         }
         catch (Exception ex)
         {
             Log4Helper.WriteLog(ex.ToString());
         }
         finally
         {
             requestnumber     = 0;
             rediserrorlist    = 0;
             foldererrorlist   = 0;
             weberrorlist      = 0;
             redissuccesslist  = 0;
             foldersuccesslist = 0;
             websuccesslist    = 0;
             //没有任务,休息5秒钟  
             Thread.Sleep(Timespace);
         }
     }
 }
예제 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="daylength">时间长度(天为单位)</param>
        /// <returns></returns>
        private string DeleteResponse(string daylength)
        {
            Hashtable map     = new Hashtable();
            int       request = 0;
            int       success = 0;
            int       fail    = 0;
            int       day     = int.Parse(daylength);

            try
            {
                SqlserverHelper helper = new SqlserverHelper();
                request = helper.DeleteOnline(day);
                success = helper.DeleteSuccess(day);
                fail    = helper.DeleteFail(day);
                map.Add("state", "成功");
                map.Add("msg", "");
            }
            catch (Exception ex)
            {
                Log4Helper.Debug(ex.Message, ex);
                map.Add("state", "失败");
                map.Add("msg", ex.Message);
            }
            map.Add("request", request);
            map.Add("success", success);
            map.Add("fail", fail);
            string json = JsonConvert.SerializeObject(map);

            return(json);
        }
예제 #4
0
        private void GetErrorResponseNumber(HttpContext context)
        {
            Hashtable map     = new Hashtable();
            DataTable dtTable = new DataTable();
            string    type    = HttpUtility.UrlDecode(context.Request["type"]);
            string    error   = HttpUtility.UrlDecode(context.Request["error"]);

            try
            {
                SqlserverHelper helper = new SqlserverHelper();
                dtTable = helper.GetErrorResponseNumber(type, error);
                map.Add("state", "成功");
                map.Add("msg", "");
            }
            catch (Exception ex)
            {
                Log4Helper.Debug(ex.Message, ex);
                map.Add("state", "失败");
                map.Add("msg", ex.Message);
            }
            map.Add("data", dtTable);
            string json = JsonConvert.SerializeObject(map);

            context.Response.Write(json);
        }
예제 #5
0
        private void cmbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDatabase.SelectedItem != null && cmbDatabase.SelectedItem.ToString() != TipsDB)
            {
                //保存最后使用项
                var config = ConfigHelper.GetConfig <AppConfig>();
                config.LastDb = cmbDatabase.SelectedItem.ToString();
                ConfigHelper.UpdateConfig(config);

                //联动加载表
                var id = cmbDatabase.SelectedItem.ToString().Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0];
                listBox.Items.Clear();
                //listBox.Items.Add(TipsDbTable);

                var thread = new Thread(() =>
                {
                    UpdateUI(() => { lblStatus.Text = "正在读取数据库架构,请稍候..."; });
                    var conn   = FormDbService.GetConnectionString(Convert.ToInt32(id));
                    var tables = SqlserverHelper.GetTableNames(conn);
                    if (tables.Count > 0)
                    {
                        if (tables[0] == "Error")
                        {
                            UpdateUI(() => { lblStatus.Text = "数据库连接失败,请检查数据连接配置是否正确"; });
                        }
                        else
                        {
                            UpdateUI(() =>
                            {
                                foreach (var s in tables)
                                {
                                    listBox.Items.Add(s);
                                }

                                lblStatus.Text        = "共" + listBox.Items.Count + "张表";
                                listBox.SelectedIndex = 0;
                            });
                        }
                    }
                })
                {
                    IsBackground = true
                };
                thread.Start();
            }
        }
예제 #6
0
        private void DeleteResponse(string daylength)
        {
            int request = 0;
            int success = 0;
            int fail    = 0;
            int day     = int.Parse(daylength);

            try
            {
                SqlserverHelper helper = new SqlserverHelper();
                request = helper.DeleteOnline(day);
                success = helper.DeleteSuccess(day);
                fail    = helper.DeleteFail(day);
            }
            catch (Exception ex)
            {
                Log4Helper.Debug(ex.Message, ex);
            }
        }
예제 #7
0
        private void BtnDocument_Click(object sender, EventArgs e)
        {
            string connection = GetConnectionString();

            var dbName = new Regex(
                "(?i)(database|Initial Catalog)=(?<db>[^;]*?);",
                RegexOptions.CultureInvariant
                | RegexOptions.Compiled
                ).Match(connection).Groups["db"].Value;

            if (!string.IsNullOrEmpty(connection))
            {
                var threadDelegate = new ThreadStart(delegate
                {
                    var sw = new Stopwatch();
                    sw.Start();
                    Invoke(new MethodInvoker(() =>
                    {
                        btnDel.Enabled      = false;
                        btnSave.Enabled     = false;
                        btnTest.Enabled     = false;
                        BtnDocument.Enabled = false;

                        lblStatus.Text = @"处理中,请稍候...";
                    }));

                    List <TableInfo> tables = SqlserverHelper.GetTables(connection);
                    var tempalte            = PathHelper.AppPath.Combine("DbDocument").Combine("table.html");

                    //文档存放路径
                    var savePath       = Environment.GetFolderPath(Environment.SpecialFolder.Desktop).Combine(dbName + "-数据库文档");
                    var saveTablesPath = savePath.Combine("tables");
                    try
                    {
                        if (Directory.Exists(savePath))
                        {
                            FileHelper.DeleteFolder(savePath);
                        }

                        if (!Directory.Exists(saveTablesPath))
                        {
                            Directory.CreateDirectory(saveTablesPath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Invoke(new MethodInvoker(() =>
                        {
                            btnDel.Enabled      = true;
                            btnSave.Enabled     = true;
                            btnTest.Enabled     = true;
                            BtnDocument.Enabled = true;
                            lblStatus.Text      = @"初始化文档存放目录异常:" + ex.Message;
                            MessageBox.Show(ex.Message, "提示信息");
                        }));
                    }

                    var config                             = ConfigHelper.GetConfig <AppConfig>();
                    ITemplate template                     = BuildManager.CreateTemplate(tempalte);
                    template.Context.CurrentPath           = PathHelper.AppPath.Combine("DbDocument");
                    template.Context.TempData["datetime"]  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    template.Context.TempData["conn"]      = connection;
                    template.Context.TempData["author"]    = config.Author;
                    template.Context.TempData["namespace"] = config.NameSpace;
                    var count = 0;
                    foreach (TableInfo table in tables)
                    {
                        count++;
                        var tableName = table.TableName;

                        #region 表实体

                        string className = table.TableName.Contains("_")
                                               ? tableName.Substring(tableName.LastIndexOf("_", StringComparison.Ordinal) + 1)
                                               : tableName;
                        string note   = SqlserverHelper.GetTableNote(connection, tableName);
                        var tableInfo = new TableInfo
                        {
                            TableNote = note,
                            ClassName = className,
                            TableName = tableName
                        };

                        #endregion

                        #region 字段

                        List <FieldInfo> fieldList = SqlserverHelper.GetFieldInfoList(connection, tableName);
                        var list    = new List <FieldInfo>();
                        var excepts = new List <string>();
                        excepts.AddRange(config.ExceptFields.Replace(",", ",").ToLower().Trim().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries));
                        foreach (FieldInfo fieldInfo in fieldList)
                        {
                            if (!excepts.Contains(fieldInfo.Name.ToLower()))
                            {
                                list.Add(fieldInfo);
                            }
                            if (fieldInfo.IsPrimaryKey)
                            {
                                tableInfo.PrimaryKey = fieldInfo.Name;
                            }
                        }
                        #endregion

                        template.Context.TempData["table"]  = tableInfo;
                        template.Context.TempData["fields"] = list;

                        string html = template.Render();
                        var path    = saveTablesPath.Combine(table.TableName + ".html");
                        FileHelper.WriteFile(path, html, Encoding.UTF8);
                        Invoke(new MethodInvoker(() => { lblStatus.Text = @"正在生成(" + count + "/" + tables.Count + "):" + tableName; }));
                    }

                    //生成首页
                    var indexPath = PathHelper.AppPath.Combine("DbDocument").Combine("index.html");
                    var txt       = FileHelper.ReadFile(indexPath, Encoding.Default);

                    var tableHtml = "";
                    foreach (TableInfo table in tables)
                    {
                        tableHtml += "<li><span class=\"file\"><a href=\"tables/" + table.TableName + ".html\" target=\"right\">" + table.TableName + "</a></span></li>" + Environment.NewLine;
                    }
                    txt = txt.Replace("{$tables}", tableHtml);
                    txt = txt.Replace("{$dataBase}", dbName.Trim());
                    FileHelper.WriteFile(savePath.Combine("index.html"), txt, Encoding.UTF8);

                    //主框架页
                    var mainPath = PathHelper.AppPath.Combine("DbDocument").Combine("main.html");
                    txt          = FileHelper.ReadFile(mainPath, Encoding.Default);
                    txt          = txt.Replace("{$tables}", tableHtml);
                    txt          = txt.Replace("{$dataBase}", dbName.Trim());
                    txt          = txt.Replace("{$tableCount}", tables.Count.ToString());
                    txt          = txt.Replace("{$createuser}", config.Author.Trim());
                    txt          = txt.Replace("{$datetime}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    FileHelper.WriteFile(savePath.Combine("main.html"), txt, Encoding.UTF8);

                    //样式文件
                    FileHelper.CopyDirectory(PathHelper.AppPath.Combine("DbDocument").Combine("style"), savePath.Combine("style"));
                    FileHelper.CopyDirectory(PathHelper.AppPath.Combine("DbDocument").Combine("script"), savePath.Combine("script"));
                    sw.Stop();
                    TimeSpan ts        = sw.Elapsed;
                    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

                    Invoke(new MethodInvoker(() =>
                    {
                        btnDel.Enabled      = true;
                        btnSave.Enabled     = true;
                        btnTest.Enabled     = true;
                        BtnDocument.Enabled = true;
                        lblStatus.Text      = @"生成成功,文件已保存到:" + savePath + " 耗时:" + elapsedTime;
                        Help.ShowHelp(this, savePath.Combine("index.html"));
                    }));
                });
                new Thread(threadDelegate).Start();
            }
            else
            {
                lblStatus.Text = @"抱歉,数据库连接字符串构造异常";
            }
        }
예제 #8
0
        public static string CreateCode(int dbId, string tableName, string templateFile)
        {
            var sw = new Stopwatch();

            sw.Start();
            var config = ConfigHelper.GetConfig <AppConfig>();
            var con    = FormDbService.GetConnectionString(dbId);

            var template = BuildManager.CreateTemplate(templateFile);

            #region 表实体

            var className = tableName.Contains("_")
                ? tableName.Substring(tableName.LastIndexOf("_", StringComparison.Ordinal) + 1)
                : tableName;
            var classChineseName = SqlserverHelper.GetTableNote(con, tableName);
            var tableInfo        = new TableInfo
            {
                TableNote = classChineseName,
                ClassName = className,
                TableName = tableName
            };

            #endregion

            #region 字段

            var fieldList = SqlserverHelper.GetFieldInfoList(con, tableName);
            var list      = new List <FieldInfo>();
            var except    = config.ExceptFields ?? "";
            var excepts   = except.Replace(",", ",").ToLower().Trim().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var fieldInfo in fieldList)
            {
                if (!excepts.Contains(fieldInfo.Name.ToLower()))
                {
                    list.Add(fieldInfo);
                }
                if (fieldInfo.IsPrimaryKey)
                {
                    tableInfo.PrimaryKey = fieldInfo.Name;
                }
            }

            #endregion

            #region 加载模板内置对象

            Dictionary <string, PresentBase> tempData = new Dictionary <string, PresentBase>();
            if (tempData.Count <= 0)
            {
                Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (Assembly assembly in assemblies)
                {
                    //反射调用展现层类库
                    if (assembly.FullName.Contains("RC.Software.Presentation"))
                    {
                        Type[] classes = assembly.GetTypes();
                        foreach (Type type in classes)
                        {
                            if (IsInherit(type, typeof(PresentBase)))
                            {
                                string name     = type.Name.ToLower();
                                var    instance = Activator.CreateInstance(type) as PresentBase;
                                tempData.Add(name, instance);
                            }
                        }
                    }
                }
            }
            foreach (var pair in tempData)
            {
                template.Context.TempData[pair.Key] = pair.Value;
            }

            #endregion

            template.Context.CurrentPath           = templateFile;
            template.Context.TempData["datetime"]  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            template.Context.TempData["conn"]      = con;
            template.Context.TempData["table"]     = tableInfo;
            template.Context.TempData["fields"]    = list;
            template.Context.TempData["author"]    = config.Author ?? "";
            template.Context.TempData["namespace"] = config.NameSpace ?? "";

            #region 内置标签方法 (动态加载)

            object insideStaticLabel = null;
            try
            {
                const string insideClassName = "RC.Software.Presentation.InsideStaticLabel";
                string       fileName        = Path.Combine(Thread.GetDomain().BaseDirectory, @"InsideStaticLabel.cs");

                if (File.Exists(fileName))
                {
                    var             sourceFile = new FileInfo(fileName);
                    CodeDomProvider provider   = new CSharpCodeProvider();
                    var             cp         = new CompilerParameters();
                    cp.ReferencedAssemblies.Add("System.dll");                   //添加命名空间引用
                    cp.ReferencedAssemblies.Add("RC.Software.Presentation.dll"); //添加命名空间引用
                    cp.ReferencedAssemblies.Add("RC.Software.Framework.dll");

                    cp.GenerateExecutable    = false; // 生成类库
                    cp.GenerateInMemory      = true;  // 保存到内存
                    cp.TreatWarningsAsErrors = false; // 不将编译警告作为错误

                    // 编译
                    CompilerResults results = provider.CompileAssemblyFromFile(cp, sourceFile.FullName);
                    if (results.Errors.Count < 1)
                    {
                        Assembly asm = results.CompiledAssembly;                 // 加载
                        insideStaticLabel = asm.CreateInstance(insideClassName); //获取编译后的类型
                    }
                    else
                    {
                        string msg = null;
                        for (int index = 0; index < results.Errors.Count; index++)
                        {
                            CompilerError error = results.Errors[index];
                            msg += "【错误" + (index + 1) + "】" + Environment.NewLine;
                            msg += "[文件] " + error.FileName + Environment.NewLine;
                            msg += "[位置] 行" + error.Line + ",列" + error.Column + Environment.NewLine;
                            msg += "[信息] " + error.ErrorText + Environment.NewLine;
                            msg += Environment.NewLine;
                        }
                        MessageBox.Show(msg, "内置方法类编译错误");
                    }
                }
            }
            catch
            {
                //如果用户文件写的有问题,用系统内置的标签方法
                if (insideStaticLabel == null)
                {
                    insideStaticLabel = new InsideStaticLabel();
                }
            }
            if (insideStaticLabel == null)
            {
                insideStaticLabel = new InsideStaticLabel();
            }
            template.Context.TempData["rc"] = insideStaticLabel;

            #endregion

            var html = template.Render();
            return(html);
        }