下载:nhibernate
使用方式:
1,项目引入dll:
* Antlr3.Runtime.dll
* Castle.Core.dll
* Iesi.Collections.dll
* LinFu.DynamicProxy.dll
* log4net.dll
* NHibernate.ByteCode.Castle.dll
* NHibernate.ByteCode.LinFu.dll
* NHibernate.dll
* nunit.core.dll
* nunit.framework.dll
2,编写数据库连接:对于一般的应用程序,编写hibernate.cfg.xml放在根目录下,属性设置为始终复制,因为nhibernate是对输出目录bin的文件进行读取的,对于web可在web.config中进行添加。
1)hibernate.cfg.xml,在官方文档的Configuration_Templates文件夹下有模板,例子如下:
NHibernate.Driver.SqlClientDriver
Server=(local);initial catalog=nhibernate;Integrated Security=SSPI;user id=sa;password=123abc;min pool size=1;max pool size=512
10
false
NHibernate.Dialect.MsSql2000Dialect
true
60
true 1, false 0, yes 'Y', no 'N'
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
2) web.config 在下进行Nhibernate 配置
3,编写实体类
4,编写实体类映射文件 如:Product.hbm.xml,将此其属性设置为嵌入资源,这是因为NHibernate是通过查找程序集中的资源文件来进行实体的映射,故要将映射文件嵌入到程序集中。
如:
注:1), 要为Microsoft Visual Studio 2008添加编写NHibernate配置文件智能提示的功能。只要在下载的NHibernate里找到configuration.xsd和 nhibernate-mapping.xsd两个文件并复制到X:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas目录即可。
2),此时即可通过架构类来自动生成数据库表
var cfg = new Configuration();
cfg.Configure();
cfg.AddAssembly(typeof(Product).Assembly);
new SchemaExport(cfg).Execute(true, true, false);
5,因为操作数据库是用Session来完成的,可编写一helper类,用来集中处理, 编写NHibernateHelper.cs如下:
using NHibernate;
using NHibernate.Cfg;
using NHebernateTest.Domain;
namespace NHebernateTest.Repositories
{
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new Configuration();
configuration.Configure();
//configuration.AddAssembly(typeof(Product).Assembly);
_sessionFactory = configuration.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
}
6,编写操作类及接口,操作类即是引用上面的helper类进行数据库的操作。
1)CRUD操作:
using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Update(product); //session.Save(product);session.Delete(product);
transaction.Commit();
}
2)查询
* 据关键字查询:session.Get(productId);
* 据其它属性查询
* 返回一个值:session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq("Name", name)).UniqueResult();
* 返回一个集合:session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq("Name", name)).List();
分类: .NET
SchemaExport:根据实体类的配置文件生成数据库表
先编写持久化类和映射文件,然后使用SchemaExport工具生成数据库架构。这样的方式就是领域驱动设计/开发。
好处:当领域模型需要改变,只需修改NHibernate结构和应用程序,不需要修改数据库架构,只要利用SchemaExport工具重新生成数据库架构就可以了。但是使用数据库只是其中一种方式,我们也可以使用XML文件来存储数据。
NHibernate的hbm2dll提供SchemaExport工具:给定一个连接字符串和映射文件,不需输入其他东西就可以按照持久化类和映射文件自动生成数据库架构
SchemaExport工具就是把DDL脚本输出到标准输出,同时/或者执行DDL语句。SchemaExport工具提供了三个方法,分别是 Drop()、Create()、Execute(),前两个方法实质是调用Execute()方法。通常使用Execute()方法来生成数据库架构的。
如:
var cfg = new Configuration();
cfg.Configure(); //自动寻找hibernate.cfg.xml文件读取数据库连接信息
cfg.AddAssembly(typeof(Product).Assembly); //根据Product类查找Product.hbm.xml
new SchemaExport(cfg).Execute(true, true, false);
//第一个true输出sql创建语句到控制台,第二个用来先删除后创建
NHibernate
多条件选择下拉框-DropDownCheckList
1,添加引用:DropDownCheckList.dll
2,将DropDownCheckList.js放置到网站根目录的aspnet_client\UNLV_IAP_WebControls\DropDownCheckList\文件夹下
3,演示代码
4,获取选择的数据:
Label1.Text = this.DropDownCheckList1.SelectedValuesToString(“,”, “”);
//Label2.Text = this.DropDownCheckList1.SelectedLabelsToString(“,”,””);
效果图:
引用:http://www.codeproject.com/KB/custom-controls/DropDownCheckList.aspx#xx2456914xx
获取路径
对于Windows程序 和Web 应用程序来说,他们运行的路径是不一样的,所以关键是判断当前运行的程序是哪种程序.于是可以使用如下的代码 string path = ""; if (System.Environment.CurrentDirectory == AppDomain.CurrentDomain.BaseDirectory)//Windows应用程序则相等 …{ path = AppDomain.CurrentDomain.BaseDirectory; } else …{ path = AppDomain.CurrentDomain.BaseDirectory + "Bin\"; }
HttpContext.Current.Request.Url.AbsoluteUri
//获取网站根目录
public static string GetRootURI()
{
string AppPath = "";
HttpContext HttpCurrent = HttpContext.Current;
HttpRequest Req;
if (HttpCurrent != null)
{
Req = HttpCurrent.Request;
string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
//直接安装在 Web 站点
AppPath = UrlAuthority;
else
//安装在虚拟子目录下
AppPath = UrlAuthority + Req.ApplicationPath;
}
return AppPath;
}
ASP.NET图形化显示数据
1,引入System.Web.DataVisualization.dll
工具箱添加
2,配置文件中增加:
<httpHandlers>
<add path=”ChartImg.axd” verb=”GET,HEAD” type=”System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″
validate=”false” />
</httpHandlers>
3,插入控件到页面使用。
4, 效果图如下:
参考自:http://www.codeproject.com/KB/web-image/chart1.aspx
C#随机数产生
Random ra = new Random() ;
Console.WriteLine(ra.Next());
Console.WriteLine(ra.Next(10))
生成规则
* 获取电脑启动以来的时间,与一固定值进行连续减法操作(0x9a4ec86 – Math.Abs(Environment.TickCount)),所得结果均匀的存放到一56位数组内
* 每次取时,第一次取SeedArray[0] – SeedArray[21]的值,然后顺移,故第二次取SeedArray[1] – SeedArray[22]的值….
* 因取的启动时间的间隔最小单位是0.5秒,故在这0.5秒内,若连续构造Random,产生随机数,因启动时间相同,故每次的SeedArray[0] – SeedArray[21]的值也会相同。为避免这种情况,应构造一个Random,连续用Next()取值,这样会递邓56位数组中的下一次相减数。
注:因产生数组的方法是固定的,传入同一启动时间,所得数组值也是固定的,故知C#随机数是伪随即数,这也符合计算机程序的特性的确定性,即:即对于相同的输入只能得出相同的输出。
生成一系列数字:0x9a4ec86 – Math.Abs(Environment.TickCount)
向系统事件查看器中写入日志-EventLog ,可创建,也可删除自定义的事件源
using System.Diagnostics;
{
static void Main(string[] args)
{
// Create the source, if it does not already exist.
if (!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created. Exit the application to allow it to be registered.
return;
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log.
myLog.WriteEntry("Writing to event log.");
}
WPF
WPF: Windows Presentation Foundation ,”我佩服”
- 由XAML代码和程序代码组成。
- 一套代码Web与桌面应用程序都可作用。
Ajax开发
1,VS2008默认带有AJAX Extensions组件
2,局部刷新:UpdatePanel
- 页面引入ScriptManager,设置EnablePartialRendering=”true”
- 将需局部刷新的代码块用UpdatePanel包裹
- 若想得到点击按纽触发局部刷新,设置UpdatePanel的Triggers
3,进度条:UpdateProgress: 它将显示页面上所有的UpdatePanel控件更新的进度信息。,
可用AssoicateUpdatePanelID指定关联的UpdatePanel
- 页面放置UpdatePanel
- 在UpdatePanel放置UpdateProgerss
数字证书
1,网页传输数据是明文形式,实现https形式可以保证其安全,一种方式就是数字证书加密。
2,SSL位于于HTTP协议层与TCP协议层之间,用于建立用户与服务器之间的加密通信,它是依靠数字证书实现的。
3,数字证书实现:
* 为服务器安装证书服务,在系统安装盘。
* 配置网站:IIS-网站属性-目录安全性-安全通信:服务器证书,让系统自动生成一个。
* 配置网站:IIS-网站属性-目录安全性-安全通信:编辑,指定安全方式
* 利用https://网站域名访问
C#语法拾遗
C#语法拾遗
1,using;
* using 命名空间名字;
* using 别名 = 包括详细命名空间信息的具体类型,以区别两个不同命名空间有相同的类名。
* using定义范围:即时释放资源,在范围结束时即时释放资源,
* 如: using (StreamWriter w = File.AppendText(“c:\\temp.txt”))
{
Log(context, w);
w.Close();
}
2,@符号的使用
* 将转义符当成一般字符使用:string s = @”c:\a.txt”;
* 忽略换行:string s =string s = @”sdf
sdf
sfsdf”;
3,预处理命令
* #warning 和#error : 若编译器遇到,则产生警告或错误信息,以提示开发者,而#error会直接退出编译
* 如:#warning : 测试使用,正式发布时请去掉下句代码
* #region description #endregion 将一段代码标记为一个指定名称的代码块,可直接折叠,便于阅读
4,对于引用类型,==类似于比较文件夹的路径是否相同,而equals()比较的是文件夹中的内容是否一样。注:对于string,==比较的是值。
原理:==比较的是栈,值变量存储在栈中,而引用类型地址也是存储在栈中。而equals比较的是堆,而引用类型的值就存在于堆中。
引用类型对应有多个字段,故地址存放于栈中,多个字段存放于堆中。
5,const是编译时常数,须在最开始赋初值,默认是static, 而readonly是运行是常数,默认不是static.
* const是编译时常数,故不能修饰引用类型,因为引用类型的构造要在运行时完成。不过string与null除外。
* 注:数组也是引用类型,同样不可用const修饰。
* const默认是static,故不可在非静态方法中修饰局部变量。
6,sealed:不可继承,断子绝孙。virtual与override进行覆盖。
7,变量与属性的区别:属性是对字段的一种封装,可以控制读写,体现了面向对象的封装性。
8,class与struct的区别:class是引用类型,内存分配于堆上,而struct是引用类型,内存分配于线程的栈上。
类似百度文库效果实现
实现的效果如下:
步骤:
1,利用FileUpload控件做文件上传
2,转换:安装FlashPaper2.2,
在程序中调用cmd命令完成转换:
FlashPrinter.exe “test.doc” -o “test4.swf”
注:iis及应用程序池需开权限以执行FlashPrinter
如下:
try
{
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start();
string strOutput = null;
string outputPath = Server.MapPath("~//test5.swf");
string s = @"FlashPrinter.exe " + "\"" + FilePath + "\" -o \"" + outputPath + "\"";
p.StandardInput.WriteLine(s);
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
Console.WriteLine(strOutput);
p.WaitForExit();
p.Close();
lblMessage.Text = "success";
embed1.Attributes.Add("src", outputPath);
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
注:执行完之后可关掉进程
///?<summary>
///?根据进程名称来关闭进程
///?</summary>
///?<param?name="processName"></param>
private?static?void?KillPrecess(string?processName)
{
foreach?(Process?p?in?Process.GetProcesses())
{
if?(p.ProcessName?==?processName)
{
p.Kill();
}
}?
}
3,在线播放:若文档较小,一般的flash播放器即可。若文件很大,一次加载所有再显示文件的播放器显然会拖慢速度,这时需要了解的是一个开源的flexpaper播放器,它可以播放一帧一页的flash;要像百度文库、豆丁一样修改flexpaper,让它支持一次仅读取指定页数的flash;如果文档安全级别较高,不允许下载查看,则需要给flexpaper加上加密解密算法;如果需要登录用户才能查看,则要让flexpaper有登录UI。
文件上传:asp:FileUpload
1,页面放置控件FileUpload
2,代码:
string FileName = fileUpload1.PostedFile.FileName;
FileName = FileName.Substring(FileName.LastIndexOf("\\") + 1);// 取出文件名的路径(不包括文件的名称)
string upload_file = Server.MapPath("./upload/") + FileName;//取出服务器虚拟路径,存储上传文件
fileUpload1.PostedFile.SaveAs(upload_file);//上传文件
常用属性:
(1)FileUpload1.HasFile用来检查 FileUpload是否有指定文件。
(2)HttpContext.Current.Request.MapPath("~/") 则是获取网站所在的磁盘绝对路径的,如D:\Inetpub\ServerControls\路径,之所以要这么做,是因为FileUpload控件必须指定“绝对路径”,而非相对路径,同时绝对路径也必须有写入权限。
(3)FileUpload1.SaveAs()则是将上传文件存储在磁盘的方法。
(4)FileUpload1.FileName用于获取上传文件名称。
(5)FileUpload1.PostedFile.ContentLength 用于设置或获取上传文件大小,以Byte为单位。
(6)FileUpload1.PostedFile.ContentType 用于设置或获取上传文件的类型
调用cmd执行命令
注意:对于命令行,若路径中带有空格时,如D:\My Documents\a.txt时,将找不到此路径,可采用以下两种方法:
1,加引号如:"D:\My Documents\a.txt"
2, 变缩写:采用8个字符缩写,即写头六个字母(略去空白),另加波浪号和1 改成:D:\MyDocu~1
try
{
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start();
string strOutput = null;
string s = @"F:\DownLoad\wenku\FlashPaper2.2\FlashPaper2.2\FlashPrinter.exe " + "\"" + Server.MapPath("~//test.doc") + "\" -o \"" + Server.MapPath("~//test2.swf") + "\"";
p.StandardInput.WriteLine(s);
p.StandardInput.WriteLine("exit");
strOutput = p.StandardOutput.ReadToEnd();
Console.WriteLine(strOutput);
p.WaitForExit();
p.Close();
lblMessage.Text = "success";
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
Response输出指定内容,去掉页面自带的内容
Response输出指定内容,去掉页面自带的内容
//下面的方法,无论当前页面是什么内容,都只输出自己指定的数据。
Response.Clear(); //清除页面前的内容
Response.Write(“hahahahahahahahahhahahahahahahahhahahahaha”); //指定的内容
Response.End(); //之后的内容不再输出
抓取IP
抓取IP
REMOTE_ADDR:访问网站的最新的一个IP地址
HTTP_X_FORWARDED_FOR:中转IP集合即 从出发点到网站前的IP集合,以逗号分开
1,若直接访问网站,不经过代理,则REMOTE_ADDR为真实IP,HTTP_X_FORWARDED_FOR为空
2,若使用代理访问网站,则REMOTE_ADDR为最后一个经过的代理IP地址,而HTTP_X_FORWARDED_FOR集合中第一个为真实IP
由上得出抓取真实IP的方法为:
private string GetIP()
{
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
return Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(new char[] { ',' })[0];
}
else
{
return Request.ServerVariables["REMOTE_ADDR"];
}
}
注:REMOTE_ADDR此值是不可修改的,因为网站要与代理服务器通信,要给它传数据,若可修改,那么代理服务器就收不到数据了,因此若通过REMOTE_ADDR得到IP,那么此IP一定是真实的。
HTTP_X_FORWARDED_FOR值是可以修改的,若通过此值取真实IP,有可能是篡改的非真实IP.不过,对于大访问量的网站来说,大部分的客户都是合法的,只有极少的一部分通过篡改IP的方式去访问,在此种情况下,可以适用上述方法得到IP
不过对于网上投票那种,篡改IP的方式则很有空间,对于此种,就不能再通过IP去确定是不是同一人点击之类,可以写一个加密的cookie来识别。
//篡改HTTP_X_FORWARDED_FOR
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
"http://localhost:7867/MyTestWebSite/UserIP.aspx");
request.Headers.Add("REMOTE_ADDR", "192.168.5.88");
request.Headers.Add("VIA", "ghj1976");
request.Headers.Add("X_FORWARDED_FOR", "0.0.0.0");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new
StreamReader(response.GetResponseStream());
string info = stream.ReadToEnd();
stream.Close();
response.Close();
request = null;
Console.Write(info);
Console.ReadLine();
}
解决方案添加工程及网站
1,工程都有一*.csproj,直接添加即可。
?2,对于网站,先用IIS指向此网站,然后在解决方案添加的时候 添加现有网站-本地IIS 找到网站,加上即可。
模拟_doPostBack:让textbox on blur 或按下确定时执行服务端事件
原理:在on blur 或 onkeydown 时显示调用 _doPoastBack事件,回访到服务器端,要执行对应的哪个方法,在前台加hidden指定
如: function btnClick( btn ){
??????????? if (? event.keyCode == 13 &&? btn != undefined ){
??????????????? //btn.click();
??????????????? document.getElementById(“myHidState”).value = btn.id;? //设置input type = ‘hidden’ 的值
??????????????? __doPostBack(btn.id,””);
??????????? }
??????? }
在后台 load时就可据 Request.Forms[“myHidStateName”] 的值要执行对应的方法
后台得到客户端控制如input的值
? <input type=”text” id = “Text1″ name=”myText111” />
在后台用:Request.Form[“myText111”] 调用前台的值遍历页面传来的所有值
int loop1;
NameValueCollection coll=Request.Form;?
string[] arr1 = coll.AllKeys;
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{ Response.Write(“Form: ” + arr1[loop1] + “<br>”); }