c#(asp.net/core)杂谈笔记


1.js解析json格式的时间


View Code
 //转换json格式时间的方法 如Date(1340239979000)转换为正常
            function ConvertJSONDateToJSDateObject(JSONDateString) {
                var date = new Date(parseInt(JSONDateString.replace("/Date(", "").replace(")/", ""), 10));
                var year = date.getFullYear();
                var month = date.getMonth + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                var hour = date.getHours();
                var minute = date.getMinutes();
                var second = date.getSeconds();
                var datastr = year + "-" + month + "-" + currentDate + " " + hour + ":" + minute + ":" + second;
                return datastr;
            }

2.查询父分类下的所有子分类(sql)。


View Code
with a as 
(
   select * from TbRegion where RegionUid='1'
   union all
   select s.* from TbRegion as s , a where s.ParRegionUid=a.RegionUid   ---这里查的a表是那个表啊?
)
select * from a

3.ajax获取session


View Code
using System.Web.SessionState;  //添加此引用
public class roadshow_demo : IHttpHandler, IReadOnlySessionState   //继承IReadOnlySessionState接口
{ 
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

4.获取别人网页上自己想要的链接地址


View Code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace asp.net技术点测试
{
    public partial class _Default : System.Web.UI.Page
    {
        //HtmlAgilityPack.dll
        //http://blog.cnfol.com/jldgold
        protected string aa;
        protected void Page_Load(object sender, EventArgs e)
        {
            //HttpWebRequest httpWebRequest = WebRequest.Create(@"http://blog.cnfol.com/jldgold/list") as HttpWebRequest;
            //HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
            //Stream stream = httpWebResponse.GetResponseStream();
            //StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            //string s = reader.ReadToEnd();
            //reader.Close();
            //stream.Close();
            //httpWebResponse.Close();
            //HtmlDocument htmlDoc = new HtmlDocument();
            //htmlDoc.LoadHtml(s);
            //HtmlNodeCollection anchors = htmlDoc.DocumentNode.SelectNodes(@"//a");
            //foreach (HtmlNode anchor in anchors)
            //{
            //    Regex reg = new Regex("景良东:");
            //    if (reg.Matches(anchor.InnerHtml).Count == 0)
            //    {

            //    }
            //    else
            //    {
            //        Response.Write(anchor.OuterHtml + "<br/>");
            //    }
            //}
            //Response.End();

            Response.Write(GainLink("http://blog.cnfol.com/jldgold/list","景良东:"));
            Response.End();
        }

        /// <summary>
        /// 获取网页上自己想要的链接
        /// </summary>
        /// <param name="link">获取网页上的链接的网页地址</param>
        /// <param name="regexstr">正则匹配自己想要的链接所共有包含的内容</param>
        /// <returns>返回链接集合</returns>
        public string GainLink(string link, string regexstr)
        {
            String str="";
            HttpWebRequest httpWebRequest = WebRequest.Create(link) as HttpWebRequest;
            HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
            Stream stream = httpWebResponse.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string s = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            httpWebResponse.Close();
            HtmlDocument htmlDoc = new HtmlDocument();
            htmlDoc.LoadHtml(s);
            HtmlNodeCollection anchors = htmlDoc.DocumentNode.SelectNodes(@"//a");
            foreach (HtmlNode anchor in anchors)
            {
                Regex reg = new Regex(regexstr);
                if (reg.Matches(anchor.InnerHtml).Count == 0)
                {

                }
                else
                {
                    str += anchor.OuterHtml+"</br>";
                }
            }
            return str;
        }
    }
}

