分享一个轻型ORM--Dapper选用理由

by Administrator 2015.6.16 10:23

推荐理由:Dapper只有一个代码文件,完全开源,你可以放在项目里的任何位置,来实现数据到对象的ORM操作,体积小速度快:)

Google Code下载地址:

   http://code.google.com/p/dapper-dot-net/

   https://github.com/SamSaffron/dapper-dot-net

授权协议:Apache License 2.0

用法示例:http://weblogs.asp.net/jalpeshpvadgama/archive/2011/05/19/insert-with-dapper-micro-orm-and-asp-net-mvc-3.aspx

 

Dapper - a simple object mapper for .Net

Official Github clone: https://github.com/SamSaffron/dapper-dot-net

Documentation you can improve

The Dapper tag wiki on Stack Overflow can be improved by any Stack Overflow users. Feel free to add relevant information there.

Features

Dapper is a single file you can drop in to your project that will extend your IDbConnection interface.

It provides 3 helpers:

Execute a query and map the results to a strongly typed List

Note: all extension methods assume the connection is already open, they will fail if the connection is closed.

public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

Example usage:

publicclassDog
{
   
publicint?Age{get;set;}
   
publicGuidId{get;set;}
   
publicstringName{get;set;}
   
publicfloat?Weight{get;set;}

   
publicintIgnoredProperty{get{return1;}}
}            
           
var guid =Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id",new{Age=(int?)null,Id= guid });
           
dog
.Count()
   
.IsEqualTo(1);

dog
.First().Age
   
.IsNull();

dog
.First().Id
   
.IsEqualTo(guid);

Execute a query and map it to a list of dynamic objects

public static IEnumerable<dynamic> Query (this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null, bool buffered = true)

This method will execute SQL and return a dynamic list.

Example usage:

 var rows = connection.Query("select 1 A, 2 B union all select 3, 4");

((int)rows[0].A)
   
.IsEqualTo(1);

((int)rows[0].B)
   
.IsEqualTo(2);

((int)rows[1].A)
   
.IsEqualTo(3);

((int)rows[1].B)
   
.IsEqualTo(4);

Execute a Command that returns no results

