零碎知识汇总

作者:Dreamer
出处:http://www.dreamerlzy.com/blog/article/detail/piece-knowledge
说明:本文版权归作者所有,欢迎转载,但未经作者同意时,请在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
参考: 无

1、网页禁止右键功能 且同时防止拖动图片

<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false" onbeforecopy="return false">

2手机摇一摇背景变色

<script type="text/javascript">  
        var color = new Array('#fff', '#ff0', '#f00', '#000', '#00f', '#0ff');  
        if(window.DeviceMotionEvent) {  
            var speed = 25;  
            var x = y = z = lastX = lastY = lastZ = 0;  
            window.addEventListener('devicemotion', function(){  
                var acceleration =event.accelerationIncludingGravity;  
                x = acceleration.x;  
                y = acceleration.y;  
                if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed) {  
                    document.body.style.backgroundColor = color[Math.round(Math.random() * 10) % 6];                }  
                lastX = x;  
                lastY = y;  
            }, false);  
        }  
    </script>

3VS只显示错误不显示错误位置 一般是由于目录 路径中含有括号之类的字符,去掉即可

4、DataTable该行已存在于另一个表中

  DataRow dr = dt.Rows[0];

  dttoplocation.Rows.Add(dr.ItemArray);              

5、DropDownList绑定时避免项已被删除时的报错

sid = ds.Tables[0].Rows[0]["LId"].ToString();
li = ddlLocaiton.Items.FindByValue(sid);
if (li != null)
{
  li.Selected = true;
}
//或
ddlLocaiton.text=sid;

6、FileUpload控件的文件路径、文件名、扩展名

string fileNameNo = Path.GetFileName(FileUploadImg.PostedFile.FileName); //获取文件名和扩展名
string DirectoryName = Path.GetDirectoryName(FileUploadImg.PostedFile.FileName); //获取文件所在目录
string Extension = Path.GetExtension(FileUploadImg.PostedFile.FileName); //获取扩展名
string fileName = Path.GetFileNameWithoutExtension(FileUploadImg.PostedFile.FileName); //获取文件名(不包括扩展名)
string fullPath = Path.GetFullPath(FileUploadImg.PostedFile.FileName); //获取文件的绝对路径
string PathRoot = Path.GetPathRoot(FileUploadImg.PostedFile.FileName); //获取文件所在地分区

7、net4.0时屏蔽危险项代码无效

在web.config的httpRuntime节点上增加requestValidationMode="2.0"即可 

8、repeater嵌套绑定

(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem)
----指触发对象的类型是DadaList里的基本行或是替换行(简单的说是DataList里的所有数据项内容)
Item 是单数行,AlternatingItem是双数行
protected void RepShow_ItemDataBound(object sender, RepeaterItemEventArgs e)//绑定内部repeater
{
  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
   Repeater rep_detailphoto = (Repeater)e.Item.FindControl("rep_detailphoto");
   DataRowView rows = (DataRowView)e.Item.DataItem;
   rep_detailphoto.DataSource = Infarts.BLL.ShareInfoServices.CommonSelect("PAS_ShowIndexPhotos","Sid",rows["id"].ToString());
   rep_detailphoto.DataBind();
  }
}

9、SqlConnectionStringBuilder 

SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder("data source=127.0.0.1;uid=sa;password=pwd;database=aa.bb.cc");
//builder.DataSource = "(local)";
//builder.InitialCatalog = "Northwind";
//builder.UserID = "user1";
//builder.Password = "P@ssw0rd";
//Console.WriteLine(builder.ConnectionString);
Console.WriteLine(builder.InitialCatalog);
Console.WriteLine(builder.Password);

10、伪静态后真实的html无法访问的解决方法

<compilation>
<buildProviders>
<add extension=".html" type="System.Web.Compilation.PageBuildProvider"/>
</buildProviders>
</compilation>
<httpHandlers>
<add verb="*" path="*.html" type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>

11、下载文件时输出报文头

public void downloadfile(string s_fileName)
{
 HttpContext.Current.Response.ContentType = "application/ms-download";
 string s_path = HttpContext.Current.Server.MapPath("~/") + s_fileName;
 System.IO.FileInfo file = new System.IO.FileInfo(s_path);
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
 HttpContext.Current.Response.Charset = "utf-8";
 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
 HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
 HttpContext.Current.Response.WriteFile(file.FullName);
 HttpContext.Current.Response.Flush();
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.End();
}

12、设置站点全局编码

<globalization requestEncoding="UTF-8" responseEncoding="UTF-8"/>

13、webform弹出提示

#region//跳转 提示 类方法

/// <summary>
/// 弹出提示
/// </summary>
public static void alertInfo(Page Page, string info)
{
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "say", "<script>alert(\"" + info + "\");</script>"); return;
}