 5.ckedit、ckfinder的使用。。


View Code
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
    <script src="ckeditor/ckeditor.js" type="text/javascript"></script>
    <script src="ckfinder/ckfinder.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
          <asp:TextBox ID="txtcontent" runat="server" TextMode="MultiLine" Height="550px" Width="100%"></asp:TextBox>
    </div>
    <script type="text/javascript">
          var editor = CKEDITOR.replace('<%= txtcontent.ClientID %>');
          CKFinder.setupCKEditor(editor, '../ckfinder/');
    </script>
    </form>
</body>
</html>


6.图片延时加载


 

View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="图片延时加载._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Lazy Load Enabled</title>
        <script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
    </head>
    <body>
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /> <!--备注,必须有滚滚动条出现,才能有延时加载效果。所以这里加了一对换行符,为了获得滚动条-->
        <img lazyload="img/bmw_m1_hood.jpg?1277878639" /><br />
        <img lazyload="img/bmw_m1_side.jpg?1277878639" /><br />
        <img lazyload="img/viper_1.jpg?1277878639" /><br />
        <img lazyload="img/viper_corner.jpg?1277878639" /><br />
        <img lazyload="img/bmw_m3_gt.jpg?1277878639" /><br />
        <img lazyload="img/corvette_pitstop.jpg?1277878639" /><br />
        <script type="text/javascript" src="Scripts/LazeLoad.js"></script>  <!--这里是需要下载添加的js-->
        <script type="text/javascript">   
            lazyLoad.Run();
        </script>
    </body>
</html>

7.无刷新图片预览、上传


View Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>图片预览效果</title>
<script src="js/CJL.0.1.min.js"></script>
<script src="js/ImagePreview.js"></script>
<script src="js/jquery-1.5.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
    
<style>
.perview {width:800px;background:#fff;font-size:12px; border-collapse:collapse; margin:auto; padding:auto;}
.perview td, .perview th {padding:5px;border:1px solid #ccc;}
.perview th {background-color:#f0f0f0; height:20px;}
.perview a:link, .perview a:visited, .perview a:hover, .perview a:active {color:#00F;}
.perview table{ width:100%;border-collapse:collapse;}
</style>
<SCRIPT>
    //清空File控件的值,并且预览处显示默认的图片
    function clearFileInput() {
        var form = document.createElement('form');
        document.body.appendChild(form);
        //记住file在旧表单中的的位置
        var file = document.getElementById("idFile");
        var pos = file.nextSibling;
        form.appendChild(file);
        form.reset();//通过reset来清空File控件的值
        document.getElementById("colspan").appendChild(file);
        document.body.removeChild(form);
        //在预览处显示图片 这是在浏览器支持滤镜的情况使用的
        document.getElementById("idImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='images/abshiu.jpg'";
        //这是是火狐里面显示默认图片的
        if (navigator.userAgent.indexOf('Firefox') >= 0) {
            $("#idImg").attr('src', 'images/abshiu.jpg');
        }
    }
    function upLoadFile() {
        var options = {
            type: "POST",
            url: 'Files.ashx',
            success: showResponse
        };

        // 将options传给ajaxForm
        $('#myForm').ajaxSubmit(options);

    }
    function showResponse() {
        alert("上传成功!");
    } 
</SCRIPT>
</head>
<body>
<form id="myForm" runat="server">
    <table border="0" class="perview">
        <tr>
                <th width="45%">选择文件</th>
                <th width="45%">预览图</th>
                <th width="10%">上传图片</th>
        </tr>
        <tr>
            <td height="200"><span id="colspan"><input id="idFile" runat="server" name="pic" type="file4.获取别人网页上自己想要的链接地址100%).attr(<s4.获取别人网页上img sr/spanc=自己想要的链接地址100%).attr(pan style="color: #800000;">" /></span>&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" id="resets" name="resets" value="还原" onclick="clearFileInput()" /></td>
            <td align="center"><img id="idImg" src="images/abshiu.jpg" /></td>
            <td><input type="button" name="resets" value="上传保存图片" onclick="upLoadFile()" /></td>
        </tr>
    </table>
    <script>

        var ip = new ImagePreview($$("idFile"), $$("idImg"), {
            maxWidth: 200, maxHeight: 200, action: "ImagePreview.ashx"
        });
        ip.img.src = ImagePreview.TRANSPARENT;
        ip.file.onchange = function() { ip.preview(); };

    </script>
    </form>
</body>
</html>
View Code
<%@ WebHandler Language="c#" Class="File_WebHandler" Debug="true" %>

using System;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;

public class File_WebHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpFileCollection files = context.Request.Files;
        if (files.Count > 0)
        {
            Random rnd = new Random();
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];

                if (file.ContentLength > 0)
                {
                    string fileName = file.FileName;
                    string extension = Path.GetExtension(fileName);
                    int num = rnd.Next(5000, 10000);
                    string path = "file/" + num.ToString() + extension;
                    file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
                }
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
View Code
<%@ WebHandler Language="c#" Class="File_WebHandler" Debug="true" %>

using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

public class File_WebHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.Count > 0)
        {
            HttpPostedFile file = context.Request.Files[0];

            if (file.ContentLength > 0 && file.ContentType.IndexOf("image/") >= 0)
            {
                int width = Convert.ToInt32(context.Request.Form["width"]);
                int height = Convert.ToInt32(context.Request.Form["height"]);

                string path = "data:image/jpeg;base64," + Convert.ToBase64String(ResizeImg(file.InputStream, width, height).GetBuffer());

                context.Response.Write(path);
            }
        }
    }

    public MemoryStream ResizeImg(Stream ImgFile, int maxWidth, int maxHeight)
    {
        Image imgPhoto = Image.FromStream(ImgFile);
        
        decimal desiredRatio = Math.Min((decimal)maxWidth / imgPhoto.Width, (decimal)maxHeight / imgPhoto.Height);
        int iWidth = (int)(imgPhoto.Width * desiredRatio);
        int iHeight = (int)(imgPhoto.Height * desiredRatio);
        
        Bitmap bmPhoto = new Bitmap(iWidth, iHeight);

        Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
        gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(0, 0, imgPhoto.Width, imgPhoto.Height), GraphicsUnit.Pixel);

        MemoryStream ms = new MemoryStream();
        bmPhoto.Save(ms, ImageFormat.Jpeg);

        imgPhoto.Dispose();
        gbmPhoto.Dispose();
        bmPhoto.Dispose();

        return ms;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}


8.linq 与 AspNetPager.dll 的结合使用


View Code
//1.在工具栏里添加选项卡并为其命名。。
//2.在添加的选项卡里添加dll引用。
//3.编写代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace lky_link_to_sql
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BingdingD_Newsread();   //绑定表的方法;     

        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            
            BingdingD_Newsread();  

        }

        private void BingdingD_Newsread()
        {
            link_to_sql.DataClasses1DataContext Dns = new link_to_sql.DataClasses1DataContext();  // Linq to sql 类形成的model;
            var News = from nm in Dns.sb_data_tables  select nm;
            News = News.OrderByDescending(T => T.data_tables_id);
            PagedDataSource pds = new PagedDataSource();
            pds.DataSource = News.ToList();  //这里好像一定要Tolist();不然会有点错误;
            pds.AllowPaging = true;

            AspNetPager1.RecordCount = News.Count(); //记录总数;
            pds.CurrentPageIndex = AspNetPager1.CurrentPageIndex - 1;
            pds.PageSize = AspNetPager1.PageSize;
            Repeater1.DataSource = pds;
            Repeater1.DataBind();
        }



    }
}



////////////////////////////////////////////////////////////////////////////


<div style=" float:left;">   
<asp:Repeater ID="Repeater1" runat="server">
 <ItemTemplate>
 <p><%#Eval("nname") %></p>
</ItemTemplate>    
    </asp:Repeater>
    </div>
    <div>
    <webdiyer:AspNetPager ID="AspNetPager1" runat="server"  PageSize="4"  FirstPageText="首页"  LastPageText="末页" NextPageText="下一页" PrevPageText="上一页" AlwaysShow="true"
            onpagechanged="AspNetPager1_PageChanged" HorizontalAlign="Center">
    </webdiyer:AspNetPager></div>  

9.jquery 判断是否隐藏


View Code
var temp= $("#test").is(":hidden");//是否隐藏 如果隐藏true否则为false
        var temp1= $("#test").is(":visible");//是否可见 如果显示true否则为false
        var temp2=$("#test").css("display")="none";  //是否可见 如果显示true否则为false

10.repeater 嵌套---多级分类绑定