public static int Execute(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

Example usage:

connection.Execute(@"
  set nocount on
  create table #t(i int)
  set nocount off
  insert #t
  select @a a union all select @b
  set nocount on
  drop table #t"
,new{a=1, b=2})
   
.IsEqualTo(2);

Execute a Command multiple times

The same signature also allows you to conveniently and efficiently execute a command multiple times (for example to bulk-load data)

Example usage:

connection.Execute(@"insert MyTable(colA, colB) values (@a, @b)",
   
new[]{new{ a=1, b=1},new{ a=2, b=2},new{ a=3, b=3}}
 
).IsEqualTo(3);// 3 rows inserted: "1,1", "2,2" and "3,3"

This works for any parameter that implements IEnumerable<T> for some T.

Performance

A key feature of Dapper is performance. The following metrics show how long it takes to execute 500 SELECT statements against a DB and map the data returned to objects.

The performance tests are broken in to 3 lists:

  1. POCO serialization for frameworks that support pulling static typed objects from the DB. Using raw SQL.
  2. Dynamic serialization for frameworks that support returning dynamic lists of objects.
  3. Typical framework usage. Often typical framework usage differs from the optimal usage performance wise. Often it will not involve writing SQL.

Performance of SELECT mapping over 500 iterations - POCO serialization

 

Method Duration Remarks
Hand coded (using a SqlDataReader) 47ms
Dapper ExecuteMapperQuery<Post> 49ms
ServiceStack.OrmLite (QueryById) 50ms
PetaPoco 52ms Can be faster
BLToolkit 80ms
SubSonic CodingHorror 107ms
NHibernate SQL 104ms
Linq 2 SQL ExecuteQuery 181ms
Entity framework ExecuteStoreQuery 631ms

 

Performance of SELECT mapping over 500 iterations - dynamic serialization

 

Method Duration Remarks
Dapper ExecuteMapperQuery (dynamic) 48ms
Massive 52ms
Simple.Data 95ms

 

Performance of SELECT mapping over 500 iterations - typical usage

 

Method Duration Remarks
Linq 2 SQL CompiledQuery 81ms Not super typical involves complex code
NHibernate HQL 118ms
Linq 2 SQL 559ms
Entity framework 859ms
SubSonic ActiveRecord.SingleOrDefault 3619ms

 

Performance benchmarks are available here: http://code.google.com/p/dapper-dot-net/source/browse/Tests/PerformanceTests.cs , Feel free to submit patches that include other ORMs - when running benchmarks, be sure to compile in Release and not attach a debugger (ctrl F5)

Parameterized queries

Parameters are passed in as anonymous classes. This allow you to name your parameters easily and gives you the ability to simply cut-and-paste SQL snippets and run them in Query analyzer.

new{A =1, B ="b"}// A will be mapped to the param @A, B to the param @B 

Advanced features

List Support

Dapper allow you to pass in IEnumerable<int> and will automatically parameterize your query.

For example:

connection.Query<int>("select * from (select 1 as Id union all select 2 union all select 3) as X where Id in @Ids", new { Ids = new int[] { 1, 2, 3 });

Will be translated to:

select*from(select1asIdunion all select2union all select3)as X whereIdin(@Ids1,@Ids2,@Ids3)" // @Ids1 = 1 , @Ids2 = 2 , @Ids2 = 3

Buffered vs Unbuffered readers

Dapper's default behavior is to execute your sql and buffer the entire reader on return. This is ideal in most cases as it minimizes shared locks in the db and cuts down on db network time.

However when executing huge queries you may need to minimize memory footprint and only load objects as needed. To do so pass, buffered: false into the Query method.

Multi Mapping

Dapper allows you to map a single row to multiple objects. This is a key feature if you want to avoid extraneous querying and eager load associations.

Example:

var sql = 
@"select * from #Posts p
left join #Users u on u.Id = p.OwnerId
Order by p.Id"
;
 
var data = connection.Query<Post,User,Post>(sql,(post, user)=>{ post.Owner= user;return post;});
var post = data.First();
 
post
.Content.IsEqualTo("Sams Post1");
post
.Id.IsEqualTo(1);
post
.Owner.Name.IsEqualTo("Sam");
post
.Owner.Id.IsEqualTo(99);

important note Dapper assumes your Id columns are named "Id" or "id", if your primary key is different or you would like to split the wide row at point other than "Id", use the optional 'splitOn' parameter.

Multiple Results

Dapper allows you to process multiple result grids in a single query.

Example:

var sql = 
@"
select * from Customers where CustomerId = @id
select * from Orders where CustomerId = @id
select * from Returns where CustomerId = @id"
;
 
using(var multi = connection.QueryMultiple(sql,new{id=selectedId}))
{
   
var customer = multi.Read<Customer>().Single();
   
var orders = multi.Read<Order>().ToList();
   
var returns = multi.Read<Return>().ToList();
   
...
}

Stored Procedures

Dapper supports fully stored procs:

var user = cnn.Query<User>("spGetUser",new{Id=1}, 
        commandType
:CommandType.StoredProcedure).First();}}}

If you want something more fancy, you can do:

var p =newDynamicParameters();
p
.Add("@a",11);
p
.Add("@b", dbType:DbType.Int32, direction:ParameterDirection.Output);
p
.Add("@c", dbType:DbType.Int32, direction:ParameterDirection.ReturnValue);

cnn
.Execute("spMagicProc", p, commandType: commandType.StoredProcedure);

int b = p.Get<int>("@b");
int c = p.Get<int>("@c");

Ansi Strings and varchar

Dapper supports varchar params, if you are executing a where clause on a varchar column using a param be sure to pass it in this way:

