首页
归档
留言
友链
广告合作
壁纸
更多
美女主播
Search
1
博瑞GE车机升级/降级
5,649 阅读
2
Mac打印机设置黑白打印
5,043 阅读
3
修改elementUI中el-table树形结构图标
4,946 阅读
4
Mac客户端添加腾讯企业邮箱方法
4,705 阅读
5
intelliJ Idea 2022.2.X破解
4,454 阅读
后端开发
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
登录
/
注册
Search
标签搜索
Spring Boot
Java
Vue
Mac
Spring Cloud
MyBatis
WordPress
MacOS
asp.net
Element UI
Nacos
MySQL
.Net
Spring Cloud Alibaba
Mybatis-Plus
Typecho
jQuery
Java Script
IntelliJ IDEA
微信小程序
Laughing
累计撰写
629
篇文章
累计收到
1,421
条评论
首页
栏目
后端开发
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
页面
归档
留言
友链
广告合作
壁纸
美女主播
搜索到
225
篇与
的结果
2018-10-21
解决Oracle in 超过1000个问题 C#拼接字符串
private string getOracleSQLIn(string[] ids, string field) { int count = Math.Min(ids.Length, 1000); int len = ids.Length; int size = len % count; if (size == 0) { size = len / count; } else { size = (len / count) + 1; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < size; i++) { int fromIndex = i * count; int toIndex = Math.Min(fromIndex + count, len); string productId = string.Join("','", getArrayValues(fromIndex, toIndex, ids).ToArray()); if (i != 0) { builder.Append(" or "); } builder.Append(field).Append(" in ('").Append(productId).Append("')"); } return builder.ToString(); } public List<string> getArrayValues(int fromindex, int toindex, string[] array) { List<string> listret = new List<string>(); for (int i = fromindex; i < toindex; i++) { listret.Add(array[i]); } return listret; }
2018年10月21日
1,124 阅读
0 评论
0 点赞
2018-10-14
python异常之else代码块
通过将可能引发错误的代码放在try-except 代码块中,可提高这个程序抵御错误的能力。错误是执行除法运算的代码行导致的,因此我们需要将它放到try-except 代码块中。这个示例还包含一个else 代码块;依赖于try 代码块成功执行的代码都应放到else 代码块中:try: answer = 5/1 except ZeroDivisionError as e: print('不能除零') else: print(answer)try-except-else 代码块的工作原理大致如下:Python尝试执行try代码块中的代码;只有可能引发异常的代码才需要放在try语句中。有时候,有一些仅在try 代码块成功 执行时才需要运行的代码这些代码应放在else代码块中。except代码块告诉Python,如果它尝试运行try代码块中的代码时引发了指定的异常,该怎么办。
2018年10月14日
1,080 阅读
0 评论
0 点赞
2018-10-04
sqlalchemy 连接数据库出现 No module named 'MySQL'
问题再现使用sqlalchemy调用MySql时,连接信息一开始是这么写的engine = create_engine('mysql+mysqlconnector://账户:密码@域名或IP:端口/数据库') 问题分析出现问题的原因就在于红色的部分,使用了mysqlconnector进行连接,在python3中,我们改用pymysql进行连接。问题解决安装pymysqlpip install pymysql修改数据库连接信息engine = create_engine('mysql+pymysql://账户:密码@域名或IP:端口/数据库')
2018年10月04日
1,260 阅读
0 评论
0 点赞
2018-10-04
python生成验证码
依赖PILpip install pillow公共方法import hashlib import random import string from PIL import Image, ImageFont, ImageDraw, ImageFilter from flask import Flask app = Flask(__name__) app.config.from_object("config.DevelopmentConfig") # 从config.py读入配置 def rndColor(): """随机颜色""" return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127) def gene_text(): """生成4位验证码""" return ''.join(random.sample(string.ascii_letters + string.digits, 4)) def draw_lines(draw, num, width, height): """划线""" for num in range(num): x1 = random.randint(0, width / 2) y1 = random.randint(0, height / 2) x2 = random.randint(0, width) y2 = random.randint(height / 2, height) draw.line(((x1, y1), (x2, y2)), fill='black', width=1) def get_verify_code(): """生成验证码图形""" code = gene_text() # 图片大小120×50 width, height = 100, 40 # 新图片对象 im = Image.new('RGB', (width, height), 'white') # 字体 font = ImageFont.truetype('app/static/arial.ttf', 30) # draw对象 draw = ImageDraw.Draw(im) # 绘制字符串 for item in range(4): draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)), text=code[item], fill=rndColor(), font=font) # 划线 draw_lines(draw, 2, width, height) # 高斯模糊 im = im.filter(ImageFilter.GaussianBlur(radius=1.5)) return im, code def salted_password(password): salt = app.config.get('SALT_KEY') hsobj = hashlib.sha256(salt.encode("utf-8")) hsobj.update(password.encode("utf-8")) return hsobj.hexdigest().upper() 调用from app import app from flask import render_template, request, session, redirect, make_response,url_for,flash from app import db from app.functions import get_verify_code, salted_password import re from app.models import Users,UsersJson,Menus,MenuDto import datetime from io import BytesIO from app.PubFunc.EmailHelp import EmailCls import json from datetime import timedelta import threading @app.route('/code') def get_code(): image, code = get_verify_code() # 图片以二进制形式写入 buf = BytesIO() image.save(buf, 'jpeg') buf_str = buf.getvalue() # 把buf_str作为response返回前端,并设置首部字段 response = make_response(buf_str) response.headers['Content-Type'] = 'image/gif' # 将验证码字符串储存在session中 session['verifyCode'] = code return response @app.route('/') def main(): if 'userName' not in session or session['userName'] == None or session['userName'] == '': return redirect('login') # email = EmailCls() # emailInfo = email.getEmail() # t= threading.Thread(target=email.getEmail) # t.setDaemon(True) # t.start() # t.join() menus = test_set_subMenus() return render_template('index.html',userinfo=json.loads(session['userinfo']),emailInfo=None,menus=menus) @app.route('/logout') def logout(): session.clear return redirect('/login') @app.route('/login', methods=['GET', 'POST']) def login(): if (request.method == 'GET'): return render_template('login.html') else: username = request.form.get('userlogin') password = request.form.get('loginpassword') verifyCode = request.form.get('loginverifycode') rememberme = request.form.get('rememberme') remembermemonth = request.form.get('remembermemonth') if rememberme=='on': app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) #配置7天有效 session.permanent = timedelta(days=7) if remembermemonth=='on': app.config['PERMANENT_SESSION_LIFETIME'] = True # 长期有效,一个月的时间有效 session.permanent = True # 长期有效,一个月的时间有效 if 'verifyCode' not in session or session['verifyCode'] == None or session['verifyCode'] == '': return redirect('login') if verifyCode == None or verifyCode == '': return '请输入验证码' if verifyCode.upper() != session['verifyCode'].upper(): return '验证码输入不正确' if username == None or username == '': return '请输入用户名' if password == None or password == '': return '请输入密码' user = db.session.query(Users).filter_by(user_login=username).first() if user == None: return '当前用户尚未注册' if not user.user_pass == salted_password(password): return '密码输入不正确' session['userName'] = username session['userinfo']=json.dumps(user,default=UsersJson) return redirect('/') @app.route('/register', methods=['POST', ]) def register(): username = request.form.get('regusername') password = request.form.get('regpassword') verifyCode = request.form.get('regverifycode') userEmail = request.form.get('regemail') if username == None or username == '': return '请输入用户名' if userEmail == None or userEmail == '': return '请输入邮箱' if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net,me,org,com.cn.cc.co]{1,3}$', userEmail): return '邮箱格式不正确' if password == None or password == '': return '请输入密码' if verifyCode.upper() != session['verifyCode'].upper(): return '验证码输入不正确' user = Users() user.user_login = username user.user_email = userEmail user.user_pass = salted_password(password) user.user_nicename = username user.user_registered = datetime.datetime.now() user.user_status = 1 user.display_name = username sql = 'SELECT 1 FROM Users where user_login=:username or user_email=:user_email' userExist = db.session.execute(sql, {'username': username, 'user_email': userEmail}) if len(userExist.fetchall()) > 0: return '当前用户已存在或者邮箱已被注册' db.session.add(user) db.session.commit() return redirect('/') @app.route('/welcome_iframe.html') def elements(): return render_template('welcome_iframe.html') @app.route('/UI/buttons_iframe.html') def buttons(): return render_template('UI/buttons_iframe.html') @app.route('/UI/general_iframe.html') def general_iframe(): return render_template('UI/general_iframe.html') @app.route('/UI/icons_iframe.html') def icons_iframe(): return render_template('UI/icons_iframe.html') @app.route('/UI/modals_iframe.html') def modals_iframe(): return render_template('UI/modals_iframe.html') @app.route('/UI/sliders_iframe.html') def sliders_iframe(): return render_template('UI/sliders_iframe.html') @app.route('/UI/timeline_iframe.html') def timeline_iframe(): return render_template('UI/timeline_iframe.html') def queryByParent(parentid): menus = db.session.query(Menus).filter_by(parentid=parentid).all() return menus def set_subMenus(id, menus): """ 根据传递过来的父菜单id,递归设置各层次父菜单的子菜单列表 :param id: 父级id :param menus: 子菜单列表 :return: 如果这个菜单没有子菜单,返回None;如果有子菜单,返回子菜单列表 """ # 记录子菜单列表 subMenus = [] # 遍历子菜单 for m in menus: if m.parentid == id: subMenus.append(m) # 把子菜单的子菜单再循环一遍 for sub in subMenus: menus2 = queryByParent(sub.id) # 还有子菜单 if len(menus): sub.subMenus = set_subMenus(sub.id, menus2) # 子菜单列表不为空 if len(subMenus): return subMenus else: # 没有子菜单了 return None def test_set_subMenus(): # 一级菜单 rootMenus = queryByParent('0') for menu in rootMenus: subMenus = queryByParent(menu.id) menu.subMenus = set_subMenus(menu.id, subMenus) jsonData = json.dumps(rootMenus,default=MenuDto,ensure_ascii=False) return jsonData 前台<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>开发框架</title> <meta name="keywords" content="开发框架" /> <meta name="description" content="开发框架" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- basic styles --> <link href="/static/css/bootstrap.min.css" rel="stylesheet" /> <link rel="stylesheet" href="/static/css/font-awesome.min.css" /> <link rel="shortcut icon" href="/static/img/favicon.ico"/> <link rel="stylesheet" href="/static/css/font.googleapis.com.css" /> <link rel="stylesheet" href="/static/css/ace.min.css" /> <link rel="stylesheet" href="/static/css/ace-rtl.min.css" /> </head> <body class="login-layout"> <div class="main-container"> <div class="main-content"> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <div class="login-container"> <div class="center"> <h1> <i class="fa fa-leaf green"></i> <a href="https://www.erpdev.cn"><span class="red">ErpDev.Cn</span></a> <br/> <span class="white">基于Python的开发框架</span> </h1> <h4 class="blue">©copy; <a href="https://lisen.cc">李森的博客</a></h4> </div> <div class="space-6"></div> <div class="position-relative"> <div id="login-box" class="login-box visible widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <h4 class="header blue lighter bigger"> <i class="icon-coffee green"></i> 请输入个人信息 </h4> <div class="space-6"></div> <form action="{{ url_for("login") }}" method="post" name="loginform" id="loginform"> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="text" id="userlogin" name="userlogin" class="form-control" placeholder="请输入用户名" required minlength="4" maxlength="30" /> <i class="icon-user"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="password" id="loginpassword" name="loginpassword" class="form-control" placeholder="请输入密码" required minlength="8" /> <i class="icon-lock"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <div class="row"> <div class="col-sm-4 col-xs-4"> <img id="loginverifycodeImg" src="/code" /> </div> <div class="col-sm-8 col-xs-8"> <input type="text" id="loginverifycode" name="loginverifycode" class="form-control" placeholder="请输入验证码" required minlength="4" maxlength="4" /> </div> </div> <i class="icon-lock"></i> </span> </label> <div class="space"></div> <div class="clearfix"> <label class="inline"> <input type="checkbox" class="ace" id="rememberme" name="rememberme"/> <span class="lbl">记住我(7天)</span> </label> <label class="inline"> <input type="checkbox" class="ace" id="remembermemonth" name="remembermemonth"/> <span class="lbl">记住我(1个月)</span> </label> <button type="submit" class="width-35 pull-right btn btn-sm btn-primary"> <i class="icon-key"></i> 登录 </button> </div> <div class="space-4"></div> </fieldset> </form> <div class="social-or-login center"> <span class="bigger-110">通过以下方式登录</span> </div> <div class="social-login center"> <a class="btn btn-primary"> <i class="fa fa-qq"></i> </a> <a class="btn btn-info"> <i class="fa fa-wechat"></i> </a> <a class="btn btn-danger"> <i class="fa fa-weibo"></i> </a> </div> </div><!-- /widget-main --> <div class="toolbar clearfix"> <div> <a href="#" onclick="show_box('forgot-box'); return false;" class="forgot-password-link"> <i class="icon-arrow-left"></i> 忘记密码? </a> </div> <div> <a href="#" onclick="show_box('signup-box'); return false;" class="user-signup-link"> 注册 <i class="icon-arrow-right"></i> </a> </div> </div> </div><!-- /widget-body --> </div><!-- /login-box --> <div id="forgot-box" class="forgot-box widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <h4 class="header red lighter bigger"> <i class="icon-key"></i> 找回密码 </h4> <div class="space-6"></div> <p> 请输入邮箱 </p> <form> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="email" class="form-control" placeholder="邮箱" /> <i class="icon-envelope"></i> </span> </label> <div class="clearfix"> <button type="button" class="width-35 pull-right btn btn-sm btn-danger"> <i class="icon-lightbulb"></i> 发送 </button> </div> </fieldset> </form> </div><!-- /widget-main --> <div class="toolbar center"> <a href="#" onclick="show_box('login-box'); return false;" class="back-to-login-link"> 登录 <i class="icon-arrow-right"></i> </a> </div> </div><!-- /widget-body --> </div><!-- /forgot-box --> <div id="signup-box" class="signup-box widget-box no-border"> <div class="widget-body"> <div class="widget-main"> <h4 class="header green lighter bigger"> <i class="icon-group blue"></i> 注册 </h4> <div class="space-6"></div> <p> 请输入个人信息: </p> <form action="register" method="POST"> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="email" id="regemail" name="regemail" class="form-control" placeholder="请输入邮箱" required maxlength="100" /> <i class="icon-envelope"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="text" id="regusername" name="regusername" class="form-control" placeholder="请输入用户名" required maxlength="30" minlength="4" /> <i class="icon-user"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="password" id="regpassword" name="regpassword" class="form-control" placeholder="请输入密码" required minlength="8" maxlength="100" /> <i class="icon-lock"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <input type="password" id="regcomfirmpassword" name="regcomfirmpassword" class="form-control" placeholder="请再次输入密码" required equalTo:"#regpassword" /> <i class="icon-retweet"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <div class="row"> <div class="col-sm-4 col-xs-4"> <img src="/code" /> </div> <div class="col-sm-8 col-xs-8"> <input type="text" id="regverifycode" name="regverifycode" class="form-control" placeholder="验证码" required="true" maxlength="4" minlength="4" /> </div> </div> <i class="icon-lock"></i> </span> </label> <label class="block"> <input type="checkbox" class="ace" required /> <span class="lbl"> 我同意 <a href="#">用户协议</a> </span> </label> <div class="space-24"></div> <div class="clearfix"> <button type="reset" class="width-30 pull-left btn btn-sm"> <i class="icon-refresh"></i> 取消 </button> <button type="submit" class="width-65 pull-right btn btn-sm btn-success"> 注册 <i class="icon-arrow-right icon-on-right"></i> </button> </div> </fieldset> </form> </div> <div class="toolbar center"> <a href="#" onclick="show_box('login-box'); return false;" class="back-to-login-link"> <i class="icon-arrow-left"></i> 登录 </a> </div> </div><!-- /widget-body --> </div><!-- /signup-box --> </div><!-- /position-relative --> </div> </div><!-- /.col --> </div><!-- /.row --> </div> </div><!-- /.main-container --> <!-- basic scripts --> <!--[if !IE]> --> <script type="text/javascript"> window.jQuery || document.write("<script src='/static/js/jQuery/jquery-2.2.3.min.js'>"+"<"+"/script>"); </script> <script type="text/javascript" src="/static/js/jQuery/jquery.validate.min.js"></script> <!-- <![endif]--> <!--[if IE]> <script type="text/javascript"> window.jQuery || document.write("<script src='/static/js/jquery-1.10.2.min.js'>"+"<"+"/script>"); </script> <![endif]--> <script type="text/javascript"> if("ontouchend" in document) document.write("<script src='/static/js/jQuery/jquery.mobile.custom.min.js'>"+"<"+"/script>"); </script> <!-- inline scripts related to this page --> <script type="text/javascript"> $(function(){ $("#loginverifycodeImg").click(function(){ $('#loginverifycodeImg').attr('src',"/code?t="+Date()); }) }) function show_box(id) { jQuery('.widget-box.visible').removeClass('visible'); jQuery('#'+id).addClass('visible'); } </script> </body> </html>
2018年10月04日
1,177 阅读
0 评论
0 点赞
2018-10-04
C#中string.Format输出内容中含有花括号的解决方法
问题再现今天在开发的时候,遇到了需要传递session的地方,我们这边是用过formstate传递的,如下:argumentString = string.Format("{FORMSTATE~dwbh}='{0}'&{FORMSTATE~ssbm}='{1}'&{FORMSTATE~year}='{2}'&{FORMSTATE~month}='{3}'&{FORMSTATE~zclb}='{4}'&{FORMSTATE~zcbh}='{5}'", hsdw, ssbm, year, month, zclb, zcbh);问题分析因为花括号字符是拿来做填充检测的(比如{0}表示首个子串),函数并不知道我们最外面的花括号是文本内容,结果就解析失败了。问题解决细想一下微软在提供string.Format方法时,不会没有考虑到花括号问题,就像文本内双引号内容我们用 \" 表示,查了一下果然有代替表示方法,用两个连在一起的“{{”表示“{”,右花括号也同理,所以得到最终解决方案:argumentString = string.Format("{{FORMSTATE~dwbh}}='{0}'&{{FORMSTATE~ssbm}}='{1}'&{{FORMSTATE~year}}='{2}'&{{FORMSTATE~month}}='{3}'&{{FORMSTATE~zclb}}='{4}'&{{FORMSTATE~zcbh}}='{5}'", hsdw, ssbm, year, month, zclb, zcbh);
2018年10月04日
1,373 阅读
0 评论
1 点赞
2018-06-24
Mac 上使用virtualenv 搭建多个Python开发环境
安装virtualenvsudo pip install virtualenv 输入virtualenv检查是否安装成功创建virtualenv创建文件夹mkdir envs下面开始新建不使用系统Python包的虚拟环境:virtualenv --no-site-packages [envs/django] cd envs/django 激活虚拟环境source bin/activate 退出虚拟环境deactivate
2018年06月24日
1,116 阅读
0 评论
1 点赞
2018-05-16
NPOI设置列宽、行高、下拉列表等信息
using Genersoft.Platform.Controls.WinForms; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Collections; using Genersoft.GS.HIS.ZW.SPI; using NPOI.HSSF.Util; using NPOI.SS.Util; namespace Genersoft.GS.HIS.ZW.Controller { public class ExcelHelper : IDisposable { #region 变量属性 private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; private string fileName = string.Empty; #endregion #region 构造函数 public ExcelHelper() { disposed = false; } #endregion #region 方法 #region 将DataTable数据导入到excel中 /// <summary> /// 将DataTable数据导入到excel中 /// </summary> /// <param name="data">要导入的数据</param> /// <param name="isColumnWritten">DataTable的列名是否要导入</param> /// <param name="sheetName">要导入的excel的sheet的名称</param> /// <returns>导入数据行数(包含列名那一行)</returns> public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten, out string fileName) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; fileName = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; ; //文件名 fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(0); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } workbook.Write(fs); //写入到excel fs.Close(); return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } } #endregion #region 将excel中的数据导入到DataTable中 /// <summary> /// 将excel中的数据导入到DataTable中 /// </summary> /// <param name="sheetName">excel工作薄sheet的名称</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public DataSet ExcelToDataTable(string sheetName, bool isFirstRowColumn, string excelPath) { DataSet ds = new DataSet(); ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(excelPath, FileMode.Open); long left = fs.Length; byte[] bytes = new byte[1024]; int maxLength = bytes.Length; int start = 0; int num = 0; while (left > 0) { fs.Position = start; num = 0; if (left < maxLength) num = fs.Read(bytes, 0, Convert.ToInt32(left)); else num = fs.Read(bytes, 0, maxLength); if (num == 0) break; start += num; left -= num; } fs.Seek(0, SeekOrigin.Begin); if (excelPath.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (excelPath.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } //最后一列的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //没有数据的行默认是null //处理空行数据 bool isBlankRow = true; for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //对象实例不为null { if (!string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))//判断单元格是否为空 { isBlankRow = false; } } } if (isBlankRow) { continue; } //增加行数据 DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } if (data != null) { DataView dv = data.DefaultView; dv.Sort = "合同编号 Asc"; DataTable dtSort = dv.ToTable(); ds.Tables.Add(dtSort); return ds; } else { return null; } } catch (Exception ex) { UMessageBox.Information(ex.Message); return null; } } #endregion #region 将excel中的数据导入到DataTable中 /// <summary> /// 将excel中的数据导入到DataTable中 /// </summary> /// <param name="sheetName">excel工作薄sheet的名称</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public DataSet BDExcelToDataTable(string sheetName, bool isFirstRowColumn, string excelPath) { DataSet ds = new DataSet(); ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(excelPath, FileMode.Open); long left = fs.Length; byte[] bytes = new byte[1024]; int maxLength = bytes.Length; int start = 0; int num = 0; while (left > 0) { fs.Position = start; num = 0; if (left < maxLength) num = fs.Read(bytes, 0, Convert.ToInt32(left)); else num = fs.Read(bytes, 0, maxLength); if (num == 0) break; start += num; left -= num; } fs.Seek(0, SeekOrigin.Begin); if (excelPath.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (excelPath.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } //最后一列的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //没有数据的行默认是null //处理空行数据 bool isBlankRow = true; for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //对象实例不为null { if (!string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))//判断单元格是否为空 { isBlankRow = false; } } } if (isBlankRow) { continue; } //增加行数据 DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } if (data != null) { DataView dv = data.DefaultView; DataTable dtSort = dv.ToTable(); ds.Tables.Add(dtSort); return ds; } else { return null; } } catch (Exception ex) { UMessageBox.Information(ex.Message); return null; } } #endregion #region 将DataTable数据导入到excel中 /// <summary> /// 将DataTable数据导入到excel中 /// </summary> /// <param name="data">要导入的数据</param> /// <param name="isColumnWritten">DataTable的列名是否要导入</param> /// <param name="sheetName">要导入的excel的sheet的名称</param> /// <returns>导入数据行数(包含列名那一行)</returns> public int DataTableToExcelForDirectory(DataTable data, string sheetName, bool isColumnWritten, string fileName, DJType type, string description = "") { int i = 0; int j = 0; int count = 0; ISheet sheet = null; fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (!string.IsNullOrEmpty(description))//添加描述信息 { IRow row = sheet.CreateRow(count); ICellStyle cellStyle = workbook.CreateCellStyle(); ICell cell = row.CreateCell(0); cell.SetCellValue(description); cellStyle.WrapText = true;//自动换行 cellStyle.BorderBottom = cellStyle.BorderLeft = cellStyle.BorderRight = cellStyle.BorderTop = BorderStyle.Thin; cell.CellStyle = cellStyle; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); row.Height = 30 * 20; count++; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(count); IDataFormat format = workbook.CreateDataFormat(); for (j = 0; j < data.Columns.Count; ++j) { ICell cell = row.CreateCell(j); ICellStyle cellStyle = workbook.CreateCellStyle(); if (data.Columns[j].DataType.ToString() == "System.Decimal") { cellStyle.DataFormat = format.GetFormat("0.00"); } else { cellStyle.DataFormat = format.GetFormat("@"); } HSSFFont ffont = (HSSFFont)workbook.CreateFont(); ffont.FontHeight = 16 * 16; ffont.FontName = "宋体"; cellStyle.SetFont(ffont); cellStyle.BorderBottom = cellStyle.BorderLeft = cellStyle.BorderRight = cellStyle.BorderTop = BorderStyle.Thin; cell.CellStyle = cellStyle; cell.SetCellValue(data.Columns[j].ColumnName); row.Cells[j] = cell; /*设置列宽*/ sheet.SetColumnWidth(j, (data.Columns[j].ColumnName.Length) * 3 * 256); switch (type) { case DJType.JXCZWPZInfo: if (data.Columns[j].ColumnName.Trim().ToUpper() == "业务分类") { //设置生成下拉框的行和列 var cellRegions = new CellRangeAddressList(count++, 65535, j, j); //设置 下拉框内容 DVConstraint constraint = DVConstraint.CreateExplicitListConstraint( new string[] { "入库", "出库" }); //绑定下拉框和作用区域,并设置错误提示信息 HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } break; case DJType.DBZWPZInfo: if (data.Columns[j].ColumnName.Trim().ToUpper() == "业务分类") { //设置生成下拉框的行和列 var cellRegions = new CellRangeAddressList(count++, 65535, j, j); //设置 下拉框内容 DVConstraint constraint = DVConstraint.CreateExplicitListConstraint( new string[] { "调拨" }); //绑定下拉框和作用区域,并设置错误提示信息 HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } break; case DJType.SRZWPZInfo: if (data.Columns[j].ColumnName.Trim().ToUpper() == "业务分类") { //设置生成下拉框的行和列 var cellRegions = new CellRangeAddressList(count++, 65535, j, j); //设置 下拉框内容 DVConstraint constraint = DVConstraint.CreateExplicitListConstraint( new string[] { "门诊收入", "住院收入" }); //绑定下拉框和作用区域,并设置错误提示信息 HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } break; case DJType.FYZWPZInfo: if (data.Columns[j].ColumnName.Trim().ToUpper() == "业务分类") { //设置生成下拉框的行和列 var cellRegions = new CellRangeAddressList(count++, 65535, j, j); //设置 下拉框内容 DVConstraint constraint = DVConstraint.CreateExplicitListConstraint( new string[] { "门诊收入", "住院收入" }); //绑定下拉框和作用区域,并设置错误提示信息 HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } break; } if (data.Columns[j].ColumnName.Trim().ToUpper() == "推送状态") { //设置生成下拉框的行和列 var cellRegions = new CellRangeAddressList(count++, 65535, j, j); //设置 下拉框内容 DVConstraint constraint = DVConstraint.CreateExplicitListConstraint( new string[] { "新增", "编辑", "删除" }); //绑定下拉框和作用区域,并设置错误提示信息 HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint); dataValidate.CreateErrorBox("输入不合法", "请输入下拉列表中的值。"); dataValidate.ShowPromptBox = true; sheet.AddValidationData(dataValidate); } } count++; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell cell = row.CreateCell(j); cell.SetCellValue(data.Rows[i][j].ToString()); ICellStyle cellStyle = workbook.CreateCellStyle(); IDataFormat format = workbook.CreateDataFormat(); cellStyle.BorderBottom = cellStyle.BorderLeft = cellStyle.BorderRight = cellStyle.BorderTop = BorderStyle.Thin; if (data.Columns[j].DataType.ToString() == "System.Decimal") { cellStyle.DataFormat = format.GetFormat("0.00"); } else { cellStyle.DataFormat = format.GetFormat("@"); } HSSFFont ffont = (HSSFFont)workbook.CreateFont(); ffont.FontHeight = 14 * 14; ffont.FontName = "宋体"; cellStyle.SetFont(ffont); cell.CellStyle = cellStyle; cell.SetCellValue(data.Columns[j].ColumnName); row.Cells[j] = cell; } ++count; } workbook.Write(fs); //写入到excel fs.Close(); return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } } #endregion #region 资源释放方法 public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (fs != null) fs.Close(); } fs = null; disposed = true; } } #endregion #region 检查DataTable列是否存在 /// <summary> /// 检查DataTable列是否存在 /// </summary> /// <param name="dataTable"></param> /// <param name="arrayList"></param> public static bool CheckColumn(DataTable dataTable, ArrayList arrayList, out string message) { message = ""; foreach (var item in arrayList) { if (!dataTable.Columns.Contains(item.ToString())) { message = "列 【" + item.ToString() + "】不存在,请检查!"; return false; } } return true; } #endregion #endregion } }
2018年05月16日
1,579 阅读
0 评论
0 点赞
2018-05-16
DataTable高效判断是否存在重复的数据
private void CheckDataRepeat(DataSet dataSet, out string message) { message = string.Empty; DataView dv = new DataView(dataSet.Tables[0]); DataTable dtBmzd = null; dtBmzd = dv.ToTable(true, new string[] { "列名1", "列名2" }); if (dtBmzd.Rows.Count < dataSet.Tables[0].Rows.Count) { message += "【列名1】、【列名2】值必须唯一,Excel中存在重复的数据,请确认!\n"; } }
2018年05月16日
1,265 阅读
0 评论
0 点赞
2018-04-01
Tomcat配置多个域名
Java最常实用的服务软件应该就是Tomcat了,前段时间也说过,赶在腾讯云搞活动的时间,把dotnetcore.com.cn、ide.net.cn还有lisen.cc几个域名也一起备案了。最近想着用Java新建一个网站。Tomcat配置多个域名还是很简单的,仍然是通过server.xml进行配置。<!--lisen.cc配置--> <Host name="lisen.cc" appBase="webapps" unpackWARs="true" autoDeploy="true"> <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <Context docBase="LiSen" path="" /> <!-- Access log processes all example. Documentation at: /docs/config/valve.html Note: The pattern used is equivalent to using pattern="common" --> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t "%r" %s %b" /> </Host> <!--dotnetcore配置--> <Host name="dotnetcore.com.cn" appBase="webapps" unpackWARs="true" autoDeploy="true"> <Context docBase="DotNetCore" path="" /> <!-- Access log processes all example. Documentation at: /docs/config/valve.html Note: The pattern used is equivalent to using pattern="common" --> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t "%r" %s %b" /> </Host>
2018年04月01日
1,088 阅读
0 评论
0 点赞
2018-03-11
log4net详细介绍
log4net介绍log4net是一个功能著名的开源日志记录组件。利用log4net可以方便地将日志信息记录到文件、控制台、Windows事件日志和数据库(包括MS SQL Server, Access, Oracle9i,Oracle8i,DB2,SQLite)中。并且我们还可以记载控制要记载的日志级别,可以记载的日志类别包括:FATAL(致命错误)、ERROR(一般错误)、WARN(警告)、INFO(一般信息)、DEBUG(调试信息)。log4net安装这里不多过多介绍了,直接通过nuget安装即可。log4net.config配置<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!--根配置--> <root> <!--日志级别:可选值: ERROR > WARN > INFO > DEBUG --> <level value="ERROR"/> <level value="WARN"/> <level value="INFO"/> <level value="DEBUG"/> <appender-ref ref="ErrorLog" /> <appender-ref ref="WarnLog" /> <appender-ref ref="InfoLog" /> <appender-ref ref="DebugLog" /> <appender-ref ref="Sqlserver" /> </root> <!-- 错误 Error.log--> <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender"> <!--目录路径,可以是相对路径或绝对路径--> <param name="File" value="Log\Ide_Net_Cn_log"/> <!--文件名,按日期生成文件夹--> <param name="DatePattern" value="/yyyy-MM-dd/"Error.log""/> <!--追加到文件--> <appendToFile value="true"/> <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]--> <rollingStyle value="Composite"/> <!--写到一个文件--> <staticLogFileName value="false"/> <!--单个文件大小。单位:KB|MB|GB--> <maximumFileSize value="200MB"/> <!--最多保留的文件数,设为"-1"则不限--> <maxSizeRollBackups value="-1"/> <!--日志格式--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message"/> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ERROR" /> <param name="LevelMax" value="ERROR" /> </filter> </appender> <!-- 警告 Warn.log--> <appender name="WarnLog" type="log4net.Appender.RollingFileAppender"> <!--目录路径,可以是相对路径或绝对路径--> <param name="File" value="Log\Ide_Net_Cn_log"/> <!--文件名,按日期生成文件夹--> <param name="DatePattern" value="/yyyy-MM-dd/"Warn.log""/> <!--追加到文件--> <appendToFile value="true"/> <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]--> <rollingStyle value="Composite"/> <!--写到一个文件--> <staticLogFileName value="false"/> <!--单个文件大小。单位:KB|MB|GB--> <maximumFileSize value="200MB"/> <!--最多保留的文件数,设为"-1"则不限--> <maxSizeRollBackups value="-1"/> <!--日志格式--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message"/> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="WARN" /> <param name="LevelMax" value="WARN" /> </filter> </appender> <!-- 信息 Info.log--> <appender name="InfoLog" type="log4net.Appender.RollingFileAppender"> <!--目录路径,可以是相对路径或绝对路径--> <param name="File" value="Log\Ide_Net_Cn_log"/> <!--文件名,按日期生成文件夹--> <param name="DatePattern" value="/yyyy-MM-dd/"Info.log""/> <!--追加到文件--> <appendToFile value="true"/> <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]--> <rollingStyle value="Composite"/> <!--写到一个文件--> <staticLogFileName value="false"/> <!--单个文件大小。单位:KB|MB|GB--> <maximumFileSize value="200MB"/> <!--最多保留的文件数,设为"-1"则不限--> <maxSizeRollBackups value="-1"/> <!--日志格式--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message"/> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="INFO" /> <param name="LevelMax" value="INFO" /> </filter> </appender> <!-- 调试 Debug.log--> <appender name="DebugLog" type="log4net.Appender.RollingFileAppender"> <!--目录路径,可以是相对路径或绝对路径--> <param name="File" value="Log\Ide_Net_Cn_log"/> <!--文件名,按日期生成文件夹--> <param name="DatePattern" value="/yyyy-MM-dd/"Debug.log""/> <!--追加到文件--> <appendToFile value="true"/> <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]--> <rollingStyle value="Composite"/> <!--写到一个文件--> <staticLogFileName value="false"/> <!--单个文件大小。单位:KB|MB|GB--> <maximumFileSize value="200MB"/> <!--最多保留的文件数,设为"-1"则不限--> <maxSizeRollBackups value="-1"/> <!--日志格式--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message"/> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="DEBUG" /> </filter> </appender> <!-- 调试 Sqlserver.log--> <appender name="Sqlserver" type="log4net.Appender.ADONetAppender"> <!--日志缓存写入条数 设置为0时只要有一条就立刻写到数据库--> <bufferSize value="0" /> <!--日志数据库连接串--> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="DATABASE=Ide_Net_Cn;SERVER=lisen.org;UID=sa;PWD=123456a?;Connect Timeout=30;" /> <!--日志数据库脚本--> <commandText value="INSERT INTO LogDetails ([OperationTime],[Url],[Ip],[Host],[Browser],[UserName],[User],Content,ExceptionInfo,ExceptionSource,ExceptionRemark,Level) VALUES ( @OperationTime, @Url, @Ip, @Host, @Browser,@UserName,@User,@Content,@ExceptionInfo,@ExceptionSource,@ExceptionRemark,@Level)" /> <!--日志内码 --> <!--<parameter> <parameterName value="@ID" /> <dbType value="String" /> <size value="36" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "NEWID()"/> </layout> </parameter>--> <!--操作时间--> <parameter> <parameterName value="@OperationTime" /> <dbType value="String" /> <size value="100" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{OperationTime}"/> </layout> </parameter> <!--url --> <parameter> <parameterName value="@Url" /> <dbType value="String" /> <size value="255" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{Url}"/> </layout> </parameter> <!--ip地址--> <parameter> <parameterName value="@Ip" /> <dbType value="String" /> <size value="255" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{Ip}"/> </layout> </parameter> <!--主机--> <parameter> <parameterName value="@Host" /> <dbType value="String" /> <size value="255" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{Host}"/> </layout> </parameter> <!--浏览器--> <parameter> <parameterName value="@Browser" /> <dbType value="String" /> <size value="100" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{Browser}"/> </layout> </parameter> <!--UserName --> <parameter> <parameterName value="@UserName" /> <dbType value="String" /> <size value="20" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{UserName}"/> </layout> </parameter> <!--用户内码--> <parameter> <parameterName value="@User" /> <dbType value="String" /> <size value="40" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{User}"/> </layout> </parameter> <!--日志内容--> <parameter> <parameterName value="@Content" /> <dbType value="String" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{Content}"/> </layout> </parameter> <!--异常信息--> <parameter> <parameterName value="@ExceptionInfo" /> <dbType value="String" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{ExceptionInfo}"/> </layout> </parameter> <!--异常来源--> <parameter> <parameterName value="@ExceptionSource" /> <dbType value="String" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{ExceptionSource}"/> </layout> </parameter> <!--异常信息备注--> <parameter> <parameterName value="@ExceptionRemark" /> <dbType value="String" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{ExceptionRemark}"/> </layout> </parameter> <!--异常等级--> <parameter> <parameterName value="@Level" /> <dbType value="String" /> <size value="1" /> <layout type="Ide.Net.Cn.Util.Log.LogLayout" > <conversionPattern value = "%property{Level}"/> </layout> </parameter> </appender> <!--Oracle数据库--> <appender name="OracleAppender" type="log4net.Appender.AdoNetAppender"> <!-- Oracle数据源--> <connectionType value="Oracle.ManagedDataAccess.Client.OracleConnection, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /> <!-- Oracle连接字符串--> <connectionString value="DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.3.206)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)));PASSWORD=watdb;PERSIST SECURITY INFO=True;USER ID=watdb;"/> <commandText value="INSERT INTO SYS_LOG(Dates,Levels,Logger,Message,Exception,ClientUser,ClientIP,RequestUrl,Action)VALUES(:Dates,:Levels,:Logger,:Message,:Exception,:ClientUser,:ClientIP,:RequestUrl,:Action)"/> <!-- 设置缓存区大小 1表明有一条日志就要写入 如果10就表示日志到达10条时一起写入 --> <bufferSize value="0"/> <parameter> <parameterName value=":Dates" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout"/> </parameter> <parameter> <parameterName value=":Levels" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value=":Logger" /> <dbType value="String" /> <size value="200" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value=":Message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value=":Exception" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%exception" /> </layout> </parameter> <!--DIY--> <parameter> <parameterName value=":ClientUser" /> <dbType value="String" /> <size value="100" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{ClientUser}" /> </layout> </parameter> <parameter> <parameterName value=":ClientIP" /> <dbType value="String" /> <size value="20" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{ClientIP}" /> </layout> </parameter> <parameter> <parameterName value=":RequestUrl" /> <dbType value="String" /> <size value="500" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{RequestUrl}" /> </layout> </parameter> <parameter> <parameterName value=":Action" /> <dbType value="String" /> <size value="20" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{Action}" /> </layout> </parameter> </appender> <!--Sqlite数据库--> <appender name="SqliteAppender" type="log4net.Appender.AdoNetAppender"> <bufferSize value="0" /> <connectionType value="System.Data.SQLite.SQLiteConnection, System.Data.SQLite, Version=1.0.98.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" /> <connectionString value="Data Source=|DataDirectory|test.db;Version=3;" /> <commandText value="INSERT INTO Log (Date, Level, Logger, ClientUser,ClientIP, RequestUrl,Action, Message, Exception) VALUES (@Date, @Level, @Logger,@ClientUser,@ClientIP, @RequestUrl,@Action, @Message, @Exception)" /> <parameter> <parameterName value="@Date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@Level" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@Logger" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@ClientUser" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{ClientUser}" /> </layout> </parameter> <parameter> <parameterName value="@ClientIP" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{ClientIP}" /> </layout> </parameter> <parameter> <parameterName value="@RequestUrl" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{RequestUrl}" /> </layout> </parameter> <parameter> <parameterName value="@Action" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%property{Action}" /> </layout> </parameter> <parameter> <parameterName value="@Message" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@Exception" /> <dbType value="String" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%exception" /> </layout> </parameter> </appender> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration> <!-- 调用实例 log4net.ILog log = log4net.LogManager.GetLogger("Filelog"); log.Info(Message); %m(message):输出的日志消息,如ILog.Debug(…)输出的一条消息 %n(new line):换行 %d(datetime):输出当前语句运行的时刻 %r(run time):输出程序从运行到执行到当前语句时消耗的毫秒数 %t(thread id):当前语句所在的线程ID %p(priority): 日志的当前优先级别,即DEBUG、INFO、WARN…等 %c(class):当前日志对象的名称 %L:输出语句所在的行号 %F:输出语句所在的文件名 %-数字:表示该项的最小长度,如果不够,则用空格填充 例如,转换模式为%r [%t]%-5p %c - %m%n 的 PatternLayout 将生成类似于以下内容的输出: 176 [main] INFO org.foo.Bar - Located nearest gas station. -->定义实体类LogEntity.cs/************************************************************************************* * CLR版 本: 4.0.30319.42000 * 机器名称: LISEN0100 * 命名空间: Ide.Net.Cn.Util.Log * 文件名称: LogEntity * 创建时间: 2018/3/11 15:51:49 * 作 者: 李森的博客 * 个人博客: http://lisen.cc * 个人邮箱: lisen@lisen.org * 文件说明: * 修改时间: * 修 改 人: 李森的博客 * 修改说明: *************************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ide.Net.Cn.Util.Log { public class LogEntity { #region 属性 /// <summary> /// 操作时间 /// </summary> public DateTime OperationTime { get; set; } /// <summary> /// Url地址 /// </summary> public string Url { get; set; } /// <summary> /// 类名 /// </summary> public string Class { get; set; } /// <summary> /// IP /// </summary> public string Ip { get; set; } /// <summary> /// 主机 /// </summary> public string Host { get; set; } /// <summary> /// 浏览器 /// </summary> public string Browser { get; set; } /// <summary> /// 操作人 /// </summary> public string UserName { get; set; } /// <summary> /// 操作人编号或内码 /// </summary> public string User { get; set; } /// <summary> /// 内容 /// </summary> public string Content { get; set; } /// <summary> /// 异常信息 /// </summary> public string ExceptionInfo { get; set; } /// <summary> /// 异常来源 /// </summary> public string ExceptionSource { get; set; } /// <summary> /// 异常信息备注 /// </summary> public string ExceptionRemark { get; set; } #endregion #region 构造函数 #endregion #region 方法 #endregion } }定义文本格式化类LogFormat.cs,用于控制文本输出/************************************************************************************* * CLR版 本: 4.0.30319.42000 * 机器名称: LISEN0100 * 命名空间: Ide.Net.Cn.Util.Log * 文件名称: LogFormat * 创建时间: 2018/3/11 16:37:24 * 作 者: 李森的博客 * 个人博客: http://lisen.cc * 个人邮箱: lisen@lisen.cc * 文件说明: 格式化消息实体 * 修改时间: * 修 改 人: 李森的博客 * 修改说明: *************************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ide.Net.Cn.Util.Log { public class LogFormat { #region 属性 #endregion #region 构造函数 #endregion #region 方法 /// <summary> /// 生成错误 /// </summary> /// <param name="logEntity">对象</param> /// <returns></returns> public static string ErrorFormat(LogEntity logEntity) { StringBuilder strInfo = new StringBuilder(); strInfo.Append("1. 错误: >> 操作时间: " + logEntity.OperationTime + " 操作人: " + logEntity.UserName + " 操作人编号: " + logEntity.User + " \r\n"); strInfo.Append("2. 地址: " + logEntity.Url + " \r\n"); strInfo.Append("3. 类名: " + logEntity.Class + " \r\n"); strInfo.Append("4. Ip : " + logEntity.Ip + " 主机: " + logEntity.Host + " 浏览器: " + logEntity.Browser + " \r\n"); strInfo.Append("5. 内容: " + logEntity.Content + "\r\n"); strInfo.Append("-----------------------------------------------------------------------------------------------------------------------------\r\n"); return strInfo.ToString(); } /// <summary> /// 生成警告 /// </summary> /// <param name="logEntity">对象</param> /// <returns></returns> public static string WarnFormat(LogEntity logEntity) { StringBuilder strInfo = new StringBuilder(); strInfo.Append("1. 警告: >> 操作时间: " + logEntity.OperationTime + " 操作人: " + logEntity.UserName + " 操作人编号: " + logEntity.User + " \r\n"); strInfo.Append("2. 地址: " + logEntity.Url + " \r\n"); strInfo.Append("3. 类名: " + logEntity.Class + " \r\n"); strInfo.Append("4. Ip : " + logEntity.Ip + " 主机: " + logEntity.Host + " 浏览器: " + logEntity.Browser + " \r\n"); strInfo.Append("5. 内容: " + logEntity.Content + "\r\n"); strInfo.Append("-----------------------------------------------------------------------------------------------------------------------------\r\n"); return strInfo.ToString(); } /// <summary> /// 生成信息 /// </summary> /// <param name="logEntity">对象</param> /// <returns></returns> public static string InfoFormat(LogEntity logEntity) { StringBuilder strInfo = new StringBuilder(); strInfo.Append("1. 信息: >> 操作时间: " + logEntity.OperationTime + " 操作人: " + logEntity.UserName + " 操作人编号: " + logEntity.User + " \r\n"); strInfo.Append("2. 地址: " + logEntity.Url + " \r\n"); strInfo.Append("3. 类名: " + logEntity.Class + " \r\n"); strInfo.Append("4. Ip : " + logEntity.Ip + " 主机: " + logEntity.Host + " 浏览器: " + logEntity.Browser + " \r\n"); strInfo.Append("5. 内容: " + logEntity.Content + "\r\n"); strInfo.Append("-----------------------------------------------------------------------------------------------------------------------------\r\n"); return strInfo.ToString(); } /// <summary> /// 生成调试 /// </summary> /// <param name="logEntity">对象</param> /// <returns></returns> public static string DebugFormat(LogEntity logEntity) { StringBuilder strInfo = new StringBuilder(); strInfo.Append("1. 调试: >> 操作时间: " + logEntity.OperationTime + " 操作人: " + logEntity.UserName + " 操作人编号: " + logEntity.User + " \r\n"); strInfo.Append("2. 地址: " + logEntity.Url + " \r\n"); strInfo.Append("3. 类名: " + logEntity.Class + " \r\n"); strInfo.Append("4. Ip : " + logEntity.Ip + " 主机: " + logEntity.Host + " 浏览器: " + logEntity.Browser + " \r\n"); strInfo.Append("5. 内容: " + logEntity.Content + "\r\n"); strInfo.Append("-----------------------------------------------------------------------------------------------------------------------------\r\n"); return strInfo.ToString(); } /// <summary> /// 生成异常信息 /// </summary> /// <param name="logEntity">对象</param> /// <returns></returns> public static string ExceptionFormat(LogEntity logEntity) { StringBuilder strInfo = new StringBuilder(); strInfo.Append("1. 调试: >> 操作时间: " + logEntity.OperationTime + " 操作人: " + logEntity.UserName + " 操作人编号: " + logEntity.User + " \r\n"); strInfo.Append("2. 地址: " + logEntity.Url + " \r\n"); strInfo.Append("3. 类名: " + logEntity.Class + " \r\n"); strInfo.Append("4. 主机: " + logEntity.Host + " Ip : " + logEntity.Ip + " 浏览器: " + logEntity.Browser + " \r\n"); strInfo.Append("5. 异常: " + logEntity.ExceptionInfo + "\r\n"); //strInfo.Append("6. 来源: " + logEntity.ExceptionSource + "\r\n"); //strInfo.Append("7. 实例: " + logEntity.ExceptionRemark + "\r\n"); strInfo.Append("-----------------------------------------------------------------------------------------------------------------------------\r\n"); return strInfo.ToString(); } #endregion } }定义工厂类LogFactory.cs,返回log类型/************************************************************************************* * CLR版 本: 4.0.30319.42000 * 机器名称: LISEN0100 * 命名空间: Ide.Net.Cn.Util.Log * 文件名称: LogFactory * 创建时间: 2018/3/11 15:27:20 * 作 者: 李森的博客 * 个人博客: http://lisen.cc * 个人邮箱: lisen@lisen.org * 文件说明: 日志工厂类,产生错误、警告、信息、调试类 * 修改时间: * 修 改 人: 李森的博客 * 修改说明: *************************************************************************************/ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace Ide.Net.Cn.Util.Log { public class LogFactory { #region 属性 #endregion #region 构造函数 /// <summary> /// 构造函数 /// </summary> static LogFactory() { FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath("~/XmlConfig/log4net.config")); log4net.Config.XmlConfigurator.ConfigureAndWatch(fileInfo); } #endregion #region 方法 public static ILog GetLogger(LogLevel logLevel) { ILog log = null; switch (logLevel) { case LogLevel.Error: log = LogManager.GetLogger("ErrorLog"); break; case LogLevel.Warning: log = LogManager.GetLogger("WarnLog"); break; case LogLevel.Info: log = LogManager.GetLogger("InfoLog"); break; case LogLevel.Debug: log = LogManager.GetLogger("DebugLog"); break; } return log; } public static ILog ErrorLog() { return LogManager.GetLogger("ErrorLog"); } public static ILog WarnLog() { return LogManager.GetLogger("WarnLog"); } public static ILog InfoLog() { return LogManager.GetLogger("InfoLog"); } public static ILog DebugLog() { return LogManager.GetLogger("DebugLog"); } public static ILog SqlLog() { return LogManager.GetLogger("Sqlserver"); } #endregion } }定义公共类log.cs,用于输出日志/************************************************************************************* * CLR版 本: 4.0.30319.42000 * 机器名称: LISEN0100 * 命名空间: Ide.Net.Cn.Util.Log * 文件名称: Log * 创建时间: 2018/3/11 15:04:03 * 作 者: 李森的博客 * 个人博客: http://lisen.cc * 个人邮箱: lisen@lisen.cc * 文件说明: 日志文件类 * 修改时间: * 修 改 人: 李森的博客 * 修改说明: *************************************************************************************/ using log4net; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ide.Net.Cn.Util.Log { public class Log { #region 字段属性 private ILog log; private bool IsLog = true; #endregion #region 构造函数 public Log(ILog log) { this.log = log; IsLog = ConfigurationManager.AppSettings["IsLog"].ToLower() == "true" ? true : false; } #endregion #region 方法 /// <summary> /// 写入错误日志 /// </summary> /// <param name="errorMsg">错误消息</param> public void Error(LogEntity errorMsg) { if (IsLog) { log.Error(LogFormat.ErrorFormat(errorMsg)); } } /// <summary> /// 写入警告日志 /// </summary> /// <param name="warnMsg">警告消息</param> public void Warn(LogEntity warnMsg) { if (IsLog) { log.Warn(LogFormat.WarnFormat(warnMsg)); } } /// <summary> /// 写入警告日志 /// </summary> /// <param name="warnMsg">警告消息</param> public void Warn(LogEntity warnMsg, Exception exception) { if (IsLog) { log.Warn(LogFormat.WarnFormat(warnMsg), exception); } } /// <summary> /// 写入信息日志 /// </summary> /// <param name="infoMsg">信息消息</param> public void Info(LogEntity infoMsg) { if (IsLog) { log.Info(LogFormat.InfoFormat(infoMsg)); } } /// <summary> /// 写入调试日志 /// </summary> /// <param name="debugMsg">调试消息</param> public void Debug(LogEntity debugMsg) { if (IsLog) { log.Debug(LogFormat.DebugFormat(debugMsg)); } } #endregion } }使用定义一个aspx页面,窗体载入后测试日志文件using Ide.Net.Cn.Util.Log; using log4net; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Ide.Net.Cn.Web { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //ILog log = LogFactory.ErrorLog();//文本日志 ILog log = LogFactory.SqlLog();//数据库日志 Log logger = new Log(log); LogEntity logEntity = new LogEntity { OperationTime = DateTime.Now, Url = "lisen.cc" }; try { logger.Warn(logEntity); } catch (Exception ex) { logger.Warn(logEntity, ex); } } } } }数据库表结构USE [Ide_Net_Cn] GO /****** Object: Table [dbo].[LogDetails] Script Date: 03/11/2018 19:13:45 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[LogDetails]( [ID] [varchar](36) NOT NULL, [OperationTime] [datetime] NULL, [Url] [varchar](255) NULL, [Ip] [nvarchar](255) NULL, [Host] [nvarchar](255) NULL, [Browser] [nvarchar](100) NULL, [UserName] [nvarchar](20) NULL, [User] [nvarchar](40) NULL, [Content] [nvarchar](max) NULL, [ExceptionInfo] [nvarchar](max) NULL, [ExceptionSource] [nvarchar](max) NULL, [ExceptionRemark] [nvarchar](max) NULL, [Level] [char](1) NULL, PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY], CONSTRAINT [LogDetails_Code] UNIQUE NONCLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'浏览器型号+版本号' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'LogDetails', @level2type=N'COLUMN',@level2name=N'Browser' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1-error; 2-warn; 3-info; 4-debug' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'LogDetails', @level2type=N'COLUMN',@level2name=N'Level' GO ALTER TABLE [dbo].[LogDetails] ADD DEFAULT (newid()) FOR [ID] GO ALTER TABLE [dbo].[LogDetails] ADD DEFAULT (NULL) FOR [ExceptionSource] GO
2018年03月11日
1,205 阅读
0 评论
1 点赞
2018-03-11
log4net不写日志原因分析
今天闲着没事看了一下log4net的东西,本来打算写个简单的日志,但是发现系统没有记录日志。其实出现这种情况,基本可以断定是配置文件没有读取到导致的。问题排查为了能够排查问题,我们打开vs查看输出信息由于我把配置文件放到单独项目,所以调增了一下我的配置文件读取方式,如下:FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath("~/XmlConfig/log4net.config")); log4net.Config.XmlConfigurator.ConfigureAndWatch(fileInfo); 然后就可以看到输出了
2018年03月11日
1,272 阅读
0 评论
0 点赞
2018-03-10
Asp.Net实现图形验证码
平时我们使用验证码的情形还是非常多的,比如登陆界面、发送短信验证码等,现在新的验证方式也又很多,比如数学计算或者滑块等,这里我们仅仅介绍传统的图形验证码。修改web.config,设置图形验证码的位数 <appSettings> <add key="VerifyCodeNum" value="4"/> </appSettings> 生成图片公共类using System; using System.Collections.Generic; using System.Configuration; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; /// <summary> /// VerifyCode 的摘要说明 /// </summary> public class VerifyCode { public VerifyCode() { // // TODO: 在此处添加构造函数逻辑 // } /// <summary> /// 生成随机数 /// </summary> /// <returns></returns> public static string GetVerifyCode() { //获取系统配置的随机数的位数 int vCodeNum = Convert.ToInt32(ConfigurationManager.AppSettings["VerifyCodeNum"]); string vChar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" + ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,P,Q" + ",R,S,T,U,V,W,X,Y,Z"; string[] vArray = vChar.Split(','); string code = "";//产生的随机数 int temp = -1;//记录上次随机数值,尽量避避免生产几个一样的随机数 Random rand = new Random(); //采用一个简单的算法以保证生成随机数的不同 for (int i = 1; i < vCodeNum + 1; i++) { if (temp != -1) { rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));//初始化随机类 } int t = rand.Next(61);//获取随机数 if (temp != -1 && temp == t) { return GetVerifyCode();//如果获取的随机数重复,则递归调用 } ttemp = t;//把本次产生的随机数记录起来 code += vArray[t];//随机数的位数加一 } return code; } /// <summary> /// 该方法是将生成的随机数写入图像文件 /// </summary> /// <param name="code">code是一个随机数</param> public static MemoryStream CreateImage(out string code) { code = GetVerifyCode(); Bitmap Img = null; Graphics g = null; MemoryStream ms = null; Random random = new Random(); //验证码颜色集合 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //验证码字体集合 string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; //定义图像的大小,生成图像的实例 Img = new Bitmap(((int)code.Length) * 16, 32); g = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象 g.Clear(Color.White);//背景设为白色 //在随机位置画背景点 for (int i = 0; i < 100; i++) { int x = random.Next(Img.Width); int y = random.Next(Img.Height); g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1); } //验证码绘制在g中 for (int i = 0; i < code.Length; i++) { int cindex = random.Next(7);//随机颜色索引值 int findex = random.Next(5);//随机字体索引值 Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字体 Brush b = new SolidBrush(c[cindex]);//颜色 int ii = 4; if ((i + 1) % 2 == 0)//控制验证码不在同一高度 { ii = 2; } g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 12), ii);//绘制一个验证字符 } ms = new MemoryStream();//生成内存流对象 Img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中 //回收资源 g.Dispose(); Img.Dispose(); return ms; } } 新建一个页面VerifyCodeImage.aspx共前台调用using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class VerifyCodeImage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string verifyCode = String.Empty; MemoryStream memoryStream = VerifyCode.CreateImage(out verifyCode); Response.ContentType = "image/jpeg"; Response.Cookies.Add(new HttpCookie("VerifyCode", verifyCode)); Response.BinaryWrite(memoryStream.ToArray()); } }调用页面<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent"> <img src="/VerifyCodeImage.aspx" id="verifyCode"/> </asp:Content>实现验证实现验证也很简答,把验证码写入cookie,用户点击登陆的时候只需要与cookie的值进行比较即可。
2018年03月10日
1,088 阅读
0 评论
1 点赞
1
...
15
16
17
...
19