View Code
public partial class repeater嵌套使用 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        rpt1Bind();
    }

    public void rpt1Bind()
    {
        xdf.BLL.KindsBLL bll = new xdf.BLL.KindsBLL();
        DataSet ds = bll.GetList(6, "type='雅顿产品'", "");
        Repeater1.DataSource = ds;
        Repeater1.DataBind();
    }
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Repeater rep = e.Item.FindControl("Repeater2") as Repeater;//找到里层的repeater对象
            DataRowView rowv = (DataRowView)e.Item.DataItem;//找到分类Repeater关联的数据项 即点击行的一行数据
            string typename = rowv["name"].ToString(); //获取点击行的列数据
            xdf.BLL.KindsBLL bll = new xdf.BLL.KindsBLL();
            DataSet ds = bll.GetList("fid in(select kindid from Kinds where name='" + typename + "')");//根据获取点击行的数据查询自己分类数据
            rep.DataSource = ds;
            rep.DataBind();
        }
    }

}
View Code
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">  <!--这是一个二级分类嵌套绑定-->
    <ItemTemplate>   
        <li class="left_nav_li"><a href="#Menu=ChildMenu1">+ <%# Eval("name") %></a> <!--绑定父分类中的列表数据-->
            <asp:Repeater ID="Repeater2" runat="server">
                <ItemTemplate>
                    <ul class="collapsed">
                         <li><a href="#"><%# Eval("type") %></a></li> <!--绑定子分类中的列表数据-->
                    </ul>
                </ItemTemplate>
            </asp:Repeater>
             
        </li>
    </ItemTemplate>
</asp:Repeater>

11.js获取项目根路径


View Code
 function getRootPath(){    //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp  
                   var curWwwPath=window.document.location.href;    //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp  
                   var pathName=window.document.location.pathname;  
                   var pos=curWwwPath.indexOf(pathName);    //获取主机地址,如: http://localhost:8083   
                   var localhostPaht=curWwwPath.substring(0,pos);    //获取带"/"的项目名,如:/uimcardprj  
                   var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);    
                   alert(localhostPaht+projectName);
                }

12.js获取完整路径,上面哪个不一定能获取到不过也能用


View Code
//获取完整路径
        function serverMapPath(fileName){
                var syspath = location.href; 
                syspath = syspath.tFile_WebHandler/preoLowerCase();      //把路径名称转换成小写
                myPosition = syspath.lastIndexOf("/");  // 获取文件路径中的最后一个"/"
                syspath = syspath.substring(0,parseInt(myPosition)+1); // 使用substring函数 截取"/"之前的字符串,就得到当前目录的路径 
                syspath = syspath.replace("file:///","");   //这里要把file:///替换为空,否则会报错
                syspath = syspath.replace(new RegExp("%20","gm")," ");   // 如果文件名中含有空格,则要还原空格,替换所有的 %20 为 " "
                syspath = syspath + fileName; 
                alert(syspath.toString());
        }
         function aa()
         {
            serverMapPath("XMLFile1.xml");
         }

13.js中遇到 'return' 语句在函数之外                    解决办法------把js以UTF-8方式保存即可


14. 精度(p)跟小数位(s)   的 解释        123.45   此数的精度为5 小说位 为2    数据库中的decimal(p, s) 


 15.asp.net页面内的跳转锚


 

View Code
                   <script type="text/javascript">
                       function aa() {
                           document.location.href = "#selectfmd";
                       }
                   </script>
                    <img  src="images/icon_ask.jpg" onclick="aa()" />    <!--从这里开始跳转-->


                    <a id="selectfmd" />  <!--跳转到这里-->

16.sql数据库中的的默认值设置 :   时间的默认值为getdate(), Guid默认值为newid()。


 17.自定义鼠标图标 火狐 谷歌 ie 兼容问题处理 :   $("#ctdiv").css({ "cursor": "url(images/next.cur),pointer" });


18.ie下正则的兼容性问题,去掉'\','/'这些符号


                var natrn = /^url.+images.+next.+cur.+pointer$/;
                if (cursorstr.match(patrn)) {         //cursorstr为要匹配的字符串,如果匹配成功则为true
                  return true;
                 }
                 else{ return false; }

19.ie下做淡隐淡出fadein fadeout效果时png 透明图片会带黑边。。  不得不说ie很垃圾,比其它浏览器还有好长的路要走!!


20.利于seo的<h1></h1>标签的使用,<h1>标签应该在超链接外边,样式加载h1{font-size=12px;font-weight=100;display : inline;}


 21. <%# Container.ItemIndex+1%> 效果是 序号 为123456....


 22.设为首页,加入收藏


View Code
function addfavor(url, title) {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf("msie 8") > -1) {
        external.AddToFavoritesBar(url, title, '收藏名称'); //IE8
    } else {
        try {
            window.external.addFavorite(url, title);
        } catch (e) {
            try {
                window.sidebar.addPanel(title, url, ""); //firefox
            } catch (e) {
                alert("加入收藏失败,请使用Ctrl+D进行添加");
            }
        }
    }
}


<a href="#" onClick="this.style.behavior='url(#default#homepage)'; this.setHomePage(document.location.href);event.returnValue=false;">设为首页</a></span> | <span><a href="javascript:void(0);" onclick="javascript:addfavor(window.location,'收藏名称');">加入收藏</a></span>

23.数据库uniqueidentifier无法转换为int类型问题,可以把uniqueidentifier类型先转换为nvarchar类型保存,然后在有nvarchar类型转换为int类型,呵呵,愚见愚行。


 24. 借鉴PetShop的架构搭建架构的时候出现的问题(如下):


1.未能加载文件或程序集“”或它的某一个依赖项。系统找不到指定的文件

解决方法:右键程序集属性名称,命名空间检查(不但要检测程序集里面的命名空间,还要检测dal中命名空间是否争取)。没问题的话当前程序集要添加dal.dll

2.C#程序启动时,提示调用的目标发生了异常

解决方法:创建sqlHelper类的工厂类中检测获取Type必须为 System.Type.GetType("Snet.DBUtility.SqlHelper") //这里必须为带命名空间的完整类名


 25.存储过程中参数为输出参数,输出参数参加拼接语句(解决方法)

View Code
@userNum int output,
@where nvarchar(255)
as
declare @sqlStr nvarchar(500)
if(@where!='')
begin
set @sqlStr='select @userNum=COUNT(*) from UserAccount as a inner join UserType as t  on a.UserName=t.UserName left join UserCommInfo as c on c.UserName=a.UserName where '+@where
EXEC sp_executesql @sqlStr, N'@userNum int output', @userNum output  ---注意在执行@sqlStr语句时需要指定参数为输出参数
end
else
select @userNum=COUNT(*) from UserAccount as a inner join UserType as t  on a.UserName=t.UserName left join UserCommInfo as c on c.UserName=a.UserName

26.刷新验证码,这个老忘加单引号,烦人。