Query<Thing>("select * from Thing where Name = @Name",new{Name=newDbString{Value="abcde",IsFixedLength=true,Length=10,IsAnsi=true});

On Sql Server it is crucial to use the unicode when querying unicode and ansi when querying non unicode.

Tags:

json2.js使用参考

by Administrator 2013.11.29 15:47

json2.js的源码地址:

https://github.com/douglascrockford/JSON-js

Visual Studio用户可以直接通过Nuget来获得。

 

json2.js提供了json的序列化和反序列化方法,可以将一个json对象转换成json字符串,也可以将一个json字符串转换成一个json对象。

 

在页面中添加json2.js的引用。

<script type="text/javascript" src="/CoreResource/JS/json2.min.js"></script> 

 

序列化方法

var jsonObj = { id: '01', name: 'Tom' }; JSON.stringify(jsonObj);

 

反序列化方法

var jsonString = "{ id: '01', name: 'Tom' }"; JSON.parse(jsonString);

Tags:

JavaScript

eval解析JSON中的注意点

by Administrator 2013.11.29 14:50

在JS中将JSON的字符串解析成JSON数据格式,一般有两种方式:

1.一种为使用eval()函数。

2. 使用Function对象来进行返回解析。

使用eval函数来解析,并且使用jquery的each方法来遍历

用jquery解析JSON数据的方法,作为jquery异步请求的传输对象,jquery请求后返回的结果是json对象,这里考虑的都是服务器 返回JSON形式的字符串的形式,对于利用JSONObject等插件封装的JSON对象,与此亦是大同小异,这里不再做说明。
这里首先给出JSON字符串集,字符串集如下:

代码如下:
var data="
{
root:
[
{name:'1',value:'0'},
{name:'6101',value:'北京市'},
{name:'6102',value:'天津市'},
{name:'6103',value:'上海市'},
{name:'6104',value:'重庆市'},
{name:'6105',value:'渭南市'},
{name:'6106',value:'延安市'},
{name:'6107',value:'汉中市'},
{name:'6108',value:'榆林市'},
{name:'6109',value:'安康市'},
{name:'6110',value:'商洛市'}
]
}";
这里以jquery异步获取的数据类型——json对象和字符串为依据,分别介绍两种方式获取到的结果处理方式。

1.对于服务器返回的JSON字符串,如果jquery异步请求没做类型说明,或者以字符串方式接受,那么需要做一次对象化处理,方式不是太麻烦,就是将该字符串放于eval()中执行一次。这种方式也适合以普通javascipt方式获取json对象,以下举例说明:

var dataObj=eval("("+data+")");//转换为json对象

Red rose为什么要 eval这里要添加 “("("+data+")");//”呢?

原因在于:eval本身的问题。 由于json是以”{}”的方式来开始以及结束的,在JS中,它会被当成一个语句块来处理,所以必须强制性的将它转换成一种表达式。

加上圆括号的目的是迫使eval函数在处理JavaScript代码的时候强制将括号内的表达式(expression)转化为对象,而不是作为语 句(statement)来执行。举一个例子,例如对象字面量{},如若不加外层的括号,那么eval会将大括号识别为JavaScript代码块的开始 和结束标记,那么{}将会被认为是执行了一句空语句。所以下面两个执行结果是不同的:
alert(eval("{}"); // return undefined
alert(eval("({})");// return object[Object]

对于这种写法,在JS中,可以到处看到。

如: (function()) {}();  做闭包操作时等。



alert(dataObj.root.length);//输出root的子对象数量
$.each(dataObj.root,fucntion(idx,item){
if(idx==0){
return true;
}
//输出每个root子对象的名称和值
alert("name:"+item.name+",value:"+item.value);
})
注:对于一般的js生成json对象,只需要将$.each()方法替换为for语句即可,其他不变。


2.对于服务器返回的JSON字符串,如果jquery异步请求将type(一般为这个配置属性)设为“json”,或者利 用$.getJSON()方法获得服务器返回,那么就不需要eval()方法了,因为这时候得到的结果已经是json对象了,只需直接调用该对象即可,这 里以$.getJSON方法为例说明数据处理方法:
$.getJSON("http://www.phpzixue.cn/",{param:"gaoyusi"},function(data){
//此处返回的data已经是json对象
//以下其他操作同第一种情况
$.each(data.root,function(idx,item){
if(idx==0){
return true;//同countinue,返回false同break
}
alert("name:"+item.name+",value:"+item.value);
});
});
这里特别需要注意的是方式1中的eval()方法是动态执行其中字符串(可能是js脚本)的,这样很容易会造成系统的安全问题。所以可以采用一些规避了eval()的第三方客户端脚本库,比如JSON in JavaScript就提供了一个不超过3k的脚本库。

第二种解析方式就是使用Function对象来完成,它的典型应用就是在JQUERY中的AJAX方法下的success等对于返回数据data的解析

var json='{"name":"CJ","age":18}';

data =(new Function("","return "+json))();

 

此时的data就是一个会解析成一个 json对象了.

Tags:

JavaScript

js/jquery 获取url参数

by Administrator 2013.11.21 11:45

js代码:

function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r!=null) return unescape(r[2]); return null;
}  

URL的参数&参数名1=XXXX&参数名2=XXXX&参数名3=XXXX  

alert(GetQueryString("参数名1"));
alert(GetQueryString("参数名2"));
alert(GetQueryString("参数名3"));

jquery 代码:

把下面代码。放到js文件中

/**
* jQuery.query - Query String Modification and Creation for jQuery
* Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* Date: 2009/8/13
*
* @author Blair Mitchelmore
* @version 2.1.6
*
**/
new function(settings) {
// Various Settings
var $separator = settings.separator || '&';
var $spaces = settings.spaces === false ? false : true;
var $suffix = settings.suffix === false ? '' : '[]';
var $prefix = settings.prefix === false ? false : true;
var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
var $numbers = settings.numbers === false ? false : true;

jQuery.query = new function() {
var is = function(o, t) {
return o != undefined && o !== null && (!!t ? o.constructor == t : true);
};
var parse = function(path) {
var m, rx = /\[([^[]*)\]/g, match = /^([^[]+?)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
while (m = rx.exec(match[2])) tokens.push(m[1]);
return [base, tokens];
};
var set = function(target, tokens, value) {
var o, token = tokens.shift();
if (typeof target != 'object') target = null;
if (token === "") {
if (!target) target = [];
if (is(target, Array)) {
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
} else if (is(target, Object)) {
var i = 0;
while (target[i++] != null);
target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
} else {
target = [];
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
}
} else if (token && token.match(/^\s*[0-9]+\s*$/)) {
var index = parseInt(token, 10);
if (!target) target = [];
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else if (token) {
var index = token.replace(/^\s*|\s*$/g, "");
if (!target) target = {};
if (is(target, Array)) {
var temp = {};
for (var i = 0; i < target.length; ++i) {
temp[i] = target[i];
}
target = temp;
}
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else {
return value;
}
return target;
};

var queryObject = function(a) {
var self = this;
self.keys = {};

if (a.queryObject) {
jQuery.each(a.get(), function(key, val) {
self.SET(key, val);
});
} else {
jQuery.each(arguments, function() {
var q = "" + this;
q = q.replace(/^[?#]/,''); // remove any leading ? || #
q = q.replace(/[;&]$/,''); // remove any trailing & || ;
if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces

jQuery.each(q.split(/[&;]/), function(){
var key = decodeURIComponent(this.split('=')[0] || "");
var val = decodeURIComponent(this.split('=')[1] || "");

if (!key) return;

if ($numbers) {
if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
val = parseFloat(val);
else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
val = parseInt(val, 10);
}

val = (!val && val !== 0) ? true : val;

if (val !== false && val !== true && typeof val != 'number')
val = val;

self.SET(key, val);
});
});
}
return self;
};

queryObject.prototype = {
queryObject: true,
has: function(key, type) {
var value = this.get(key);
return is(value, type);
},
GET: function(key) {
if (!is(key)) return this.keys;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
while (target != null && tokens.length != 0) {
target = target[tokens.shift()];
}
return typeof target == 'number' ? target : target || "";
},
get: function(key) {
var target = this.GET(key);
if (is(target, Object))
return jQuery.extend(true, {}, target);
else if (is(target, Array))
return target.slice(0);
return target;
},
SET: function(key, val) {
var value = !is(val) ? null : val;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
this.keys[base] = set(target, tokens.slice(0), value);
return this;
},
set: function(key, val) {
return this.copy().SET(key, val);
},
REMOVE: function(key) {
return this.SET(key, null).COMPACT();
},
remove: function(key) {
return this.copy().REMOVE(key);
},
EMPTY: function() {
var self = this;
jQuery.each(self.keys, function(key, value) {
delete self.keys[key];
});
return self;
},
load: function(url) {
var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
},
empty: function() {
return this.copy().EMPTY();
},
copy: function() {
return new queryObject(this);
},
COMPACT: function() {
function build(orig) {
var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
if (typeof orig == 'object') {
function add(o, key, value) {
if (is(o, Array))
o.push(value);
else
o[key] = value;
}
jQuery.each(orig, function(key, value) {
if (!is(value)) return true;
add(obj, key, build(value));
});
}
return obj;
}
this.keys = build(this.keys);
return this;
},
compact: function() {
return this.copy().COMPACT();
},
toString: function() {
var i = 0, queryString = [], chunks = [], self = this;
var encode = function(str) {
str = str + "";
if ($spaces) str = str.replace(/ /g, "+");
return encodeURIComponent(str);
};
var addFields = function(arr, key, value) {
if (!is(value) || value === false) return;
var o = [encode(key)];
if (value !== true) {
o.push("=");
o.push(encode(value));
}
arr.push(o.join(""));
};
var build = function(obj, base) {
var newKey = function(key) {
return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
};
jQuery.each(obj, function(key, value) {
if (typeof value == 'object')
build(value, newKey(key));
else
addFields(chunks, newKey(key), value);
});
};

build(this.keys);

if (chunks.length > 0) queryString.push($hash);
queryString.push(chunks.join($separator));

return queryString.join("");
}
};

return new queryObject(location.search, location.hash);
};
}(jQuery.query || {}); // Pass in jQuery.query as settings object
 
 
如果想获取test,则可以引入插件后,
用如下方法获取:
var test = $.query.get('test');

如果参数有多个相同的名称 ,则可以这样:
var arr = $.query.get('testy');
输出:   [ 值1 ,   值2,   值3...]

如果要获取多个相同名称中的某一个,可以这样:
var arrayElement = $.query.get('testy[1]');

此插件不仅能获取参数,也能设置参数。

设置一个参数:
var newUrl = $.query.set("section", 5).toString();
输出   : "?section=5"

设置两个参数:
var newUrl = $.query.set("section", 5).set("action", "do").toString();
输出 :   "?action=do§ion=5"


删除一个参数:
var oldQueryAgain = $.query.REMOVE("type");

清空所有参数:
var emptyQuery = $.query.empty();

复制所有参数:
var stillTheSame = $.query.copy();

Tags:

JavaScript

SQL随机条数

by Administrator 2013.11.11 11:45

select top 10 *, NewID() as random from [Core_UserInfo] order by random
 
 
select top (cast( floor(rand()*10) as int)) * from [Core_UserInfo] order by newid()

Tags:

SQL

jq操作select集合

by Administrator 2013.9.16 10:07

最近一段时间发现,老是要跟select,option相关的东西打交道,而且有的时候还会搞错,于是,抽了一点时间整理了一份使用jq库来操作select的一些事件及方法,供大家参考。

html代码:

<selectid="selectTest"name="selectTest">
  <optionvalue="请选择">请选择</option>
  <optionvalue="1">11</option>
  <optionvalue="2">22</option>
  <optionvalue="3">33</option>
  <optionvalue="4">44</option>
  <optionvalue="5">55</option>
  <optionvalue="6">66</option>
</select>

获取Select:

获取select选中的text

$('#selectTest').find('option:selected').text();

获取select选中的val

$('#selectTest').find('option:selected').val();

获取select选中的索引

$('#selectTest').get(0).selectedIndex

设置Select:

设置select选中的text

var text = "66";

var count = $("#selectTest option").length;

for(var i = 0; i < count; i++){    

  if($("#selectTest").get(0).options[i].text == text){  

   $("#selectTest").get(0).options[i].selected = true;  

   break;

   }  

}

设置select选中的value

$("#selectTest").find('option:selected').attr("value","Normal");

$("#selectTest").find('option:selected').val("Normal");

$("#selectTest").get(0).options[0].value = "Normal";

设置select选中的索引

$("#selectTest").get(0).selectedIndex = index;//index为索引值

设置select option项

$("#selectTest").append("< option value='Value'>Text< /option>");  //添加一项option

$("#selectTest").prepend("< option value='0'>请选择< /option>"); //在前面插入一项option

$("#selectTest option:last").remove(); //删除索引值最大的Option

$("#selectTest option[index=0]").remove();//删除索引值为0的Option

$("#selectTest option[value='3']").remove(); //删除值为3的Option

清空 Select

$("#selectTest").empty();

$("#selectTest").children().remove();

Tags:

JavaScript

Page.ClientScript.RegisterClientScriptBlock 与RegisterClientScriptBlock

by Administrator 2013.9.11 11:06
之所以没用Page.ClientScript.RegisterClientScriptBlock而用 Page.ClientScript.RegisterStartupScript是因为RegisterStartupScript 把script放置在ASP.NET page的底部,而RegisterClientScriptBlock把script放置在ASP.NET page的顶部,用RegisterClientScriptBlock会报错,javascript函数不到对象
    
1.使用 Page.ClientScript.RegisterClientScriptBlock
Listing 4-10: Using the RegisterClientScriptBlock method
c#
<%@ Page Language=”C#” %>
<script runat=”server”>
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @”function AlertHello() { alert(‘Hello ASP.NET’); }”;
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(),
“MyScript”, myScript,
true);
}

</script>

运行结果如下:
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head><title>
Adding JavaScript
</title></head>
<body>
<form method=”post” action=”JavaScriptPage.aspx” id=”form1”>
<div>
<input type=”hidden” name=”__VIEWSTATE”
value=”/wEPDwUKMTY3NzE5MjIyMGRkiyYSRMg+bcXi9DiawYlbxndiTDo=” />
</div>
<script type=”text/javascript”>
<!--
function AlertHello() { alert(‘Hello ASP.NET’); }// -->
</script>
<div>
<input type=”submit” name=”Button1” value=”Button” onclick=”AlertHello();”
id=”Button1” />
</div>
</form>
</body>
</html>

2.使用Page.ClientScript.RegisterStartupScript

RegisterStartupScript方法与RegisterClientScriptBlock方法最大的不同 是:RegisterStartupScript 把script放置在ASP.NET page的底部,而RegisterClientScriptBlock把script放置在ASP.NET page的顶部

如果你的页面中有如下代码:
<asp:TextBox ID=”TextBox1” Runat=”server”>Hello ASP.NET</asp:TextBox>

Listing 4-11: Improperly using the RegisterClientScriptBlock method
 
c#
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @”alert(document.forms[0][‘TextBox1’].value);”;
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(),
“MyScript”, myScript,
true);
}
此页面运行时会报错,原因是JavaScript function先于text box被安放于浏览器。因此JavaScript function找不到TextBox1。

Listing 4-12: Using the RegisterStartupScript method
 
c#
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @”alert(document.forms[0][‘TextBox1’].value);”;
Page.ClientScript.RegisterStartupScript(
this.GetType(),
“MyScript”, myScript,
true);
}
这段代码把JavaScript function放置于ASP.NET page底部,因此JavaScript运行时它能找到TextBox1。

3.使用Page.ClientScript.RegisterClientScriptInclude
许多开发者把JavaScript放置在.js文件中,使用RegisterClientScriptInclude方法可以注册.js文件中的 JavaScript。
Listing 4-13: Using the RegisterClientScriptInclude method
c#
string myScript = “myJavaScriptCode.js”
Page.ClientScript.RegisterClientScriptInclude(“myKey”, myScript);
这将在ASP.NET页面产生如下结构:
<script src=”myJavaScriptCode.js” type=”text/javascript”></script>

Tags:

如何在ashx页面获取Session值

by Administrator 2013.9.7 12:43

在一般事务处理页面,可以轻松的得到 Request,Response对象,从而进行相应的操作,如下:

HttpRequest Request = context.Request; 

HttpResponse Response = context.Response;

但是要得到 Session的值就没有那么简单了。比如你要在ashx得到保存在Session中的登录帐号Session["userAccount"]

如果你只是context.Session["userAccount"]的话是会报 “未将对象引用设置到对象的实例”的异常

所以,如果要想取Session中的值 ,需要如下所示

1、引入 命名空间:

using System.Web.SessionState;

2、实现IRequiresSessionState接口,具体如下  

   

/// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class AddUserInfo : IHttpHandler,IRequiresSessionState //就是这样显示的实现一下,不用实现什么方法
    {

        public void ProcessRequest(HttpContext context)
        {

      //...

       //这样你就可以如下 操作了

                if(context.Session["userAccount"] != null)

      {

        string account = context.Session["userAccount"].ToString();

      }

      //...继续下面的代码

    }

  }

Tags:

C#

SQLSERVER 怎样去除重复记录

by Administrator 2013.9.7 12:38

     有两个意义上的重复记录,一是完全重复的记录,也即所有字段均重复的记录,二是部分关键字段重复的记录,比如Name字段重复,而其他字段不一定重复或都重复可以忽略。 
     对于第一种重复,比较容易解决,使用 

select distinct * from tableName


就可以得到无重复记录的结果集。 
如果该表需要删除重复的记录(重复记录保留1条),可以按以下方法删除
select distinct * into #Tmp from tableName 
drop table tableName 
select * into tableName from #Tmp 
drop table #Tmp

发生这种重复的原因是表设计不周产生的,增加唯一索引列即可解决。

Tags:

SQL

js判断文本框不能有特殊字符

by Administrator 2013.9.7 12:12
function TextValidate() {
var code;
var character;
var err_msg = "文本不能含有空格或任何这些特殊字符以外的下划线_和连字符-)";
if (document.all) //判断是否是IE浏览器
{
code = window.event.keyCode;
}
else {
code = arguments.callee.caller.arguments[0].which;
}
var character = String.fromCharCode(code);

Tags:

JavaScript

关于博主

一个码农的个人主页!

归档

页面

最近的文章

最近的评论

None

声明

本博所有网友评论不代表本博立场,版权归其作者所有。

© Copyright 2011