/// <summary>
/// 跳转锚点
/// </summary>
public static void Ranchor(Page page, string anchor)
{
    page.ClientScript.RegisterStartupScript(page.GetType(), "say", "<script>window.location.hash = \"" + anchor + "\"; </script>");
}

/// <summary>
/// 弹出提示并跳转网址
/// </summary>
public static void alertInfo(Page page, string info, string url)
{
    page.ClientScript.RegisterStartupScript(page.GetType(), "say", "<script>alert(\"" + info + "\");window.location.href='" + url + "'</script>"); return;
}

/// <summary>
/// 弹出提示并跳转锚点
/// </summary>
public static void alertInfoRa(Page page, string info, string anchor)
{
    page.ClientScript.RegisterStartupScript(page.GetType(), "say", "<script>alert(\"" + info + "\");window.location.hash = \"" + anchor + "\"; </script>");
}

#endregion

14、验证视图状态 MAC 失败。

<system.web>
<pages validateRequest="false"  enableViewStateMac="false">
<pages>
</system.web>

不建议使用,验证失败说明用js动态修改了服务器控件的内容或在传输过程中http的信息被篡改等

15、英文月份

<%#DateTime.Parse(Eval("publishtime").ToString()).ToString("MMM", System.Globalization.CultureInfo.GetCultureInfo("en-US"))%>

16、禁止虚拟目录中的web.config继承IIS根目录的web.config的配置

解决方法是在根目录的web.config中针对根路径通过location配置这些module和handler等, 并且在location设置允许子目录重写,以及是否被子集应用程序继承设置为false,

如下把<system.web> </system.web>包含在<location></location>结点内部

<configuration>
<location path="." allowOverride="true" inheritInChildApplications="false">
<system.web>
<httpModules>
<add name="UrlRewriteModule"
type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter" />
</httpModules>
</system.web>
</location>
</configuration>

17、流氓式弹出QQ对话框

方式一
<script language="javascript">  
var qq_chat = true;
function PlayJsAdPopWin() {
    if (qq_chat) {
        popwin = window.location.href = 'http://wpa.qq.com/msgrd?v=3&uin=1000010&site=qq&menu=yes'
    }
};
setTimeout("PlayJsAdPopWin()", 3000);
</script> 

方式二
<iframe src="http://wpa.qq.com/msgrd?v=3&uin=767415470&site=qq&menu=yes" style="display: none;"></iframe>

18、bat执行sql脚本(sqlserver)

sqlcmd -i"d:\1.sql"
sqlcmd -S "这里改成你的服务器名称" -U "帐号" -P "密码" -i "脚本路径"
osql -S . -U sa -P 123456 -d TestBigSql -i "D:\22.txt"  
pause

19、修改架构名

exec sp_changeobjectowner '数据库名.修改的表名前缀','dbo'

20、分享代码

<script type="text/javascript">
    function share(id, localurl) {
        var shareLink = [];
        shareLink.push("http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=" + localurl);
        shareLink.push("http://v.t.sina.com.cn/share/share.php?url=" + localurl);
        shareLink.push("http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?to=pengyou&url=" + localurl);
        shareLink.push("http://tieba.baidu.com/i/sys/share?link=" + localurl);
        shareLink.push("http://www.douban.com/recommend/?url=localurl" + localurl);
        shareLink.push("http://t.sohu.com/third/post.jsp?content=utf-8&amp;url=" + localurl);
        shareLink.push("http://share.renren.com/share/buttonshare.do?link=" + localurl);
        shareLink.push("http://v.t.qq.com/share/share.php?url=" + localurl);
        shareLink.push("http://profile.live.com/badge/?url=" + localurl);
        shareLink.push("http://www.kaixin001.com/repaste/share.php?rurl=" + localurl);
        shareLink.push("http://tt.mop.com/share/shareV.jsp?pageUrl=" + localurl);
        shareLink.push("http://t.163.com/article/user/checkLogin.do?link=" + localurl);

        window.open(shareLink[id], "newwindow");

    }
</script>

21、限制信息展示时图片宽度

//限制图片宽度 编辑器部分使用
<script type="text/javascript">
$(window).load(function () {
	var objimg = $(".edit img");
	var n = objimg.size();
	for (var i = 0; i < n; i++) {
		var imgw = objimg.eq(i).width();
		var w = $(".edit").width();
		if (imgw > w) {
			objimg.eq(i).css("width", w);
			objimg.eq(i).css("height","auto");
		}
	}
})
</script>

22、jquery ajax弹出具体错误 

error: function (jqXHR, textStatus, errorThrown) {
	/*弹出jqXHR对象的信息*/
	alert(jqXHR.responseText);
	alert(jqXHR.status);
	alert(jqXHR.readyState);
	alert(jqXHR.statusText);
	/*弹出其他两个参数的信息*/
	alert(textStatus);
	alert(errorThrown);
}