<img src="ValCode.aspx" title="点击图片,换一张清晰验证码" onclick="this.src='ValCode.aspx?Math.random()'"/>

 27.js中的 defer


 默认为false,加上defer等于在页面完全载入后再执行,相当于 window.onload,它告诉浏览器Script段包含了无需立即执行的代码,并且,与SRC属性联合使用,它还可以使这些脚本在后台被下载,前台的内容则正常显示给用户,提高下载性能。<script language="javascript" defer>显式声明defer属性后等同于<script language="javascript" defer=true></script> 


 28.数据库创建 唯一约束 --这个很久没用忘记了。


 1.建过表时,右键单击想要创建约束的列名。

 2.点开 索引/键 ,里面已经有一个约束了,你需要点击下面添加,创建自己的一个约束

 3。选择列,在下面的唯一中选择是


29. asp.net用户控件传参:

View Code
<body>
    <form id="form1" runat="server">
    <div>    
    </div>
        <!----这里的Name一定要与,自定义里面的属性名一样----->
    <uc1:WebUserControl1 ID="WebUserControl11" Name="你好" runat="server" />
    </form>
</body>


--------------------------------------------------------------------------------


public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(name);
            
        }
        private string name;
        public string Name   //获取页面定义的参数,名称注意与参数一样
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
    }

30.请求在此上下文中不可用 


解决方案:
只有你的页面是ASP.NET调用的,你的Page类里的Response对象才有意义。  
如果你需要在你自己的类里调用Response,请用System.Web.HttpContext.Current.Response。


 31.未能加载文件或程序集……或它的某一个依赖项。参数不正确。 (异常来自 HRESULT:0x80070057 (E_INVALIDARG))


解决方法 是 删除 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary  ASP.NET files 文件夹。

我的VS编辑器是 VS2008 。在 VS2005中可能是 C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary  文件夹。

此文件夹是 VS编辑器的 运行的临时文件夹。 当突然死机的时候 可能在这里 遗留了 当前调试项目的 编译没有完成的文件。


 32 .文本框限制输入,不符合,自动清楚。适合,金钱框....


View Code
1.文本框只能输入数字代码(小数点也不能输入)
<input onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')">
2.只能输入数字,能输小数点.
<input onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')">
<input name=txt1 onchange="if(/\D/.test(this.value)){alert('只能输入数字');this.value='';}">
4.只能输入字母和汉字
<input onkeyup="value=value.replace(/[\d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[\d]/g,''))" maxlength=10 name="Numbers">
5.只能输入英文字母和数字,不能输入中文
<input onkeyup="value=value.replace(/[^\w\.\/]/ig,'')">
6.只能输入数字和英文<font color="Red">chun</font>
<input onKeyUp="value=value.replace(/[^\d|chun]/g,'')">
7.小数点后只能有最多两位(数字,中文都可输入),不能输入字母和运算符号:
<input onKeyPress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode!=46 || /\.\d\d$/.test(value))event.returnValue=false">
8.小数点后只能有最多两位(数字,字母,中文都可输入),可以输入运算符号:
<input onkeyup="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')">
9.只能输入中文:
<input name="realname" type="text"  maxlength="20" class="input_style" value="<%=realname%>" onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))" />

33.window.open(); js,打开一个新窗口函数,参数设定


View Code
window.open('index.aspx', "newwindow2", "top=100, left=100,toolbar=yes, menubar=yes, scrollbars=yes, resizable=yes, location=yes, status=yes");


//        <SCRIPT LANGUAGE="javascript"> js脚本开始; 
//        window.open 弹出新窗口的命令; 
//        'page.html' 弹出窗口的文件名; 
//        'newwindow' 弹出窗口的名字(不是文件名),非必须,可用空''代替; 
//        height=100 窗口高度; 
//        width=400 窗口宽度; 
//        top=0 窗口距离屏幕上方的象素值; 
//        left=0 窗口距离屏幕左侧的象素值; 
//        toolbar=no 是否显示工具栏,yes为显示; 
//        menubar,scrollbars 表示菜单栏和滚动栏。 
//        Resizable=no 是否允许改变窗口大小,yes为允许; 
//        location=no 是否显示地址栏,yes为允许; 
//        status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许; 
//        </SCRIPT> js脚本结束 

34.运行时错误,未能加载程序集或文件(如下图)


 

错误原因:做项目时,把项目考来考去的,致使忘记原来的路径,哎......

解决 方案:

        1.临时性解决方案:看准路径,把snet.web下bin目录下的dll文件清空。这是临时解决方案,如果重新生成的话,问题继续。

        2.真实的解决方案:看准路径这个项目必须要在,D盘--->招生人脉网--->任意目录--->Snet下(如下图)



 

35. <%#Eval("AddDate","{0:f2}")%>



36.写存储过程要注意的,自己老忘

            1、拼接sql语句时要有空格

            2、拼接Sql语句要统一类型,不要一句话有nvarchar又有varchar  只要nvarchar吧

            3、来个简单实例

  

View Code
ALTER procedure [dbo].[Pro_GetMaxId]
@TableName nvarchar(80),
@Id nvarchar(8),
@ReId nvarchar(8) output
as
declare @strSQL  nvarchar(600)
set @strSQL= 'select @ReId= Max('+@Id+') from '+ @TableName 
EXEC sp_executesql @strSQL, N'@ReId nvarchar(8) OUT',@ReId OUT

 



 37.我喜欢的js链接

http://www.jiathis.com/

http://www.codefans.net 



 38.删表删存储过程,方便

View Code
while(1=1)
begin
declare
@num int  ,
@sql nvarchar(500),
@tb nvarchar(30)

set @num=0

while(1=1)
begin
    begin
    set @num=@num+1
    end
select  @tb = t.name from
(
select row_number()over(order by name desc) as row , name from snet..sysobjects where type='u'
) as t where t.row =@num

set @sql='drop table '+@tb
exec sp_executesql @sql
if(@num=150)
begin
set @num=0
end
end
end

 



 39. 也比较帅吧,sql查询

SELECT id, Name, Introduction, phone, contact, imageUrl, types, username,
(
SELECT  TOP (1) id  FROM ShoppingCoupons WHERE ( username = m.username ) ORDER BY addtime DESC 
)
AS sid 

FROM  dbo.MerchantsInfo AS m 
View Code


 40,js操作select

