这个问题似乎以前碰到过,不过记不太清了。 程序重新生成,提示错误:在证书存储区中找不到清单签名证书。 可能是之前部署的程序证书被我删掉了或是证书过期了,结果出现这个问题。解决方案如下: 方案1:右击项目属性—>签名—>为ClickOnce清单签名,将勾掉的选项去掉。 方案2:在签名中创建一个新的签名。 方案3:记事本打开相应的csproj文件,调整节点值。<SignManifests>true</SignManifests>将true修改为false。 以上解决方案任选其一,我选了方案一,简单嘛。重新生成,问题搞定! from:https://www.cnblogs.com/190196539/archive/2011/12/03/2272861.html
View Detailshttp://www.jbxue.com/article/5649.html 打开一个页面<?php phpinfo(); ?> 然后在游览器下运行:页面提示 No input file specified. FastCGI模式下访问php文件时,出现No input file specified.错误 查看access.log 发现是 404 打开一个页面<?php phpinfo(); ?> 然后在游览器下运行:页面提示 No input file specified. FastCGI模式下访问php文件时,出现No input file specified.错误 查看access.log 发现是 404 原因分析: 1、任何对.php文件的请求,都简单地交给php-cgi去处理,但没有验证该php文件是否存在。PHP文件不存在,没办法返回普通的404错误,它返回 一个404,并带上一句”No input file specified” 2、还可能跟 路径或者 权限有关系,或者SCRIPT_FILENAME 变量没有被正确的设置(这在nginx是最常见的原因) 1)如果html也出现404错误,那么就是document root 设置的有问题 2)检查脚本文件的权限, 可能PHP或者web server不能读取它 3)SCRIPT_FILENAME设置错误 网上的解决方法: 步骤一:修改nginx主配置文件nginx.conf 默认安装的nginx配置文件中定义fastcgi处是:fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 可以将它改成: fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 必须保证 $document_root 在配置文件中,在astcgi_param SCRIPT_FILENAME前面被用到过一次, 后面有解释为什么。 步骤二:修改PHP的住配置文件php.ini 修改/etc/php5/cgi/php.ini中cgi.fix_pathinfo=1 这样也可让php-cgi正常使用SCRIPT_FILENAME这个变量 有人说,这样改也行 fastcgi_param SCRIPT_NAME /home/gavin/nginx/$fastcgi_script_name; 让我们看看PHP对这两个变量是怎么解释的吧 SCRIPT_NAME SCRIPT_FILENAME 据说,必须指定正确的SCRIPT_FILENAME, PHP-CGI会忽略SCRIPT_NAME(即使它的值设置的是正确的) 或者指定特殊的php.ini, 设置doc_root, discard path, fix pathinfo等等 script_filename 只是被用做一种快捷方式。 如果fix_pathinfo设置打开,init函数将它用来决定真实的路径 因为配置文件会改变 nginx的变量$fastcgi_script_name fastcgi_param SCRIPT_NAME /home/gavin/nginx/$fastcgi_script_name; fastcgi_param […]
View DetailsNginx Nginx有官方native build的32bit版本, 也有cygwin build的64bit版本, 出于稳定性的考虑, 还是选了官方的32bit. 解压, 本例中使用的路径是 C:\Servers\nginx-1.9.12 , 创建两个bat, 用于启动和关闭nginx: start_nginx.bat
1 2 3 4 |
@echo off set NGINX_HOME=C:\Servers\nginx-1.9.12 start /D %NGINX_HOME%\ %NGINX_HOME%\nginx.exe pause |
stop_nginx.bat
1 2 3 4 5 |
@echo off set NGINX_HOME=C:\Servers\nginx-1.9.12 cd %NGINX_HOME% nginx.exe -s quit pause |
PHP 选的版本是 7.0.4 64位 NTS(非线程安全) VC14, 本例中解压至目录 C:\Servers\php-7.0.4-nts-Win32-VC14-x64 , 使用php.ini-development 创建 php.ini, 修改以下几处, (参考 http://man.chinaunix.net/develop/php/php_manual_zh/html/ini.core.html )
1 2 3 4 5 6 7 8 9 10 11 |
date.timezone = Asia/Shanghai enable_dl = On #允许用户在运行时加载PHP扩展,即在脚本运行期间加载 cgi.force_redirect = 0 # 启用时, 防止任何人通过如 http://my.host/cgi-bin/php/secretdir/script.php 这样的 URL 直接调用 PHP。PHP 在此模式下只会解析已经通过了 web 服务器的重定向规则的 URL. 在大多数 web 服务器中以 CGI 方式运行 PHP 时很有必要用 cgi.force_redirect 提供安全。PHP 默认其为 On。可以将其关闭,但风险自担。注: Windows 用户:可以安全地在 IIS 之下将其关闭,事实上必须这么做。要在 OmniHTTPD 或 Xitami 之下使用也必须将其关闭。 cgi.fix_pathinfo=1 #1:PHP CGI 以 / 为分隔符号从后向前依次检查请求的路径, 对 CGI 提供了真正的 PATH_INFO/PATH_TRANSLATED 支持。以前 PHP 的行为是将 PATH_TRANSLATED 设为 SCRIPT_FILENAME,而不管 PATH_INFO 是什么。有关 PATH_INFO 的更多信息见 cgi 规格。将此值设为 1 将使 PHP CGI 修正其路径以遵守规格。设为 0 将使 PHP 的行为和从前一样。默认为零。用户应该修正其脚本使用 SCRIPT_FILENAME 而不是 PATH_TRANSLATED。 fastcgi.impersonate = 1 #IIS(在基于 WINNT 的操作系统上)中的 FastCGI 支持模仿客户端安全令牌的能力。这使得 IIS 能够定义运行时所基于的请求的安全上下文。Apache 中的 mod_fastcgi 不支持此特性(03/17/2002)。如果在 IIS 中运行则设为 1。默认为 0。 cgi.rfc2616_headers = 1 #指定 PHP 在发送 HTTP 响应代码时使用何种报头。如果设定为 0,PHP 发送一个 Status: 报头,Apache 和其它 web server 都支持。如果此选项设定为 1,PHP 将发送 RFC 2616 兼容的报头。除非你知道自己在做什么,否则保留其值为 0。 |
添加扩展, 修改以下几处
1 2 3 |
extension_dir = "./ext" # 指定win7下的扩展目录 # 并取消用到的扩展前面的注释 |
启动的命令是
1 |
C:\>Servers\php-7.0.4-nts-Win32-VC14-x64\php-cgi.exe -b 127.0.0.1:9000 |
如果需要后台启动PHP CGI, 使用vbs, 创建 startup.vbs
1 |
createobject("wscript.shell").run "c:\Servers\php-7.0.4-nts-Win32-VC14-x64\php-cgi.exe -b 127.0.0.1:9000",0,false |
停止PHP CGI, 创建shutdown.bat
1 2 3 |
@echo off taskkill /fi "imagename eq php-cgi.exe" pause |
Nginx 启用 PHP 修改nginx.conf
1 2 3 4 5 6 7 |
location ~ \.php$ { root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } |
重启nginx 注: PHP5.6及以下, 需要将mysql 的 libmysql.dll 拷贝至 C:\Windows\SysWOW64 PHP7貌似已经取消了支持,编译都没有了--with-mysql参数,只支持--with-mysqli和--with-pdo-mysql, 故libmysql.dll已经不需要 如果提示api-ms-win-crt-runtime-l1-1-0.dll丢失, 请安装 visual c++ redistributable 2015, 从微软官网上可以下载. 安装对系统的要求必须在win7 sp1以上, 如果win7还未升级的, 安装会失败. from:https://www.cnblogs.com/milton/p/5244387.html
View Details1、ArrarList 转换为 string[] ArrayList list = new ArrayList(); list.Add("aaa"); list.Add("bbb"); //转换成数组 string[] arrString = (string[])list.ToArray(typeof( string)); 2、string[] 转换为 ArrarList ArrayList list = new ArrayList(new string[] { "aaa", "bbb" }); 3、ArrayList 转换为 string ArrayList list = new ArrayList(); list.Add("aaa"); list.Add("bbb"); //转换成数组 string str= string.Join(",", (string[])list.ToArray(typeof( string))); 4、string 转换为 ArrayList string str="1,2,3,4,5"; ArrayList b = new ArrayList( str.Split(',') ); from:https://www.cnblogs.com/stone_w/archive/2012/03/21/2409357.html
View Details有关wordpress IP验证不当漏洞的通知,阿里云每天一封邮件加一条短信。虽然关系不大,但还是看着心烦。同时升级专业版不是小博客能够承受的,所以只能自己动手。 漏洞描述 wordpress /wp-includes/http.php文件中的wp_http_validate_url函数对输入IP验证不当,导致黑客可构造类似于012.10.10.10这样的畸形IP绕过验证,进行SSRF。【注意:该补丁为云盾自研代码修复方案,云盾会根据您当前代码是否符合云盾自研的修复模式进行检测,如果您自行采取了底层/框架统一修复、或者使用了其他的修复方案,可能会导致您虽然已经修复了改漏洞,云盾依然报告存在漏洞,遇到该情况可选择忽略该漏洞提示】 漏洞修复 找到wp-includes/http.php这个文件,在文件的465行附近找到:
1 |
$same_host = strtolower( $parsed_home['host'] ) === strtolower( $parsed_url['host'] ); |
把改行修改为成以下代码,或者注销该行添加。
1 2 3 4 5 |
if (isset($parsed_home['host'])) { $same_host = (strtolower($parsed_home['host']) === strtolower($parsed_url['host']) || 'localhost' === strtolower($parsed_url['host'])); } else { $same_host = false; }; |
还是这个文件,在 478行左右找以下代码
1 |
if ( 127 === $parts[0] || 10 === $parts[0] |
替换成
1 |
if ( 127 === $parts[0] || 10 === $parts[0] || 0 === $parts[0] |
如果在修改的时候发现478该行代码已经是修改过的代码,请忽略。 漏洞验证 登录阿里云帐号,在服务器安全页面点击验证。 参考连接: https://my.oschina.net/u/1433006/blog/752189 from:http://www.sijitao.net/2508.html
View Details目标:为提高数据库表更新(update)效率,使用多线程更新。其实这里也可以考虑另一种方法批量更新,不过如果更新失败了,同一事务(transaction)中的其他更新语句就会回滚,比较麻烦,所在还是简单点用多线程去处理。 困难点:开始是想把需要更新的数据等分到线程中去处理,不过搞了一段时间都没成功,主要是没有什么办法把动态参数从线程外传进线程内。后来换了个思路,每个线程去拿一条数据去更新,拿数据时同步处理。这样之后就可以了。 例子(部分外部类没有写上去,所以只能参考,要运行需要改改):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; public class BaiduBaikeJob { static final Logger logger = LoggerFactory .getLogger(BaiduBaikeJob.class); @Autowired private MongoLockService mongoLockService; @Autowired private WeiboPersonService weiboPersonService; @Resource(name = "globalProperties") private PropertyPlaceholderConfigurer config; final int THREAD_COUNT = 10; AtomicInteger updCounter = new AtomicInteger(0); AtomicInteger next = new AtomicInteger(0); private CountDownLatch threadCompletedCounter = new CountDownLatch(THREAD_COUNT); /** * 每隔 1小时,获得百度百科里的人物信息 */ public void baiduBaikeRun() { if ("true".equalsIgnoreCase((String) config.getProperty("runBaiduBaikeJob", "false")) && mongoLockService.getLock(MongoLockService.LOCK_BAIDU_BAIKE)) { List<WeiboPerson> unBaikeFills = null; try { unBaikeFills = weiboPersonService.findUnBaikeFills(2000); if (unBaikeFills != null && !unBaikeFills.isEmpty()) { List<WeiboPerson> weiboPersonList = new ArrayList<WeiboPerson>(); for (final WeiboPerson person : unBaikeFills) { // 获取百度百科信息 WeiboPerson weiboPerson = BaiduBaikeUtils.getBaiduBaikeInfo(person.getName()); weiboPerson.setId(person.getId()); weiboPerson.setName(person.getName()); weiboPerson.setTenantId(person.getTenantId()); weiboPerson.setGroupId(person.getGroupId()); // 更新状态 if (!StringUtils.isEmptyString(weiboPerson.getDescription())) { weiboPerson.setFlagBaike(WeiboPerson.BAIKE_SUCCESS); } else { weiboPerson.setFlagBaike(WeiboPerson.BAIKE_FAIL); } weiboPerson.setLastUpdDate(new Date()); weiboPersonList.add(weiboPerson); } // 首次更新或过期更新 baiduBaikeRunInMultiThreads(weiboPersonList); } } catch (Exception e) { logger.error("update baidu baike error," + e.getClass().getName() + ": " + e.getMessage()); } finally { try { mongoLockService.releaseLock(MongoLockService.LOCK_BAIDU_BAIKE); } catch (Exception e) { logger.error("release lock error ", e); } } } } /** * 多线程处理:更新table */ private void baiduBaikeRunInMultiThreads(final List<WeiboPerson> weiboPersonList) { ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executor.submit(new Runnable() { public void run() { WeiboPerson weiboPerson = getNext(weiboPersonList); while (null != weiboPerson) { try { // 首次更新或过期更新 weiboPersonService.update(weiboPerson); } catch (Exception e) { logger.error("table weiboPerson update error ", e); } updCounter.incrementAndGet(); // System.out.println("Thread:" + Thread.currentThread().getName() + ", counter:" + updCounter + ", name:" + weiboPerson.getName()); weiboPerson = getNext(weiboPersonList); } threadCompletedCounter.countDown(); } }); } closeThreadPool(executor); } /** * 同步处理:获取需要更新的一条微博人物 */ private synchronized WeiboPerson getNext(List<WeiboPerson> weiboPersonList){ if(next.intValue()>=weiboPersonList.size()) return null; next.incrementAndGet(); return weiboPersonList.get(next.intValue()-1); } /** * 关闭线程池 */ private void closeThreadPool(final ExecutorService executor) { try { threadCompletedCounter.await(); executor.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { // mock List<WeiboPerson> weiboPersonList = new ArrayList<WeiboPerson>(); int i = 1; while (i <= 10) { WeiboPerson weiboPerson = new WeiboPerson(); weiboPerson.setName("a" + i); weiboPersonList.add(weiboPerson); i++; } // test multi-thread BaiduBaikeJob baiduBaikeJob = new BaiduBaikeJob(); baiduBaikeJob.baiduBaikeRunInMultiThreads(weiboPersonList); } } |
from:http://blog.csdn.net/textboy/article/details/44680289
View Details1.项目背景 这里简单介绍一下项目需求背景,之前公司的项目基于EF++Repository+UnitOfWork的框架设计的,其中涉及到的技术有RabbitMq消息队列,Autofac依赖注入等常用的.net插件。由于公司的发展,业务不断更新,变得复杂起来,对于数据的实时性、存储容量要求也提高了一个新的高度。数据库上下文DbContext设计的是单例模式,基本上告别了多线程高并发的数据读写能力,看了园子里很多大神的博客,均为找到适合自己当前需求的DbContext的管理方式。总结目前主要的管理方式: 1)DbContext单例模式(长连接)。即公司之前的设计。很明显,这种设计方式无法支持多线程同步数据操作。报各种错误,最常见的,比如:集合已修改,无法进行枚举操作。—弃用 2)Using模式(短连接)。这种模式适合一些对于外键,导航属性不经常使用的场合,由于导航属性是放在上下文缓存中的,一旦上下文释放掉,导航属性就为null。当然,也尝试了其他大神的做法,比如,在上下文释放之前转换为 ToList或者使用饥饿加载的方式(ps:这种方式很不灵活,你总不可能遇到一个类类型就去利用反射加载找到它具有的导航属性吧或者直接InCluding),这些方法依旧没有办法解决目前的困境。也尝试这直接赋值给一个定义的同类 型的变量,但是对于这种带导航的导航的复杂类的深拷贝,没有找到合适的路子,有知道的可以告诉我,非常感谢! 以上两种方式及网上寻找的其他方式都没有解决我的问题。这里先上一下之前的Repository:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
1 using System.Data.Entity; 2 using System.Data.Entity.Validation; 3 4 namespace MM.Data.Library.Entityframework 5 { 6 public class EntityFrameworkRepositoryContext : RepositoryContext, IEntityFrameworkRepositoryContext 7 { 8 protected DbContext container; 9 10 public EntityFrameworkRepositoryContext(DbContext container) 11 { 12 this.container = container; 13 } 14 15 public override void RegisterNew<TAggregateRoot>(TAggregateRoot obj) 16 { 17 this.container.Set<TAggregateRoot>().Add(obj); 18 this.IsCommit = false; 19 } 20 21 public override void RegisterModified<TAggregateRoot>(TAggregateRoot obj) 22 { 23 if (this.container.Entry<TAggregateRoot>(obj).State == EntityState.Detached) 24 { 25 this.container.Set<TAggregateRoot>().Attach(obj); 26 } 27 this.container.Entry<TAggregateRoot>(obj).State = EntityState.Modified; 28 this.IsCommit = false; 29 } 30 31 public override void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj) 32 { 33 this.container.Set<TAggregateRoot>().Remove(obj); 34 this.IsCommit = false; 35 } 36 37 public override void Rollback() 38 { 39 this.IsCommit = false; 40 } 41 42 protected override void DoCommit() 43 { 44 if (!IsCommit) 45 { 46 //var count = container.SaveChanges(); 47 //IsCommit = true; 48 try 49 { 50 var count = container.SaveChanges(); 51 IsCommit = true; 52 } 53 catch (DbEntityValidationException dbEx) 54 { 55 foreach (var validationErrors in dbEx.EntityValidationErrors) 56 { 57 foreach (var validationError in validationErrors.ValidationErrors) 58 { 59 } 60 } 61 IsCommit = false; 62 } 63 } 64 } 65 66 public System.Data.Entity.DbContext DbContext 67 { 68 get { return container; } 69 } 70 71 public override void Dispose() 72 { 73 if (container != null) 74 container.Dispose(); 75 } 76 } 77 } |
View Code 2.设计思路及方法 从上下文的单例模式来看,所要解决的问题无非就是在多线程对数据库写操作上面。只要在这上面做手脚,问题应该就能引刃而解。我的想法是将所有的要修改的数据分别放入UpdateList,InsertList,DeleteList三个集合中去,然后提交到数据库保存。至于DbContext的管理,通过一个数据库工厂获取,保证每一个数据库的连接都是唯一的,不重复的(防止发生类似这种错误:正在创建模型,此时不可使用上下文。),用的时候直接去Factory拿。等到数据库提交成功后,清空集合数据。看起来,实现起来很容易,但是因为还涉及到其他技术,比如Redis。所以实现过程费劲。也许我的能力还差很多。总之,废话不多说,直接上部分实现代码: 数据库上下文建立工厂:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
1 /// <summary> 2 /// 数据库建立工厂 3 /// Modify By: 4 /// Modify Date: 5 /// Modify Reason: 6 /// </summary> 7 public sealed class DbFactory 8 { 9 public static IDbContext GetCurrentDbContext(string connectstring,string threadName) 10 { 11 lock (threadName) 12 { 13 //CallContext:是线程内部唯一的独用的数据槽(一块内存空间) 14 //传递Context进去获取实例的信息,在这里进行强制转换。 15 var Context = CallContext.GetData("Context") as IDbContext; 16 17 if (Context == null) //线程在内存中没有此上下文 18 { 19 var Scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 20 //如果不存在上下文 创建一个(自定义)EF上下文 并且放在数据内存中去 21 Context = Scope.Resolve<IDbContext>(new NamedParameter("connectionString", connectstring)); 22 CallContext.SetData("Context", Context); 23 } 24 else 25 { 26 27 if (!Context.ConnectionString.Equals(connectstring)) 28 { 29 var Scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 30 //如果不存在上下文 创建一个(自定义)EF上下文 并且放在数据内存中去 31 Context = Scope.Resolve<IDbContext>(new NamedParameter("connectionString", connectstring)); 32 CallContext.SetData("Context", Context); 33 } 34 } 35 return Context; 36 } 37 } 38 39 } |
View Code Repository:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
1 public class RepositoryBase<T, TContext> : IRepositoryBase<T> where T : BaseEntity 2 3 where TContext : ContextBase, IDbContext, IDisposable, new() 4 { 5 public List<T> InsertList { get; set; } 6 public List<T> DeleteList { get; set; } 7 public List<T> UpdateList { get; set; } 8 9 #region field 10 11 protected readonly string Connectstring; 12 ///// <summary> 13 ///// </summary> 14 //protected static IDbContext Context; 15 protected IDbContext dbContext; 16 private static readonly ILifetimeScope Scope; 17 public static int xcount = 0; 18 /////// <summary> 19 /////// </summary> 20 //protected readonly DbSet<T> Dbset; 21 22 #endregion 23 24 #region ctor 25 26 static RepositoryBase() 27 { 28 Scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 29 } 30 31 /// <summary> 32 /// 使用默认连接字符串name=connName 33 /// </summary> 34 public RepositoryBase() : this("") 35 { 36 } 37 38 /// <summary> 39 /// 构造函数 40 /// </summary> 41 /// <param name="connectionString">连接字符串</param> 42 public RepositoryBase(string connectionString) 43 { 44 InsertList = new List<T>(); 45 DeleteList = new List<T>(); 46 UpdateList = new List<T>(); 47 48 49 //*****做以下调整,初始化,建立所有数据库连接,保持长连接状态,在用的时候去判断使用连接 50 51 52 //todo 待处理 53 54 55 if (string.IsNullOrWhiteSpace(connectionString)) 56 { 57 var name = DataBase.GetConnectionString(Activator.CreateInstance<T>().DbType); 58 //Context= ContextHelper.GetDbContext(Activator.CreateInstance<T>().DbType); 59 connectionString = name; 60 } 61 Connectstring = connectionString; 62 63 // Context = Scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 64 65 //Context = new TContext { ConnectionString = connectionString }; 66 67 68 // Dbset = Context.Set<T>(); 69 70 //var loggerFactory = ((DbContext)Context).GetService<ILoggerFactory>(); 71 //loggerFactory.AddProvider(new DbLoggerProvider(Console.WriteLine)); 72 //loggerFactory.AddConsole(minLevel: LogLevel.Warning); 73 } 74 75 //public RepositoryBase(TContext context) 76 //{ 77 // Context = context; 78 // Dbset = context.Set<T>(); 79 //} 80 81 #endregion 82 83 #region Method 84 85 //public virtual IDbContext GetDbContext(ILifetimeScope scope) 86 //{ 87 88 //} 89 90 #region Check Model 91 92 /// <summary> 93 /// 校正Model 94 /// </summary> 95 protected virtual void ValidModel() 96 { 97 } 98 99 #endregion 100 101 #region Update 102 103 public virtual void Update(T entity) 104 { 105 Check.NotNull(entity, "entity"); 106 UpdateList.Add(entity); 107 //context.Set<T>().Update(entity); 108 } 109 110 public virtual void Update(IEnumerable<T> entities) 111 { 112 Check.NotNull(entities, "entities"); 113 UpdateList.AddRange(entities); 114 } 115 116 #endregion 117 118 #region PageList 119 120 public virtual IEnumerable<T> GetPageList(Expression<Func<T, bool>> where, Expression<Func<T, object>> orderBy, 121 int pageIndex, int pageSize) 122 { 123 //todo 124 } 125 126 #endregion 127 128 #region Insert 129 130 public virtual void Add(T entity) 131 { 132 Check.NotNull(entity, "entity"); 133 //排除已经存在的项(对于多线程没有任何用处) 134 if (!InsertList.Exists(e => e.Equals(entity))) 135 { 136 InsertList.Add(entity); 137 } 138 139 } 140 141 public virtual void Add(IEnumerable<T> entities) 142 { 143 Check.NotNull(entities, "entities"); 144 InsertList.AddRange(entities); 145 } 146 147 public void BulkInsert(IEnumerable<T> entities) 148 { 149 Check.NotNull(entities, "entities"); 150 InsertList.AddRange(entities); 151 } 152 153 #endregion 154 155 #region Delete 156 157 public virtual void Delete(int id) 158 { 159 var entity = GetById(id); 160 Delete(entity); 161 // throw new NotImplementedException("Delete(int id)"); 162 } 163 164 public virtual void Delete(string id) 165 { 166 throw new NotImplementedException("Delete(string id)"); 167 } 168 169 public virtual void Delete(T entity) 170 { 171 Check.NotNull(entity, "entity"); 172 DeleteList.Add(entity); 173 } 174 175 public virtual void Delete(IEnumerable<T> entities) 176 { 177 Check.NotNull(entities, "entities"); 178 foreach (var x1 in DeleteList) 179 { 180 DeleteList.Add(x1); 181 } 182 } 183 184 public virtual void Delete(Expression<Func<T, bool>> where) 185 { 186 var list = DeleteList.Where(where.Compile()); 187 Delete(list); 188 } 189 190 #endregion 191 192 #region Commit 193 194 public int Commit() 195 { 196 ValidModel(); 197 //var x = Activator.CreateInstance<T>(); 198 //Context = ContextHelper.GetDbContext(x.DbType); 199 //using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 200 //{ 201 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 202 203 //var loggerFactory = Activator.CreateInstance<ILoggerFactory>();// ((DbContext)context).GetService<ILoggerFactory>(); 204 //loggerFactory.AddProvider(new DbLoggerProvider(Console.WriteLine)); 205 dbContext = DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 206 var dbset = dbContext.Set<T>(); 207 if (InsertList != null && InsertList.Any()) 208 { 209 List<T> InsertNewList = InsertList.Distinct(new PropertyComparer<T>("Id")).ToList();//按照特定规则排除重复项 210 dbset.AddRange(InsertNewList); 211 } 212 213 if (DeleteList != null && DeleteList.Any()) 214 DeleteList.ForEach(t => 215 { 216 // Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 217 //dbContext.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 218 dbset.Attach(t); 219 dbset.Remove(t); 220 }); 221 if (UpdateList != null && UpdateList.Any()) 222 { 223 List<T> UpdateNewList = UpdateList.Distinct(new PropertyComparer<T>("Id")).ToList();//按照特定规则排除重复项 224 UpdateNewList.ForEach(t => 225 { 226 //Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 227 // dbContext.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 228 dbContext.Entry(t).State = EntityState.Modified; 229 });//.UpdateRange(UpdateNewList); 230 } 231 var result = 0; 232 try 233 { 234 result = dbContext.SaveChanges(); 235 } 236 catch (Exception ex) 237 { 238 239 // throw; 240 } 241 242 if (InsertList != null && InsertList.Any()) 243 InsertList.Clear(); 244 if (DeleteList != null && DeleteList.Any()) 245 DeleteList.Clear(); 246 if (UpdateList != null && UpdateList.Any()) 247 UpdateList.Clear(); 248 return result; 249 //} 250 } 251 252 public async Task<int> CommitAsync() 253 { 254 ValidModel(); 255 //todo 256 257 } 258 259 #endregion 260 261 #region Query 262 public IQueryable<T> Get() 263 { 264 return GetAll().AsQueryable(); 265 } 266 //public virtual T Get(Expression<Func<T, bool>> @where) 267 //{ 268 // using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 269 // { 270 271 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 272 // var dbset = context.Set<T>(); 273 // return dbset.FirstOrDefault(where); 274 // } 275 //} 276 277 public virtual async Task<T> GetAsync(Expression<Func<T, bool>> @where) 278 { 279 //todo 280 } 281 282 public virtual T GetById(int id) 283 { 284 throw new NotImplementedException("GetById(int id)"); 285 } 286 287 public virtual async Task<T> GetByIdAsync(int id) 288 { 289 throw new NotImplementedException("GetById(int id)"); 290 } 291 292 public virtual T GetById(string id) 293 { 294 throw new NotImplementedException("GetById(int id)"); 295 } 296 297 public virtual async Task<T> GetByIdAsync(string id) 298 { 299 throw new NotImplementedException("GetById(int id)"); 300 } 301 302 public virtual T Get(Expression<Func<T, bool>> @where)//, params string[] includeProperties 303 { 304 //var scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 305 //{ 306 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 307 //Thread.Sleep(50); 308 //lock (Context) 309 { 310 dbContext= DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 311 var dbset = dbContext.Set<T>().Where(e => !e.IsDeleted).AsQueryable(); 312 var entity = dbset.FirstOrDefault(where); 313 //test 314 // Context.Entry(entity).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 315 return entity; 316 } 317 318 319 //} 320 } 321 322 public virtual IEnumerable<T> GetAll() 323 { 324 //Thread.Sleep(50); 325 //lock (Context) 326 { 327 dbContext = DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 328 var dbset = dbContext.Set<T>().Where(e => !e.IsDeleted); 329 //test 330 //dbset.ToList().ForEach(t => 331 //{ 332 // Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 333 //}); 334 335 return dbset; 336 } 337 338 339 340 341 //var scope = UnitoonIotContainer.Container.BeginLifetimeScope(); 342 343 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 344 345 } 346 347 public async virtual Task<IEnumerable<T>> GetAllAsync() 348 { 349 //todo 350 } 351 352 public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) 353 { 354 //using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 355 //{ 356 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 357 358 // var dbset = context.Set<T>(); 359 //Thread.Sleep(50); 360 //lock (Context) 361 { 362 dbContext = DbFactory.GetCurrentDbContext(Connectstring, Thread.CurrentThread.Name); 363 var dbset = dbContext.Set<T>().Where(e => !e.IsDeleted); 364 //test 365 //dbset.ToList().ForEach(t => 366 //{ 367 // Context.Entry(t).State = EntityState.Detached;//将之前上下文跟踪的状态丢弃 368 //}); 369 return dbset.Where(@where).ToList(); 370 } 371 372 //} 373 } 374 375 public virtual async Task<IEnumerable<T>> GetManyAsync(Expression<Func<T, bool>> where) 376 { 377 //todo 378 } 379 380 public virtual IEnumerable<T> IncludeSubSets(params Expression<Func<T, object>>[] includeProperties) 381 { 382 //todo 383 } 384 385 #region navigation 386 /// <summary> 387 /// 加载导航 388 /// </summary> 389 /// <param name="where"></param> 390 /// <param name="includeProperties"></param> 391 /// <returns></returns> 392 //public virtual T Get(Expression<Func<T, bool>> @where, params Expression<Func<T, object>>[] includeProperties) 393 //{ 394 // using (var scope = UnitoonIotContainer.Container.BeginLifetimeScope()) 395 // { 396 397 // var context = scope.Resolve<IDbContext>(new NamedParameter("connectionString", Connectstring)); 398 // var dbset = context.Set<T>(); 399 // var query = includeProperties.Aggregate<Expression<Func<T, object>>, IQueryable<T>>(dbset, 400 // (current, includeProperty) => current.Include(includeProperty)); 401 // return query.FirstOrDefault(where); 402 // } 403 //} 404 405 //public virtual T Get(Expression<Func<T, bool>> @where)//, params string[] includeProperties 406 //{ 407 // //反射获取导航 408 // var includeProperties = 409 // Activator.CreateInstance<T>().GetType().GetProperties().Where(p => p.GetMethod.IsVirtual).Select(e => e.Name).ToArray(); 410 411 //todo 412 //} 413 #endregion 414 public List<TDynamicEntity> GetDynamic<TTable, TDynamicEntity>(Expression<Func<TTable, object>> selector, 415 Func<object, TDynamicEntity> maker) where TTable : class 416 { 417 //todo 418 } 419 420 public List<TDynamicEntity> GetDynamic<TTable, TDynamicEntity>(Func<TTable, object> selector, 421 Func<object, TDynamicEntity> maker) where TTable : class 422 { 423 //todo 424 425 } 426 427 #endregion 428 429 #region Count 430 431 public virtual async Task<int> CountAsync() 432 { 433 //todo 434 } 435 436 public virtual async Task<int> CountByAsync(Expression<Func<T, bool>> where) 437 { 438 //todo 439 } 440 441 #endregion 442 443 #region Exists 444 445 public virtual bool Exists(string id) 446 { 447 throw new NotImplementedException(); 448 } 449 450 public virtual bool Exists(int id) 451 { 452 throw new NotImplementedException(); 453 } 454 455 public virtual async Task<bool> ExistsAsync(string id) 456 { 457 throw new NotImplementedException(); 458 } 459 460 public virtual async Task<bool> ExistsAsync(int id) 461 { 462 throw new NotImplementedException(); 463 } 464 465 public virtual bool Exists(Expression<Func<T, bool>> @where) 466 { 467 throw new NotImplementedException(); 468 } 469 470 public virtual async Task<bool> ExistsAsync(Expression<Func<T, bool>> @where) 471 { 472 throw new NotImplementedException(); 473 } 474 475 #endregion 476 477 478 #endregion 479 } |
http://blog.csdn.net/wodeai1235/article/details/54923072
View Details表示伪随机数生成器,这是一种能够产生满足某些随机性统计要求的数字序列的设备。 若要浏览此类型的.NET Framework 源代码,请参阅 Reference Source。 命名空间: System 程序集: mscorlib(位于 mscorlib.dll) 继承层次结构 System.Object System.Random 语法 C#
1 2 3 |
[SerializableAttribute] [ComVisibleAttribute(true)] public class Random |
构造函数 名称 说明 Random() 新实例初始化 Random 类,使用依赖于时间的默认种子值。 Random(Int32) 新实例初始化 Random 类,使用指定的种子值。 方法 名称 说明 Equals(Object) 确定指定的对象是否等于当前对象。(继承自 Object。) Finalize() 在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object。) GetHashCode() 作为默认哈希函数。(继承自 Object。) GetType() 获取当前实例的 Type。(继承自 Object。) MemberwiseClone() 创建当前 Object 的浅表副本。(继承自 Object。) Next() 返回一个非负随机整数。 Next(Int32) 返回一个小于所指定最大值的非负随机整数。 Next(Int32, Int32) 返回在指定范围内的任意整数。 NextBytes(Byte[]) 用随机数填充指定字节数组的元素。 NextDouble() 返回一个大于或等于 0.0 且小于 1.0 的随机浮点数。 Sample() 返回一个介于 0.0 和 1.0 之间的随机浮点数。 ToString() 返回表示当前对象的字符串。(继承自 Object。) 说明 若要查看此类型的.NET Framework 源代码,请参阅 Reference Source。 您可以浏览源代码、 下载脱机查看参考资料和调试; 在逐句通过源 (包括修补程序和更新)see instructions. 伪随机数字从一组有限的数字选择以相同的概率。 因为数学算法可用于选择它们,但它们是充分随机实用的角度而言,所选的数字不完全随机的。 当前实现 Random 类根据 Donald E.Knuth 删减随机数生成器算法的修改版本。 有关详细信息,请参阅 D.e。 Knuth。 计算机编程,卷 2 的艺术︰ Seminumerical 算法。 Addison-wesley,Reading,MA,第三个版本,1997年。 若要生成加密性极安全的随机数字,如一个适合于创建随机密码,使用 RNGCryptoServiceProvider 类或从派生类 System.Security.Cryptography.RandomNumberGenerator。 在本主题中: 实例化的随机数字生成器 避免多个实例化 System.Random 类和线程安全 生成不同类型的随机数字 替换您自己的算法 如何使用到 System.Random… 检索相同的随机值序列 检索唯一的随机值序列 […]
View DetailsBigDecimal类 对于不需要任何准确计算精度的数字可以直接使用float或double,但是如果需要精确计算的结果,则必须使用BigDecimal类,而且使用BigDecimal类也可以进行大数的操作。BigDecimal类的常用方法如表11-15所示。 表11-15 BigDecimal类的常用方法 序号 方 法 类型 描 述 1 public BigDecimal(double val) 构造 将double表示形式转换 为BigDecimal 2 public BigDecimal(int val) 构造 将int表示形式转换为 BigDecimal 3 public BigDecimal(String val) 构造 将字符串表示 形式转换为BigDecimal 4 public BigDecimal add(BigDecimal augend) 普通 加法 5 public BigDecimal subtract(BigDecimal subtrahend) 普通 减法 6 public BigDecimal multiply(BigDecimal multiplicand) 普通 乘法 7 public BigDecimal divide(BigDecimal divisor) 普通 除法 范例:进行四舍五入的四则运算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package org.lxh.demo11.numberdemo; import java.math.BigDecimal; class MyMath { public static double add(double d1, double d2) { // 进行加法运算 BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); return b1.add(b2).doubleValue(); } public static double sub(double d1, double d2) { // 进行减法运算 BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); return b1.subtract(b2).doubleValue(); } public static double mul(double d1, double d2) { // 进行乘法运算 BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); return b1.multiply(b2).doubleValue(); } public static double div(double d1, double d2,int len) {// 进行除法运算 BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); return b1.divide(b2,len,BigDecimal. ROUND_HALF_UP).doubleValue(); } public static double round(double d, int len) { // 进行四舍五入 操作 BigDecimal b1 = new BigDecimal(d); BigDecimal b2 = new BigDecimal(1); // 任何一个数字除以1都是原数字 // ROUND_HALF_UP是BigDecimal的一个常量, 表示进行四舍五入的操作 return b1.divide(b2, len,BigDecimal. ROUND_HALF_UP).doubleValue(); } } public class BigDecimalDemo01 { public static void main(String[] args) { System.out.println("加法运算:" + MyMath.round(MyMath.add(10.345, 3.333), 1)); System.out.println("乘法运算:" + MyMath.round(MyMath.mul(10.345, 3.333), 3)); System.out.println("除法运算:" + MyMath.div(10.345, 3.333, 3)); System.out.println("减法运算:" + MyMath.round(MyMath.sub(10.345, 3.333), 3)); } } |
BigDecimal是Java中用来表示任意精确浮点数运算的类,在BigDecimal中,使用unscaledValue × 10-scale来表示一个浮点数。其中,unscaledValue是一个BigInteger,scale是一个int。从这个表示方法来看,BigDecimal只能标识有限小数,不过可以表示的数据范围远远大于double,在实际应用中基本足够了。 下面提一下两个精度问题: 问题一:BigDecimal的精度问题(StackOverflow上有个家伙问了相关的问题)
1 2 3 4 5 |
System.out.println(new BigDecimal(0.1).toString()); // 0.1000000000000000055511151231257827021181583404541015625 System.out.println(new BigDecimal("0.1").toString()); // 0.1 System.out.println(new BigDecimal( Double.toString(0.1000000000000000055511151231257827021181583404541015625)).toString());// 0.1 System.out.println(new BigDecimal(Double.toString(0.1)).toString()); // 0.1 |
分析一下上面代码的问题(注释的内容表示此语句的输出) 第一行:事实上,由于二进制无法精确地表示十进制小数0.1,但是编译器读到字符串"0.1"之后,必须把它转成8个字节的double值,因此,编译器只能用一个最接近的值来代替0.1了,即0.1000000000000000055511151231257827021181583404541015625。因此,在运行时,传给BigDecimal构造函数的真正的数值是0.1000000000000000055511151231257827021181583404541015625。 第二行:BigDecimal能够正确地把字符串转化成真正精确的浮点数。 第三行:问题在于Double.toString会使用一定的精度来四舍五入double,然后再输出。会。Double.toString(0.1000000000000000055511151231257827021181583404541015625)输出的事实上是"0.1",因此生成的BigDecimal表示的数也是0.1。 第四行:基于前面的分析,事实上这一行代码等价于第三行 结论: 1.如果你希望BigDecimal能够精确地表示你希望的数值,那么一定要使用字符串来表示小数,并传递给BigDecimal的构造函数。 2.如果你使用Double.toString来把double转化字符串,然后调用BigDecimal(String),这个也是不靠谱的,它不一定按你的想法工作。 3.如果你不是很在乎是否完全精确地表示,并且使用了BigDecimal(double),那么要注意double本身的特例,double的规范本身定义了几个特殊的double值(Infinite,-Infinite,NaN),不要把这些值传给BigDecimal,否则会抛出异常。 问题二:把double强制转化成int,难道不是扔掉小数部分吗?
1 |
int x=(int)1023.99999999999999; // x=1024为什么? |
原因还是在于二进制无法精确地表示某些十进制小数,因此1023.99999999999999在编译之后的double值变成了1024。 所以,把double强制转化成int确实是扔掉小数部分,但是你写在代码中的值,并不一定是编译器生成的真正的double值。 验证代码:
1 2 3 4 5 |
double d = 1023.99999999999999; int x = (int) d; System.out.println(new BigDecimal(d).toString()); // 1024 System.out.println(Long.toHexString(Double.doubleToRawLongBits(d))); // 4090000000000000 System.out.println(x); // 1024 |
前面提过BigDecimal可以精确地把double表示出来还记得吧。 我们也可以直接打印出d的二进制形式,根据IEEE 754的规定,我们可以算出0x4090000000000000=(1024)。 […]
View Details[java] view plain copy print? public class HelloWorldwww{ public static void main(String args[]){ int num ; // 声明一个整型变量num num = 3 ; // 将整型变量赋值为3 // 输出字符串,这里用"+" 号连接变量 System.out.println("这是数字"+num); System.out.println("我有"+num+" 本书!"); } }
1 2 3 4 5 6 7 8 9 10 |
public class HelloWorldwww{ public static void main(String args[]){ int num ; // 声明一个整型变量num num = 3 ; // 将整型变量赋值为3 // 输出字符串,这里用"+" 号连接变量 System.out.println("这是数字"+num); System.out.println("我有"+num+" 本书!"); } } |
通过DOS编译 提示 错误:编码GBK的不可映射字符 检查: 1、 查本机区域语言设置中文没有问题 2、 此程序可以在eclipse上正常运行 右键properties-resource-text file encoding 查是UTF-8 解决方法: 1、运行是使用javac -encoding UTF-8HelloWorlewww.java 编译通过 2、记事本打开java源文件,另存为选择ANSI编码 编译通过 说明: ANSI:美国国家标准协会,系统预设的标准文字储存格式。简体中文编码GB2312,实际上它是ANSI的一个代码页936 UTF-8:通用字集转换格式,这是为传输而设计的编码,2进制,以8位为单元对Unicode进行编码,如果使用只能在同类位元组内支持8个位元的重要资料一类的旧式传输媒体,可选择UTF-8格式。 在UTF-8里,英文字符仍然跟ASCII编码一样,因此原先的函数库可以继续使用。而中文的编码范围是在0080-07FF之间,因此是2个字节表示(但这两个字节和GB编码的两个字节是不同的),用专门的Unicode处理类可以对UTF编码进行处理。 from:http://blog.csdn.net/l1028386804/article/details/46583279
View Details