EF SqlBulkCopy 批量入库
string connection=ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
public
static
void BulkInsert<T>(
string connection,
string tableName, IList<T> list)
{
using (
var bulkCopy =
new SqlBulkCopy(connection))
{
bulkCopy.BatchSize = list.Count;
bulkCopy.DestinationTableName = tableName;
var table =
new DataTable();
var props = TypeDescriptor.GetProperties(
typeof(T))
.Cast<PropertyDescriptor>()
.Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals(
"
System
"))
.ToArray();
foreach (
var propertyInfo
in props)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
}
var values =
new
object[props.Length];
foreach (
var item
in list)
{
for (
var i =
0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
bulkCopy.WriteToServer(table);
}
}
var imports =
new List<sendapientity>();
foreach (JToken phone
in phones)
{
SendEntity sendphone = JsonConvert.DeserializeObject<SendEntity>(phone.ToString());
string tphone = sendphone.phone;
int sendid = Convert.ToInt32(sendphone.id);
sendapientity s =
new sendapientity();
s.UserId = userid;
s.PartnersCode = partnerscode;
s.SendId = sendid;
s.Phone = tphone;
s.Message = msg;
s.SentTime = sendtime;
s.CreateTime = DateTime.Now;
s.BatchId = batchid;
s.Count = count;
imports.Add(s);
}
using (SMMMContext db =
new SMMMContext())
{
BulkInsert(db.Database.Connection.ConnectionString,
"
Send_Api
", imports);
}
public
class sendapientity
{
public
int UserId {
get;
set; }
public
string PartnersCode {
get;
set; }
public
int SendId {
get;
set; }
public
string Phone {
get;
set; }
public
string Message {
get;
set; }
public
string SentTime {
get;
set; }
public DateTime CreateTime {
get;
set; }
public
long BatchId {
get;
set; }
public
int Count {
get;
set; }
}
在JavaScript中推荐的做法是用encodeURI对URI的网址部分编码,用encodeURIComponent对URI中传递的参数进行编码。
在C#中推荐的做法是用Uri.EscapeUriString对URI的网址部分编码,用Uri.EscapeDataString对URI中传递的参数进行编码。
public
static
int ToInt32(
double value)
{
if (value >=
0.0)
{
if (value <
2147483647.5)
{
int num = (
int)value;
double num2 = value - num;
if ((num2 >
0.5) || ((num2 ==
0.5) && ((num &
1) !=
0)))
{
num++;
}
return num;
}
}
else
if (value >= -
2147483648.5)
{
int num3 = (
int)value;
double num4 = value - num3;
if ((num4 < -
0.5) || ((num4 == -
0.5) && ((num3 &
1) !=
0)))
{
num3--;
}
return num3;
}
throw
new OverflowException(Environment.GetResourceString(
"
Overflow_Int32
"));
}
public
enum
CommentType { 不推荐=
0
, 一般=
3
, 良=
4
, 优=
5
}
///
<summary>
///
绑定评分类型
///
</summary>
///
<param name="RBL"></param>
protected
static
void BindRadioButtonList(RadioButtonList RBL)
{
RBL.Items.Clear();
Type typ =
typeof(CommentType);
foreach (
int i
in Enum.GetValues(typ))
{
RBL.Items.Add(
new ListItem(Enum.GetName(typ, i), Enum.Format(typ, Enum.Parse(typ, Enum.GetName(typ, i)),
"
d
")));
RBL.SelectedValue = i.ToString();
}
}
///
<summary>
///
获取类型名称
///
</summary>
///
<param name="typeid"></param>
///
<returns></returns>
protected
static
string BindRating(
string typeid)
{
string typename =
"";
Type typ =
typeof(CommentType);
foreach (
int i
in Enum.GetValues(typ))
{
if (typeid == Enum.Format(typ, Enum.Parse(typ, Enum.GetName(typ, i)),
"
d
"))
{
typename = Enum.GetName(typ, i);
}
}
return typename;
}
//
.NET 正确获取当前URL
HttpContext.Current.Request.Url.ToString() 不可靠
HttpContext.Current.Request.Url.PathAndQuery 正确
///
new List
<int>
(ht.Keys),用到了 List 的构造拷贝函数
///
在遍历数据结构的时候,是不可以修改原数据结构的。不然就会抛出错误。
foreach (
string key
in
new List<
string>(_IpAdresses.Keys))
{
_IpAdresses[key]--;
if (_IpAdresses[key] ==
0)
_IpAdresses.Remove(key);
}
c# 四舍五入 保留几位小数点
protected
string
getProductPrice(
int
id)
{
CustomerProInfo cp
=
ahlan.getCustomerProInfoByID(id);
double
x
=
double
.Parse((cp.Product.sprice
*
cp.proValue
/
10
).ToString());
//
两个double相乘结果是double?,所以要强制在转换一次
return
ChinaRound(x,
2
).ToString();
}
//
value你要转换的double数据,decimals要保留的小数点
double
ChinaRound(
double
value,
int
decimals)
{
if
(value
<
0
)
{
return
Math.Round(value
+
5
/
Math.Pow(
10
, decimals
+
1
), decimals, MidpointRounding.AwayFromZero);
}
else
{
return
Math.Round(value, decimals, MidpointRounding.AwayFromZero);
}
}
//判断用户是手机还是pc访问
public
class IsPhoneAttribute : ActionFilterAttribute
{
public
override
void OnActionExecuting(ActionExecutingContext filterContext)
{
string u = filterContext.HttpContext.Request.ServerVariables[
"
HTTP_USER_AGENT
"];
Regex b =
new Regex(
@"
android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino
", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Regex v =
new Regex(
@"
1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-
", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (!(b.IsMatch(u) || v.IsMatch(u.Substring(
0,
4))))
{
filterContext.Controller.ViewData[
"
ErrorMessage
"] =
"
对不起,请用手机访问!
";
filterContext.Result =
new ViewResult()
{
ViewName =
"
ErrorInfo
",
ViewData = filterContext.Controller.ViewData,
};
}
}
}
发送短信接口
public
static
bool SendMobileMsg(
string msgContent, List<
string> destListPhones)
{
try
{
bool result =
false;
string strPhones =
string.Join(
"
;
", destListPhones.ToArray());
strPhones +=
"
;
";
var encoding = System.Text.Encoding.GetEncoding(
"
GB2312
");
string postData =
string.Format(
"
uid=用户名&pwd=密码&mobile={0};&msg={1}&dtime=
", strPhones, msgContent);
byte[] data = encoding.GetBytes(postData);
//
定义 WebRequest
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(
"
http://www.smsadmin.cn/smsmarketing/wwwroot/api/post_send/
");
myRequest.Method =
"
POST
";
myRequest.ContentType =
"
application/x-www-form-urlencoded
";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
//
发送数据
newStream.Write(data,
0, data.Length);
newStream.Close();
//
得到 Response
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader =
new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
string content = reader.ReadToEnd();
if (content.Substring(
0,
1) ==
"
0
")
result =
true;
else
{
if (content.Substring(
0,
1) ==
"
2
")
//
余额不足
{
//
"手机短信余额不足";
//
TODO
}
else
{
//
短信发送失败的其他原因,请参看官方API
}
result =
false;
}
return result;
}
catch
{
return
false;
}
}
很“干净”的调用,没有WebService也没有COM。
唯一要注意的就是编码用 GB2312 否则您收到短信的中文部分都是乱码,另外第10行的用户名和密码被硬编码了,应写在配置文件内。
private
static
readonly
Regex reg_b
=
new
Regex(
@"
\B
"
, RegexOptions.Compiled);
private
static
readonly
Regex reg_en
=
new
Regex(
@"
[a-zA-Z]+
"
, RegexOptions.Compiled);
private
static
readonly
Regex reg_num
=
new
Regex(
@"
^[\-\.\s\d]+$
"
, RegexOptions.Compiled);
private
static
Regex reg_word
=
null
;
//
组合所有屏蔽词的正则
private
static
Regex GetRegex()
{
if
(reg_word
==
null
)
{
reg_word
=
new
Regex(GetPattern(), RegexOptions.Compiled
|
RegexOptions.IgnoreCase);
}
return
reg_word;
}
///
<summary>
///
检查输入内容是否包含脏词(包含返回true)
///
</summary>
public
static
bool
HasBlockWords(
string
raw)
{
return
GetRegex().Match(raw).Success;
}
///
<summary>
///
脏词替换成*号
///
</summary>
public
static
string
WordsFilter(
string
raw)
{
return
GetRegex().Replace(raw,
"
***
"
);
}
///
<summary>
///
获取内容中含有的脏词
///
</summary>
public
static
IEnumerable
<
string
>
GetBlockWords(
string
raw)
{
foreach
(Match mat
in
reg_word.Matches(raw))
{
yield
return
(mat.Value);
}
}
private
static
string
GetPattern()
{
StringBuilder patt
=
new
StringBuilder();
string
s;
foreach
(
string
word
in
GetBlockWords())
{
if
(word.Length
==
0
)
continue
;
if
(word.Length
==
1
)
{
patt.AppendFormat(
"
|({0})
"
, word);
}
else
if
(reg_num.IsMatch(word))
{
patt.AppendFormat(
"
|({0})
"
, word);
}
else
if
(reg_en.IsMatch(word))
{
s
=
reg_b.Replace(word,
@"
(?:[^a-zA-Z]{0,3})
"
);
patt.AppendFormat(
"
|({0})
"
, s);
}
else
{
s
=
reg_b.Replace(word,
@"
(?:[^\u4e00-\u9fa5]{0,3})
"
);
patt.AppendFormat(
"
|({0})
"
, s);
}
}
if
(patt.Length
>
0
)
{
patt.Remove(
0
,
1
);
}
return
patt.ToString();
}
///
<summary>
///
获取所有脏词
///
</summary>
public
static
string
[] GetBlockWords()
{
return
new
string
[]{
"
国民党
"
,
"
fuck
"
,
"
110
"
};
//
这里应该从数据库获取
}
这个程序可替换以下内容:
国民党
国-民-党
国o民o党
fuck
f.u.c.k
110(110的变形写法不被替换)
//
int double 转换
int
goodper;
int
badper;
int
goodposts
=
Convert.ToInt32(dr[
"
goodpost
"
]);
int
badposts
=
Convert.ToInt32(dr[
"
badpost
"
]);
if
(goodposts
+
badposts
==
0
)
{
goodper
=
badper
=
0
;
}
else
{
int
alls
=
goodposts
+
badposts;
goodper
=
Convert.ToInt32((
double
)goodposts
/
alls
*
100
);
badper
=
100
-
goodper;
}
如:
Convert.ToInt32(
4
/
5
*
100
)
=
0
Convert.ToInt32(
4.0
/
5
*
100
)
=
80
//
中英文字符串截取方法
public
static
string
Intercept(
string
input,
int
p)
{
Encoding encode
=
Encoding.GetEncoding(
"
gb2312
"
);
byte
[] byteArr
=
encode.GetBytes(input);
if
(byteArr.Length
<=
p)
return
input;
int
m
=
0
, n
=
0
;
foreach
(
byte
b
in
byteArr)
{
if
(n
>=
p)
break
;
if
(b
>
127
) m
++
;
//
重要一步:对前p个字节中的值大于127的字符进行统计
n
++
;
}
if
(m
%
2
!=
0
) n
=
p
+
1
;
//
如果非偶:则说明末尾为双字节字符,截取位数加1
return
encode.GetString(byteArr,
0
, n);
}
Console.WriteLine(Intercept(
"
ABC中国人
"
,
7
));
Console.WriteLine(Intercept(
"
ABCD中国人
"
,
7
));
Console.WriteLine(Intercept(
"
ABC中D国人
"
,
7
));
/*
测试代码的结果:
ABC中国
ABCD中国
ABC中D国
*/
//
kigg 发表于某天某时某分前
public
static
string
Ago(
this
DateTime target)
{
StringBuilder result
=
new
StringBuilder();
TimeSpan diff
=
(DateTime.Now
-
target.ToLocalTime());
if
(diff.Days
>
0
)
{
result.AppendFormat(
"
{0} days
"
, diff.Days);
}
if
(diff.Hours
>
0
)
{
if
(result.Length
>
0
)
{
result.Append(
"
,
"
);
}
result.AppendFormat(
"
{0} hours
"
, diff.Hours);
}
if
(diff.Minutes
>
0
)
{
if
(result.Length
>
0
)
{
result.Append(
"
,
"
);
}
result.AppendFormat(
"
{0} minutes
"
, diff.Minutes);
}
if
(result.Length
==
0
)
{
result.Append(
"
few moments
"
);
}
return
result.ToString();
}
}
<%
# GetOutTime(Eval(
"
发布时间
"
))
%>
///
<summary>
///
///
</summary>
///
<param name="dtime">
发布时间
</param>
///
<returns></returns>
public
static
string
GetOutTime(DateTime dtime)
{
DateTime dt
=
DateTime.Now;
TimeSpan ts
=
((TimeSpan)(dt
-
dtime));
int
days
=
ts.Days;
int
hours
=
ts.Hours;
int
minutes
=
ts.Minutes;
int
milliseconds
=
ts.Milliseconds;
if
(days
>
0
)
return
string
.Format(
"
发布于{0}天前
"
, days);
if
(hours
>
0
)
return
string
.Format(
"
发布于{0}小时前
"
, hours);
if
(minutes
>
0
)
return
string
.Format(
"
发布于{0}分钟前
"
, minutes);
return
string
.Format(
"
发布于{0}秒前
"
, milliseconds);
}
public
static
string
ToPrettyDate
(
this
DateTime date
)
{
var timeSince
=
DateTime
.
Now
.
Subtract
(
date
)
;
if
(
timeSince
.
TotalMilliseconds
<
1
)
return
"not yet"
;
if
(
timeSince
.
TotalMinutes
<
1
)
return
"just now"
;
if
(
timeSince
.
TotalMinutes
<
2
)
return
"1 minute ago"
;
if
(
timeSince
.
TotalMinutes
<
60
)
return
string
.
Format
(
"{0} minutes ago"
, timeSince
.
Minutes
)
;
if
(
timeSince
.
TotalMinutes
<
120
)
return
"1 hour ago"
;
if
(
timeSince
.
TotalHours
<
24
)
return
string
.
Format
(
"{0} hours ago"
, timeSince
.
Hours
)
;
if
(
timeSince
.
TotalDays
==
1
)
return
"yesterday"
;
if
(
timeSince
.
TotalDays
<
7
)
return
string
.
Format
(
"{0} day(s) ago"
, timeSince
.
Days
)
;
if
(
timeSince
.
TotalDays
<
14
)
return
"last week"
;
if
(
timeSince
.
TotalDays
<
21
)
return
"2 weeks ago"
;
if
(
timeSince
.
TotalDays
<
28
)
return
"3 weeks ago"
;
if
(
timeSince
.
TotalDays
<
60
)
return
"last month"
;
if
(
timeSince
.
TotalDays
<
365
)
return
string
.
Format
(
"{0} months ago"
, Math
.
Round
(
timeSince
.
TotalDays
/
30
)
)
;
if
(
timeSince
.
TotalDays
<
730
)
return
"last year"
;
return
string
.
Format
(
"{0} years ago"
, Math
.
Round
(
timeSince
.
TotalDays
/
365
)
)
;
}
DateTime dt
=
DateTime.Now;
Gengerate g
=
new
Gengerate();
g.GengerateHtml();
DateTime dt2
=
DateTime.Now;
TimeSpan ts
=
dt2.Subtract(dt);
string
strTs
=
ts.TotalSeconds.ToString();
ltGengerate.Text
=
"
生成成功,生成用时
"
+
strTs
+
"
秒!
"
;
//
ddl点击赋值:
if
(DropDownList1.selectedindex
>-
1
)
{
DropDownList1.Items[DropDownList1.SelectedIndex].Text
=
TextBox1.Text;
}
//设置ddl的enabled属性:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
OnRowDataBound="GridView1_RowDataBound" >
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //一定要
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
if (ddl != null)
{
if (ddl.SelectedValue == "1")
{
ddl.Enabled = false;
}
}
}
}
string strPath = Server.MapPath("~/roomindex");
/// <summary>
/// 用递归方法删除文件夹目录及文件
/// </summary>
/// <param name="dir">带文件夹名的路径</param>
public void DeleteFolder(string dir)
{
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
File.Delete(d); //直接删除其中的文件
else
DeleteFolder(d); //递归删除子文件夹
}
Directory.Delete(dir, true); //删除已空文件夹
}
}
确保您具有足够的权限 对路径 的访问被拒绝
删除权限设置:
在web.config中的<system.web>下加入<identity impersonate="true"/>
//
根据用户选择的值设置Cookie的保存时间
if
(
this
.RadioButtonList1.SelectedValue.ToString()
==
"
1
"
)
//
一天
{
this
.Response.Cookies[
"
UserName
"
].Expires
=
DateTime.Now.AddDays(
1
);
this
.Response.Cookies[
"
Password
"
].Expires
=
DateTime.Now.AddDays(
1
);
}
if
(RadioButtonList1.SelectedValue.ToString()
==
"
2
"
)
//
一个月
{
this
.Response.Cookies[
"
UserName
"
].Expires
=
DateTime.Now.AddMonths(
1
);
this
.Response.Cookies[
"
Password
"
].Expires
=
DateTime.Now.AddMonths(
1
);
}
if
(RadioButtonList1.SelectedValue.ToString()
==
"
3
"
)
//
半年
{
this
.Response.Cookies[
"
UserName
"
].Expires
=
DateTime.Now.AddYears(
1
/
2
);
this
.Response.Cookies[
"
Password
"
].Expires
=
DateTime.Now.AddYears(
1
/
2
);
}
if
(RadioButtonList1.SelectedValue.ToString()
==
"
4
"
)
//
一年
{
this
.Response.Cookies[
"
UserName
"
].Expires
=
DateTime.Now.AddYears(
1
);
this
.Response.Cookies[
"
Password
"
].Expires
=
DateTime.Now.AddYears(
1
);
}
//
将用户输入的用户名和密码保存到Cookie中
this
.Response.Cookies[
"
UserName
"
].Value
=
this
.tname.Text;
this
.Response.Cookies[
"
Password
"
].Value
=
this
.tpass.Text;
//
跳转到getcookie.aspx页面中显示Cookie中的值
Response.Write(
"
用户登录成功!并将用户登录的用户名和密码保存到Cookie中。
"
);
}
else
{
Response.Redirect(
"
Login.aspx
"
);
}
}
//
Attribute:
Response.Write(
"
浏览器的信息为:<br>
"
);
Response.Write(
"
(1)浏览器=
"
+
Request.Browser.Browser
+
"
<br>
"
);
Response.Write(
"
(2)型态=
"
+
Request.Browser.Type
+
"
<br>
"
);
Response.Write(
"
(3)名称=
"
+
Request.Browser.Browser
+
"
<br>
"
);
Response.Write(
"
(4)版本=
"
+
Request.Browser.Version
+
"
<br>
"
);
Response.Write(
"
(5)使用平台=
"
+
Request.Browser.Platform
+
"
<br>
"
);
Response.Write(
"
(6)是否为测试版=
"
+
Request.Browser.Beta
+
"
<br>
"
);
Response.Write(
"
(7)是否为位的环境=
"
+
Request.Browser.Win16
+
"
<br>
"
);
Response.Write(
"
(8)是否为位的环境=
"
+
Request.Browser.Win32
+
"
<br>
"
);
Response.Write(
"
(9)是否支持框架(Frame)=
"
+
Request.Browser.Frames
+
"
<br>
"
);
Response.Write(
"
(10)是否支持表格(Table)=
"
+
Request.Browser.Tables
+
"
<br>
"
);
Response.Write(
"
(11)是否支持Cookies=
"
+
Request.Browser.Cookies
+
"
<br>
"
);
Response.Write(
"
(12)是否支持ActiveX Controls=
"
+
Request.Browser.ActiveXControls
+
"
<br>
"
);
string
bb
=
System.Environment.CurrentDirectory.ToString();
Response.Write(bb);
string
a
=
Request.Url.ToString();
string
b
=
Request.Path.ToString();
string
c
=
Request.PhysicalPath.ToString();
Response.Write(
"
URL地址:
"
+
a
+
"
<br>虚拟路径:
"
+
b
+
"
<br>物理路径:
"
+
c);
string
HostName
=
Server.MachineName.ToString();
Response.Write(
"
电脑的名称为:
"
+
HostName)
string
path
=
Server.MapPath(
"
~
"
).ToString();
Response.Write(
"
物理路径为:
"
+
path);
//
结果:
//
物理路径为:C:\Documents and Settings\itd0300166.PLSH166\桌面\曾祥展\ASP.NET 2.0+SQL Server 2005全程指南\Study_NET\chap05\Server
string
Encode
=
Server.HtmlDecode(
"
<b>HTML代码中的内容</b>
"
);
string
Decode
=
Server.HtmlEncode(
"
<b>HTML代码中的内容</b>
"
);
Response.Write(Encode
+
"
<br>
"
+
Decode);
结果:
HTML代码中的内容
<
b
>
HTML代码中的内容
</
b
>
http://www.cnblogs.com/hun_dan/archive/2011/03/01/1968298.html
/
///
/gridview导出excel
public
override
void
VerifyRenderingInServerForm(Control control)
{
//
Confirms that an HtmlForm control is rendered for
}
protected
void
Button3_Click(
object
sender, EventArgs e)
{
Response.Clear();
Response.Buffer
=
false
;
Response.Charset
=
"
GB2312
"
;
Response.AppendHeader(
"
Content-Disposition
"
,
"
attachment;filename=score.xls
"
);
Response.ContentEncoding
=
System.Text.Encoding.GetEncoding(
"
GB2312
"
);
Response.ContentType
=
"
application/ms-excel
"
;
Response.Write(
"
<meta http-equiv=Content-Type content=\
"
text
/
html; charset
=
GB2312\
"
>
"
);
this
.EnableViewState
=
false
;
System.Globalization.CultureInfo str
=
new
System.Globalization.CultureInfo(
"
ZH-CN
"
,
true
);
System.IO.StringWriter oStringWriter
=
new
System.IO.StringWriter(str);
HtmlTextWriter oHtmlTextWriter
=
new
HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
<
script language
=
"
javascript
"
type
=
"
text/javascript
"
>
//
先获取所有的Checkbox
var chkList
=
document.getElementsByName(
"
CheckBox1
"
);
window.onload
=
function()
{
//
为所有checkbox添加onclick事件处理,以自动更新“已选择的项”
for
(var i
=
0
; i
<
chkList.length; i
++
)
{
chkList[i].onclick
=
chkClick;
}
}
//
checkbox的onclick事件,用于更新“已选择的项”
function chkClick()
{
var checkedList
=
""
;
//
获取所有被选中的项
for
(var i
=
0
; i
<
chkList.length; i
++
){
if
(chkList[i].
checked
)
checkedList
+=
chkList[i].value
+
"
,
"
;
}
//
把选中项的列表显示到“已选择的项”中,substring在这里是为了去除最后一个逗号
document.getElementById(
"
HiddenField1
"
).value
=
checkedList.substring(
0
,checkedList.length
-
1
);
}
</
script
>
string
type
=
HiddenField1.Value;
string
[] keyValue
=
type.Split(
'
,
'
);
foreach
(
string
str
in
keyValue)
{
//
判定是否选中任何一门
string
sql1
=
"
select * from xk where 课程编号='
"
+
str
+
"
'
"
;
//
遍历 Panel1下的下拉框
foreach
(System.Web.UI.Control ddl
in
Panel1.Controls)
{
if
(ddl
is
DropDownList)
{
DropDownList d
=
(DropDownList)ddl;
str
=
str
+
d.SelectedValue.ToString()
+
"
,
"
;
}
}
int
j
=
0
;
string
[] words
=
sqlpj.Split(
'
,
'
);
//
TextBox1.Text = sqlpj.Substring(sqlpj.IndexOf(words[20]), sqlpj.Length- sqlpj.IndexOf(words[20]));
TextBox1.Text
=
sqlpj.Remove(
0
,sqlpj.IndexOf(words[
20
]));
foreach
(System.Web.UI.Control ddl
in
Panel1.Controls)
{
if
( ddl
is
DropDownList)
{
DropDownList d
=
(DropDownList)ddl;
d.Text
=
words[j];
j
++
;
}
}
//
第二种方法
string
[] sqlleft
=
new
string
[
20
];
string
sqlrigth
=
sqlpj;
for
(
int
i
=
0
; i
<
20
; i
++
)
{
int
dex
=
sqlpj.IndexOf(
'
,
'
);
sqlleft[i]
=
sqlrigth.Substring(
0
, dex);
sqlrigth
=
sqlrigth.Substring(dex
+
1
);
}
TextBox1.Text
=
sqlrigth;
int
j
=
0
;
foreach
(System.Web.UI.Control ddl
in
Panel1.Controls)
{
if
(ddl
is
DropDownList)
{
DropDownList d
=
(DropDownList)ddl;
d.Text
=
sqlleft[j];
j
++
;
}
}
<
asp:HyperLinkField DataNavigateUrlFields
=
"
任课老师
"
DataNavigateUrlFormatString
=
"
Stu_pjtea.aspx?任课老师={0}
"
HeaderText
=
"
进入评教
"
NavigateUrl
=
"
Stu_pjtea.aspx
"
Text
=
"
<font color=red >进入</font>
"
/>
string
teaname
=
Request.QueryString[
"
任课老师
"
].ToString();
//从1,50随机20个不重复数
public int[] GetRandomUnrepeatArray(int minValue, int maxValue, int count)
{
Random rnd = new Random();
int length = maxValue - minValue + 1;
byte[] keys = new byte[length];
rnd.NextBytes(keys);
int[] items = new int[length];
for (int i = 0; i < length; i++)
{
items[i] = i + minValue;
}
Array.Sort(keys, items);
int[] result = new int[count];
Array.Copy(items, result, count);
return result;
}
调用:
int[] a= GetRandomUnrepeatArray(1,100,20);
for (int i = 0; i < a.Length; i++)
{
Response.Write(a[i].ToString()+",");
}
//结果:27,34,44,19,30,67,58,18,26,57,62,16,8,91,100,31,56,85,88,29
/// <summary>
/// 从1到33中任意选取不重复的6个随机数
/// </summary>
/// <returns></returns>
public List<int> GenerateNumber()
{
//用于存放1到33这33个数 . List<int> container = new List<int>(33);
//用于保存返回结果
List<int> result = new List<int>(6);
Random random = new Random();
for (int i = 1; i <= 33; i++)
{
container.Add(i);
}
int index = 0;
int value = 0;
for (int i = 1; i <= 6; i++)
{
//从[0,container.Count)中取一个随机值,保证这个值不会超过container的元素个数
index = random.Next(0, container.Count);
//以随机生成的值作为索引取container中的值
value = container[index];
//将随机取得值的放到结果集合中
result.Add(value);
//从容器集合中删除这个值,这样会导致container.Count发生变化
container.RemoveAt(index);
//注意这一句与上面一句能达到同样效果,但是没有上面一句快
//container.Remove(value);
}
//result.Sort();排序
return result;
}
public int[] GenerateNumber()
{
//用于存放1到33这33个数
int[] container = new int[33];
//用于保存返回结果
int[] result = new int[6];
Random random = new Random();
for (int i = 1; i <= 33; i++)
{
container[i - 1] = i;
}
int index = 0;
int value = 0;
for (int i = 0; i < 6; i++)
{
//从[1,container.Count + 1)中取一个随机值,保证这个值不会超过container的元素个数
index = random.Next(1, container.Length-1-i);
//以随机生成的值作为索引取container中的值
value = container[index];
//将随机取得值的放到结果集合中
result[i]=value;
//将刚刚使用到的从容器集合中移到末尾去
container[index] = container[container.Length - i-1];
//将队列对应的值移到队列中
container[container.Length - i-1] = value;
}
//result.Sort();排序
return result;
}
Random r = new Random(Guid.NewGuid().GetHashCode()); 随机不重复
// Select/Deselect checkboxes based on header checkbox
function SelectheaderCheckboxes(headerchk) {
// debugger
var gvcheck = document.getElementById('rptList');
var i;
//Condition to check header checkbox selected or not if that is true checked all checkboxes
var checkedList = "";
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
var s=$($(inputs)).next().html();
if (s!==null) {
checkedList += s + ",";
}
document.getElementById("hidvalue").value = checkedList.substring(0, checkedList.length - 1);
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
document.getElementById("hidvalue").value = "";
}
}
//function to check header checkbox based on child checkboxes condition
function Selectchildcheckboxes(header) {
var ck = header;
var count = 0;
var gvcheck = document.getElementById('rptList');
var headerchk = document.getElementById(header);
var rowcount = gvcheck.rows.length;
var checkedList = '';
//By using this for loop we will count how many checkboxes has checked
for (i = 1; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
if (inputs[0].checked) {
count++;
var s = $($(inputs)).next().html();
if (s !== null) {
checkedList += s + ",";
}
}
document.getElementById("hidvalue").value = checkedList.substring(0, checkedList.length - 1);
}
//Condition to check all the checkboxes selected or not
if (count == rowcount - 1) {
headerchk.checked = true;
}
else {
headerchk.checked = false;
}
}
//先获取所有的Checkbox
var chkList = $('#rptList').find(".chkChild input");
window.onload = function () {
//为所有checkbox添加onclick事件处理,以自动更新“已选择的项”
for (var i = 0; i < chkList.length; i++) {
chkList[i].onclick = chkClick;
}
}
//checkbox的onclick事件,用于更新“已选择的项”
function chkClick() {
var checkedList = "";
//获取所有被选中的项
for (var i = 0; i < chkList.length; i++) {
if (chkList[i].checked)
// checkedList += chkList[i].value + ",";
checkedList += $($(chkList[i])).next().html() + ",";
}
//把选中项的列表显示到“已选择的项”中,substring在这里是为了去除最后一个逗号
document.getElementById("hidvalue").value = checkedList.substring(0, checkedList.length - 1);
}
/// <summary>
/// 随机排列数组元素 打乱顺序 调用 string[] newlist = Shuffle(arr);
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Source"></param>
public static T[] Shuffle<T>(T[] Source)
{
if (Source == null) return null;
int len = Source.Length;//用變數記會快一點點點
Random rd = new Random();
int r;//記下隨機產生的號碼
T tmp;//暫存用
for (int i = 0; i < len - 1; i++)
{
r = rd.Next(i, len);//取亂數,範圍從自己到最後,決定要和哪個位置交換,因此也不用跑最後一圈了
if (i == r) continue;
tmp = Source[i];
Source[i] = Source[r];
Source[r] = tmp;
}
return Source;
}