//判断select选项中 是否存在Value="paraValue"的Item 
//向select选项中 加入一个Item 
//从select选项中 删除一个Item 
//删除select中选中的项 
//修改select选项中 value="paraValue"的text为"paraText" 
//设置select中text="paraText"的第一个Item为选中 
//设置select中value="paraValue"的Item为选中 
//得到select的当前选中项的value 
//得到select的当前选中项的text 
//得到select的当前选中项的Index 
//清空select的项 
//js 代码
// 1.判断select选项中 是否存在Value="paraValue"的Item        
function jsSelectIsExitItem(objSelect, objItemValue) {        
    var isExit = false;        
    for (var i = 0; i < objSelect.options.length; i++) {        
        if (objSelect.options[i].value == objItemValue) {        
            isExit = true;        
            break;        
        }        
    }        
    return isExit;        
}         
   
// 2.向select选项中 加入一个Item        
function jsAddItemToSelect(objSelect, objItemText, objItemValue) {        
    //判断是否存在        
    if (jsSelectIsExitItem(objSelect, objItemValue)) {        
        alert("该Item的Value值已经存在");        
    } else {        
        var varItem = new Option(objItemText, objItemValue);      
        objSelect.options.add(varItem);     
        alert("成功加入");     
    }        
}        
   
// 3.从select选项中 删除一个Item        
function jsRemoveItemFromSelect(objSelect, objItemValue) {        
    //判断是否存在        
    if (jsSelectIsExitItem(objSelect, objItemValue)) {        
        for (var i = 0; i < objSelect.options.length; i++) {        
            if (objSelect.options[i].value == objItemValue) {        
                objSelect.options.remove(i);        
                break;        
            }        
        }        
        alert("成功删除");        
    } else {        
        alert("该select中 不存在该项");        
    }        
}    
   
   
// 4.删除select中选中的项    
function jsRemoveSelectedItemFromSelect(objSelect) {        
    var length = objSelect.options.length - 1;    
    for(var i = length; i >= 0; i--){    
        if(objSelect[i].selected == true){    
            objSelect.options[i] = null;    
        }    
    }    
}      
   
// 5.修改select选项中 value="paraValue"的text为"paraText"        
function jsUpdateItemToSelect(objSelect, objItemText, objItemValue) {        
    //判断是否存在        
    if (jsSelectIsExitItem(objSelect, objItemValue)) {        
        for (var i = 0; i < objSelect.options.length; i++) {        
            if (objSelect.options[i].value == objItemValue) {        
                objSelect.options[i].text = objItemText;        
                break;        
            }        
        }        
        alert("成功修改");        
    } else {        
        alert("该select中 不存在该项");        
    }        
}        
   
// 6.设置select中text="paraText"的第一个Item为选中        
function jsSelectItemByValue(objSelect, objItemText) {            
    //判断是否存在        
    var isExit = false;        
    for (var i = 0; i < objSelect.options.length; i++) {        
        if (objSelect.options[i].text == objItemText) {        
            objSelect.options[i].selected = true;        
            isExit = true;        
            break;        
        }        
    }              
    //Show出结果        
    if (isExit) {        
        alert("成功选中");        
    } else {        
        alert("该select中 不存在该项");        
    }        
}        
   
// 7.设置select中value="paraValue"的Item为选中    
document.all.objSelect.value = objItemValue;    
       
// 8.得到select的当前选中项的value    
var currSelectValue = document.all.objSelect.value;    
       
// 9.得到select的当前选中项的text    
var currSelectText = document.all.objSelect.options[document.all.objSelect.selectedIndex].text;    
       
// 10.得到select的当前选中项的Index    
var currSelectIndex = document.all.objSelect.selectedIndex;    
       
// 11.清空select的项    
document.all.objSelect.options.length = 0;  
View Code

  41、webservice 地址



 42、Jquery 操作表格

$(".msgtable tr:nth-child(odd)").addClass("tr_bg"); //隔行变色     tr:nth-child(odd)  所有的tr odd表示奇数行, even 表示偶数行。

43、A potentially dangerous Request.Form value was detected from the client (prodDescriptionZh="<img src="/upload/2/...").

<system.web>
    <httpRuntime requestValidationMode="2.0"/>     
</system.web>

44丶webservice 传递字符超额。

 </system.web>   ----位置

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="NewBehavior">
          <dataContractSerializer maxItemsInObjectGraph="65536000" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding name="PmsChaRecServiceSoap" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647"
          textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192000" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security>
            <transport realm="" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://192.168.0.100:8081/PmsChaRecService.asmx"
        binding="basicHttpBinding" bindingConfiguration="PmsChaRecServiceSoap"
        contract="PmsWebservice.PmsChaRecServiceSoap" name="PmsChaRecServiceSoap" />
    </client>
  </system.serviceModel>



</configuration>   ----位置
View Code

45丶extjs3 日期控件在谷歌中拉长 


 

.x-date-picker
{
    border: 1px solid #1b376c;
    border-top: 0 none;
    background: #fff;
    position: relative;
    width:185px;
}
View Code

把原来的css换为这个。

46、跨服务器链接数据库,

消息 15281,级别 16,状态 1,第 2 行
SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT'OpenRowset/OpenDatasource' 的访问,因为此组件已作为此服务器安全配置的一部分而被关闭。系统管理员可以通过使用 sp_configure 启用 'Ad Hoc Distributed Queries'。有关启用 'Ad Hoc Distributed Queries' 的详细信息,请参阅 SQL Server 联机丛书中的 "外围应用配置器"。  

-- 启用Ad Hoc Distributed Queries
exec sp_configure 'show advanced options',1  
reconfigure  
exec sp_configure 'Ad Hoc Distributed Queries',1  
reconfigure  

select * from 
openrowset
('SQLOLEDB', '117.74.135.19'; 'sa';'huayueinfo', new8843.dbo.activity)


select * from 
opendatasource(
'SQLOLEDB','Data Source=117.74.135.19;User ID=sa;password=huayueinfo'
).new8843.dbo.activity


--使用完成后,关闭Ad Hoc Distributed Queries:
exec sp_configure 'Ad Hoc Distributed Queries',0  
reconfigure  
exec sp_configure 'show advanced options',0  
reconfigure  

47、一个表的一个字段中实现 字段值包含一批连续的字符串,效果如图:

begin
declare @i int ;
set @i=77541214;
update dbo.Am_ShoPaper set shoPapNumber='AMHD'+CONVERT(varchar,@i),@i=@i+1;
end 
View Code

 

48、MVC4项目中(.net 4.5)区域模块中 报错 “System.Web”中不存在类型或命名空间名称“Optimization”


 

MVC4项目中(.net 4.5)区域模块中报错:

命名空间“System.Web”中不存在类型或命名空间名称“Optimization”(是否缺少程序集引用?)

很明显,添加区域时,vs自动在web.config文件中增加了Optimization命名空间的配置,

(Optimization 的作用是优化压缩script 和css )

 

区域文件夹中view文件夹下的Web.config文件配置中:

<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>

而在程序中却没有引用   System.Web.Optimization.dll  ,所以为了解决报错,可直接在   工具----库程序包管理器------程序包管理器控制台   执行下面

Install-Package Microsoft.AspNet.Web.Optimization

 


49.CS0234: 命名空间“System.Web.Mvc”中不存在类型或命名空间名称“Ajax”, CS0234: 命名空间“System.Web.Mvc”中不存在类型或命名空间名称“Html”


在工程引用中,将System.Web.Mvc 属性 “复制本地” 设置为 true 即可


 51、t-sql rownumber 分组排序

SELECT ROW_NUMBER() OVER(PARTITION BY ucode ORDER BY ucode) sn,* FROM ZP_DriverStatus
    WHERE uCode 
    IN
    (
    'zp1006422',    
    'zp1008590',
    'zp1009505'
    )

 52、mvc,webapi传递数组。

 js 传递时 要设置 traditional: true

 53、路由配置的变量

{SERVER_PORT} 端口变量
{HTTP_HOST} 域名

 54、让你浏览器死的代码

<script>
var total="";
for (var i=0;i<1000000;i++)
{
    total= total+i.toString ();
    history.pushState (0,0,total);
}
</script>
View Code

 56、数据库当前连接查询

select s.open_transaction_count ,
c.most_recent_sql_handle,t.text,s.*
 from sys.dm_exec_sessions s
inner join sys.dm_exec_connections c
on s.session_id = c.session_id 
cross apply sys.dm_exec_sql_text(c.most_recent_sql_handle) t
where program_name  = 'back_sRW.aidaijia.com'
  <add name="ReadOnlyDB" connectionString="server=192.168.10.53\MSSQLSERVER1;uid=un_adj;pwd=123.com;database=aidaijiaNew;Application Name=back_sRW.aidaijia.com" providerName="System.Data.SqlClient"/>
View Code

 57、设置cpu使用,任务管理器,详细信息,右键设置相关性。

 58、 layer.msg("1", { icon: 1 }); 1-7都是什么?

59. vs文件嵌套工具 File Nesting

60.创建视图或者控制器的时候需要在debug环境下创建

61.如果出现有代码已优化,调试不出变量,需要在项目属性生成中,把优化代码去掉√

62.操作枚举

 #region 通过枚举获取select的options
        /// <summary>
        /// 获取枚举的Options
        /// </summary>
        public static string GetEnumOptions<T>(object defaultValue = null)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                var data = GetEnumDic(typeof(T));
                if (data != null)
                {
                    foreach (var m in data)
                    {
                        if (defaultValue != null && defaultValue + "" == m.Key)
                        {
                            sb.Append($"<option selected='selected' value='{m.Key}'>{m.Value}</option>");
                        }
                        else
                        {
                            sb.Append($"<option value='{m.Key}'>{m.Value}</option>");
                        }

                    }
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                log.Debug(ex.Message);
                return "";
            }
        }
        ///<summary>
        /// 返回 Dic<枚举项,描述>
        ///</summary>
        ///<param name="enumType"></param>
        ///<returns>Dic<枚举项,描述></returns>
        static Dictionary<string, string> GetEnumDic(Type enumType)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            FieldInfo[] fieldinfos = enumType.GetFields();
            foreach (FieldInfo field in fieldinfos)
            {
                if (field.FieldType.IsEnum)
                {
                    Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    var intValue = (int)System.Enum.Parse(enumType, field.Name);
                    dic.Add(intValue + "", ((DescriptionAttribute)objs[0]).Description);
                }
            }

            return dic;
        }
        #endregion
View Code

63.ftp服务器,文件夹打开出现权限不足,但是浏览器可以打开时,如下设置,首先需安装ftp服务与ftp扩展2个程序.

ie如:谷歌如:

64. git上传时提示:413 Request Entity Too Large 的解决方法

 65.控制台exe后台执行操作如下

1.新建后缀名为vbs的文件

2.写入下列代码,即可.

Set ws = CreateObject("Wscript.Shell")

ws.run "E:\mindoc_windows_amd64\mindoc.exe",0

3.设置开机启动,

win10 中 C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp 文件夹下放入 vbs文件或者vbs快捷键

 

66.平日里运行的好好的,突然报错,让我措手不及啊.简易的解决方案如下.日后有时间再来看看吧.(配置文件解决)

CS0012: 类型“System.Object”在未被引用的程序集中定义。必须添加对程序集“System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”的引用。

<system.web>
      <assemblies>
        <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
      </assemblies>
    </compilation>
  </system.web>

 行转列列转行

select * from dbo.SplitString('1¥2¥3','','1')

SELECT STUFF((SELECT top 3 ''+orderno FROM AttendOrder for xml path('')),1,1,'')

引用类型对象去重

class OrderListComparer : IEqualityComparer<GiftsProduct>
        {
            public bool Equals(GiftsProduct x, GiftsProduct y)
            {
                if (Object.ReferenceEquals(x, y)) return true;
                if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                    return false;
                return x.Pid == y.Pid;
            }

            public int GetHashCode(GiftsProduct gift)
            {
                if (Object.ReferenceEquals(gift, null)) return 0;
                int hashStudentName = gift.Pid == null ? 0 : gift.Pid.GetHashCode();
                return hashStudentName;
            }
        }
View Code

 jqueryui 自动补全完善

  var arr_InstallShopId = [];
        $("#a_InstallShopId").blur(function () {
            var text = $(this).val();
            if (text == "") {
                return $("#InstallShopId").val("");
            }
            arr_InstallShopId.forEach(function (item, index) {
                if (text == item.label) {
                    return $("#InstallShopId").val(item.key);
                }
            });
        }).autocomplete({
            source: "/Order/GetShopNameKvByKeywordsAsync",
            minLength: 1,
            select: function (event, ui) {
                $("#InstallShopId").val(ui.item.key);
            },
            focus: function () {
                $("#InstallShopId").val("");
            },
            open: function () {
                $("#InstallShopId").val("");
            },
        }).data("autocomplete")._renderItem = function (ul, item) {
            arr_InstallShopId.push(item);
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a>" + item.value + "</a>")
                .appendTo(ul);
        };
View Code

 如果你想要看framework 版本号,可以直接输入%systemroot%\Microsoft.NET\Framework

 EZDML生成model脚本

function ExtStr(Str: string; Len: Integer): string;
var
  I: Integer;
begin
  Str := Trim(Str);
  if Length(Str) <= Len then
    for I := Length(Str) to Len do
      Str := Str + ' ';
  Result := Str;
end;

function DEF_CTMETAFIELD_DATATYPE_NAMES_CSHARP(idx: TCtFieldDataType): string;
begin
  case Integer(idx) of
    0: Result := 'unknown';
    1: Result := 'string';
    2: Result := 'int';
    3: Result := 'double';
    4: Result := 'DateTime';
    5: Result := 'bool';
    6: Result := 'enum';
    7: Result := 'var';
    8: Result := 'object';
    9: Result := 'List';
    10: Result := 'function';
    11: Result := 'EventHnadler';
    12: Result := 'type';
  else
    Result := 'unknown';
  end;
end;


function getProtectName(N: string): string;
begin
  Result := N;
  if (Result <> '') and (N <> UpperCase(N)) then
    if Result[1] >= 'A' then
      if Result[1] <= 'Z' then
        Result[1] := Chr(Ord(Result[1]) + (Ord('a') - Ord('A')));
end;

function getPublicName(N: string): string;
begin
  Result := N;
  if (Result <> '') then
    if Result[1] >= 'a' then
      if Result[1] <= 'z' then
        Result[1] := Chr(Ord(Result[1]) - (Ord('a') - Ord('A')));
end;

function GetDesName(p, n: string): string;
begin
  if p = '' then
    Result := n
  else
    Result := p;
end;

var
  I, L: Integer;
  clsName, S, T, V, FT: string;
  f: TCtMetaField;

function GFieldName(Fld: TCtMetaField): string;
begin
  Result := GetDesName(f.Name, f.DisplayName);
end;

function GFieldType(Fld: TCtMetaField): string;
begin
  if f.DataType = cfdtOther then
    Result := f.DataTypeName
  else if f.DataType = cfdtEnum then
    Result := getPublicName(GFieldName(f)) + 'Enum'
  else
    Result := DEF_CTMETAFIELD_DATATYPE_NAMES_CSHARP(f.DataType);
end;

procedure AddFieldInfo;
begin
  S := GetDesName(f.Name, f.DisplayName);
  if f.DataType = cfdtFunction then
  begin
    FT := f.DataTypeName;
    if FT = '' then
      FT := 'void';
    S := 'public ' + FT + ' ' + getPublicName(S) + '()'#13#10
      + '{' + #13#10
      + '}';
  end
  else
  begin
    if f.DataType = cfdtOther then
      FT := f.DataTypeName
    else if f.DataType = cfdtEnum then
      FT := GFieldType(f)
    else
      FT := DEF_CTMETAFIELD_DATATYPE_NAMES_CSHARP(f.DataType);
    S := 'public ' + FT + ' ' + getPublicName(S) + '{ get;  set;}';
  end;

  T := F.GetFieldComments;
  if T <> '' then
  begin
      //T := F.Comment;
    if (Pos(#13, T) > 0) or (Pos(#10, T) > 0) then
    begin
      if Length(T) <= 100 then
      begin
        T := StringReplace(T, #13#10, ' ', [rfReplaceAll]);
        T := StringReplace(T, #13, ' ', [rfReplaceAll]);
        T := StringReplace(T, #10, ' ', [rfReplaceAll]);
        S := '//' + T + #13#10 + S;
      end
      else
      begin
        T := '{' + StringReplace(T, '}', '%7D', [rfReplaceAll]) + '}';
        S := T + #13#10 + S;
      end;
    end
    else
      S := '//' + T + #13#10 + S;
  end;

  CurOut.Add('    ' + StringReplace(S, #13#10, #13#10'    ', [rfReplaceAll]));
end;
begin
  with CurTable do
  begin
    S := GetTableComments;
    CurOut.Add('/*');      
    CurOut.Add('  ###CSharp Code Generate###');
    CurOut.Add('  ' + Name);
    CurOut.Add('  Create by User(zlh) ' + DateTimeToStr(Now));
    CurOut.Add('*/');
    CurOut.Add('');
    CurOut.Add('using System;');
    CurOut.Add('using System.Text;');
    CurOut.Add('');
    CurOut.Add('namespace ' + Name);
    CurOut.Add('{');

    for I := 0 to MetaFields.Count - 1 do
    begin
      f := MetaFields[I];
      case f.DataType of
        cfdtEnum:
          begin
            CurOut.Add('  public enum ' + GFieldType(f) + '{ Unknown, Value1, Value2 }');
            CurOut.Add('');
          end;
      end;
    end;

    S := GetTableComments;
    if S <> '' then
    begin
      S := StringReplace(S, '}', '%7D', [rfReplaceAll]);
      CurOut.Add('  /* ' + StringReplace(S, #13#10, #13#10'  ', [rfReplaceAll]) + ' */');
    end;

    L := 0;
    for I := 0 to MetaFields.Count - 1 do
    begin
      f := MetaFields[I];
      S := GetDesName(f.Name, f.DisplayName);
      if L < Length(S) then
        L := Length(S);
    end;

    clsName := Name;

    CurOut.Add('  public class ' + clsName);
    CurOut.Add('  {');
    CurOut.Add('');
    for I := 0 to MetaFields.Count - 1 do
    begin
      f := MetaFields[I];
      AddFieldInfo;
    end;
    CurOut.Add('}');
    CurOut.Add('}');
  end;
end.  

部分密码检测,不含弱密码,及账号检测

 /// <summary>
        /// 计算字符串中子串出现的次数
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="substring">子串</param>
        /// <returns>出现的次数</returns>
        static int SubstringCount(string str, string substring)
        {
            if (str.Contains(substring))
            {
                string strReplaced = str.Replace(substring, "");
                return (str.Length - strReplaced.Length) / substring.Length;
            }

            return 0;
        }
        /// <summary>
        /// 密码强度
        /// </summary>
        private enum Strength
        {
            Invalid = 0, //无效密码
            Weak = 1, //低强度密码
            Normal = 2, //中强度密码
            Strong = 3 //高强度密码
        };
        /// <summary>
        /// 计算密码强度
        /// </summary>
        /// <param name="password">密码字符串</param>
        /// <returns></returns>
        private static Strength PasswordStrength(string password)
        {
            //空字符串强度值为0
            if (password == "") return Strength.Invalid;
            //字符统计
            int iNum = 0, iLtt = 0, iSym = 0;
            foreach (char c in password)
            {
                if (c >= '0' && c <= '9') iNum++;
                else if (c >= 'a' && c <= 'z') iLtt++;
                else if (c >= 'A' && c <= 'Z') iLtt++;
                else iSym++;
            }
            if (iLtt == 0 && iSym == 0) return Strength.Weak; //纯数字密码
            if (iNum == 0 && iLtt == 0) return Strength.Weak; //纯符号密码
            if (iNum == 0 && iSym == 0) return Strength.Weak; //纯字母密码
            if (password.Length <= 7) return Strength.Weak; //长度不大于6的密码
            if (iLtt == 0) return Strength.Normal; //数字和符号构成的密码
            if (iSym == 0) return Strength.Normal; //数字和字母构成的密码
            if (iNum == 0) return Strength.Normal; //字母和符号构成的密码
            if (password.Length <= 10) return Strength.Normal; //长度不大于10的密码
            return Strength.Strong; //由数字、字母、符号构成的密码
        }
        static string mails = @"qq.com,163.com,outlook.com,gmail.com,yahoo.com,msn.com,hotmail.com,
                         aol.com,ask.com,live.com,qq.com,0355.net,163.com,163.net,263.net,3721.net,yeah.net,googlemail.com,
                        mail.com,hotmail.com,msn.com,yahoo.com,gmail.com,aim.com,aol.com,mail.com,walla.com,inbox.com,126.com,
                        163.com,sina.com,21cn.com,sohu.com,yahoo.com.cn,tom.com,qq.com,etang.com,eyou.com,56.com,x.cn,chinaren.com,
                         sogou.com,citiz.com,hongkong.com,ctimail.com,hknet.com,netvigator.com,mail.hk.com,swe.com.hk,ITCCOLP.COM.HK,
                        BIZNETVIGATOR.COM,SEED.NET.TW,TOPMARKEPLG.COM.TW,PCHOME.COM.TW,cyber.net.pk,omantel.net.om,webmail.co.za,
                        libero.it,xtra.co.nz,pacific.net.sg,emirates.net.ae,eim.ae,net.sy,scs-net.org,mail.sy,ttnet.net.tr,superonline.com,
                        yemen.net.ye,y.net.ye,cytanet.com.cy,aol.com,netzero.net,twcny.rr.com,comcast.net,warwick.net,comcast.net,
                        cs.com,verizon.net,bigpond.com,otenet.gr,cyber.net.pk,vsnl.com,wilnetonline.net,cal3.vsnl.net.in,rediffmail.com,
                        sancharnet.in,NDF.VSNL.NET.IN,DEL3.VSNL.NET.IN,xtra.co.nz,yandex.ru,t-online.de,NETVISION.NET.IL,BIGPOND.NET.AU,
                        MAIL.RU,ADSL.LOXINFO.COM,SCS-NET.ORG,EMIRATES.NET.AE,candel.co.jp,zamnet.zm,hn.vnn.vn,hcm.fpt.vn,hcm.vnn.vn,
                        amet.com.ar,infovia.com.ar,mt.net.mk,sotelgui.net.gn,prodigy.net.mx,citechco.net,xxx.meh.es,terra.es,mindspring.com,
                        excite.com,africaonline.co.zw,samara.co.zw,zol.co.zw,mweb.co.zw,aviso.ci,africaonline.co.ci,afnet.net,
                        mti.gov.na,namibnet.com,iway.na,be-local.com,infoclub.com.np,mos.com.np,ntc.net.np,kalianet.to,mail.ru,
                        dnet.net.id,sinos.net,westnet.com.au,gionline.com.au,cairns.net.au,mynet.com,mt.net.mk,indigo.ie,eircom.net,
                        sbcglobal.net,ntlworld.com,nesma.net.sa,mail.mn,tiscali.co.uk,caron.se,vodamail.co.za,eunet.at,spark.net.gr,
                        swiszcz.com,club-internet.fr,walla.com";
        static string tuhus = "tuhu.cn,tuhu.work,tuhutest.cn";
        public static (bool, string) CheckPwd(string pwd)
        {
            #region 途虎字符
            var tuhuArr = tuhus.Split(',');
            foreach (var item in tuhuArr)
            {
                var tuhu = item.Trim().ToLower();
                if (pwd.ToLower().Trim().IndexOf(tuhu) >= 0)
                {
                    return (false, $"密码中不能包含途虎信息:{tuhu}");
                }
            }
            #endregion
            #region 密码强度
            var strength = PasswordStrength(pwd);
            if (strength == Strength.Weak || strength == Strength.Invalid)
            {
                return (false, $"密码中需包含:字母,数字,符号,至少2种组合。");
            }
            #endregion
            #region 邮箱后缀
            var mailArr = mails.Split(',');
            foreach (var item in mailArr)
            {
                var mail = item.Trim().ToLower();
                if (pwd.ToLower().Trim().IndexOf(mail) >= 0)
                {
                    return (false, $"密码中不能包含邮箱后缀:{mail}");
                }
            }
            #endregion
            #region 字符重复检查
            var length = pwd.Length;
            var strs = new string[length];
            for (var i = 0; i < length; i++)
            {
                strs[i] = pwd.Substring(i, 1);
            }
            foreach (var item in strs)
            {
                var count = SubstringCount(pwd, item);
                if (count >= 4)
                {
                    return (false, $"密码中单字符出现不能大于3次,{item},{count}次");
                }
            }
            #endregion
            return (true, "");
        }
View Code

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

999.  此篇博客,将不断更新,总结工作中遇到的技术点。。。

 

posted @ 2012-07-10 10:27  张龙豪  阅读(8512)  评论(3编辑  收藏  举报