C#学习零散笔记

来源:互联网 发布:sql查询分析器建立 编辑:程序博客网 时间:2024/05/17 08:12

随着用C#做东西,零零散散记录过程的一些笔记,用的是asp.net MVC4,动态更新如下...

-- asp.net中根据选择的后台开发语言类型不同,视图的后缀名也不同,如 C#语言 视图后缀名为*.cshtml, VB语言对应的为 *.vbhtml;

-- C#中是区分大小写的,即大小写敏感;

-- 视图引擎为Razor时,部分表达书写方法:
@...; @(...); @Html.Raw(...); @{...;...; }; @的输入为双写 @@ 或 写&#64; 注释 @*...*@; @(Html.someMethod<xType>()); @RenderBody();  @RenderSection("xSectionName",[true|false]);

-- 如果某文件夹A下存在 _ViewStart.cshtml, 则其被最优先执行,然后再执行A下的其它 *.cshtml, 该*.cshtml文件同时也递归应用到文件夹A下的子文件;

-- 返回部分视图结果,尤其是ajax部分取数据时,最后在controller的action中用 return PartialView(); 返回数据;
public class HomeController:Controller{
public ActionResult getUserInfo(){
//...code...
return PartialView();
}
}

-- 视图引擎在本地项目的 Gloval.asax.cs 文件中注册或配置,但如更换其它视图引擎则在该文件的Application_start方法中配置,如:
protected void Application_start(){
ViewEngines.Engines.clear(); //Razor,webForm引擎默认是被注册的
ViewEngines.Engines.add(new MyViewEngine());
RegisterRoutes(RouteTable.Routes);
}

-- 创建自定义视图引擎时,需要实现 IViewEngine 接口和 IView 接口;

-- @Html.ActionLink("链接标题","链接URL"); 建立一个链接;

-- DB链接字符串放在 web.config 文件中,公约为:
...
<connectionStrings>
<add name="xDB" connectionString="data source=.\serverName;Integrated security=SSPI;initial catalog=DBName" 
ProviderName="System.Data.Sqlclient"/>
</connectionStrings>
...

--  在Controller中方法的前面加[HttpGet]表示该方法只处理http的 GET 请求,这也是默认的请求方式;

-- 在Controller中方法的前面加[HttpPost]表示该方法只处理http的 POST 请求;

-- 在Controller的Action中在方法的前面加 [OutputCache(Duration=0)] 表示在请求输出缓存时间为0,即不缓存;

-- Session变量操作
创建 Session["xName"] = "value";  清空值 Session["xName"] = null; 取值 string a = Session["xName"].ToString(); 存在判断 if(null == Session["xName"]){...}

-- Cookies操作:
是否存在名为 xName 的cookie: if(Request.Cookies["xName"] == null)
读取 cookie : string a = Request.Cookies["xName"].Value;
设置 cookie 值:Response.Cookies["xName"].Value = "zhangsan";
设置 cookie 过期时间:HttpCookie myCookie = new HttpCookie("xName"); myCookie.Expires = DateTime.Now.AddDays(1);
清空 cookie 就是设置cookie时间过过期即可,如 myCookie.Expires = DateTime.Now.AddDays(-2);

-- C#中的属性,如果操作的是属性名本身,则get, set的方法可省略方法体; 如:
public string Message {get; set;}

-- C#中的属性,如果操作的是非属性名本身,则get, set的方法提供方法体,其中进行具体的操作; 如:
private int _category = 0;
public int Category {
get { return _category; }
set { _category = value; }
}

-- Controller中如果方法前面加 [AllowAnonymous]表示该方法允许匿名访问,即任何人都可访问;

-- 前面有 [Authorize] 标识符的类表示需要授权操作;

-- @Html.DropDownList("id",string.Empty); 用于创建select下拉菜单;

-- @using(Html.BeginForm()){ ... } 用C#创建一个表单;

-- @Html.EditorFor(model => model.Title) 用于产生一个input type=text的元素;

--  ~ 在Asp.net中是web应用程序根目录的运算符,只能在服务器端代码使用;

-- 缓存控制,清空缓存
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.addSeconds(-1);
Response.Expire = 0;
Response.cacheControl= "no-cache";

-- @Styles.Render("~/content/css") 可在页面中用来加载指定绑定名称的CSS文件,可指定多个绑定名称,用逗号隔开, 如:
@Style.Render("~/Content/css1","~/Content/css2"[,...]); 
绑定工作需在项目的App_Start文件夹下的 BundleConfig.cs 完成。

-- @Scripts.Render("~/content/script") 可在页面中用来加载指定绑定名称的Script文件,可指定多个绑定名称,用逗号隔开, 如:
@Scripts.Render("~/xpath/script1","~/xpath/script2"[,...]); 
绑定工作需在项目的App_Start文件夹下的 BundleConfig.cs 完成。

-- jQuery将参数以JSON格式发送,结果以JSON格式接受:
$.ajax({
url:'xpath/xURL',
type:'GET', //POST
dataType:'JSON',  //结果返回数据格式JSON
data:{'Name':'zhangsan','age':28},
contentType:'application/json; charset=utf-8', //指定内容类型为JSON格式,编码为utf-8
async:true,
timeout:3000,
error:function(){....},
success:function(){...}
});

-- [Serializable] 用在(一般为model)类前面表示该(model)类可进行序列化;

--  C#中将对象以JSON格式返回
return Json(objXXX,JsonRequestBehavior.AllowGet); //objXXX为某对象
方法的返回值类型为 JsonResult 或 ActionResult,同时前端以GET方式提交http请求。

-- 在运行时动态获取web应用程序的根路径: 
string rootSitePath = HttpRuntime.AppDomainAppPath;

-- return RedirectToAction("actionName", "ControllerName");
是在当前action中重定向到名称为ControllerName的控制器中名为actionName的action中;
[注意:ControllerName是路由器中设定的名称规则,即控制器文件名称不含Controller.cs部分];
如果是转到本控制器内部的另一个action,则第二个参数ControllerName可省略;
例如:
return RedirectToAction("Index", "Home"); 即在当前的action中重定向到名为Home[文件名为HomeController.cs]的控制器中名为Index的action中;
return RedirectToAction("Logout"); 即在当前的action中重定向到本控制器内部名为Logout的action中;

-- ModelState.AddModelError("errorKey","errorValue");
该语句向字典类型的ModelState中添加一条错误信息,该错误信息在控制器对应的视图中可用
@Html.ValidationMessage(errorKey)  或 @Html.ValidationSummary() 来显示[Razor引擎]

-- @Url.Content("~/Resources/")
这个是建立基于根目录下开始的Resources/路径

-- @Url.Content("/Home/Logout")
这个是建立基于当前(上下文)控制器Home下的Logout的action连接

-- _ViewStart.cshtml 是asp.net mvc4.0 默认的视图页,任何返回视图都以之开始执行,同时跟@renderBody()部分视图合并共同组合成完整的视图页。

-- 当哪个页面比如登录页,不需要执行或不需要_ViewStart.cshtml返回的视图时,在该页顶部加入如下代码即可:
@{
Layout = "~/Views/Shared/_NoRender.cshtml"; @* 也即将Layout的值指向没有头尾的的页 *@
}

同时在上面指定的路径[如~/Views/Shared/]下建立_NoRender.cshtml文件,其内容为 @RenderBody()即可。


-- 在Razor引擎的视图中引用某个命名空间的对象如下
@using com.projectName.Entity;


-- 在Razor引擎的视图中使用session对象
@{
UserSession userSession = @Session["UserSession"] as UserSession;   //UserSession实现定义好
}


-- 在Razor引擎的视图中判断字符串的长度
@{
string usertitle = "0123456789";
string showTemp = string.Empty;
if(usertitle.Length > 10){
showTemp = usertitle.Substring(0,10) + "...";
}
}

-- 在Razor引擎的视图中判断字符串是否为空或null值
@{
string myword = "...";
if(string.IsNullOrEmpty(myword)){
...
}else{
...
}
}

-- C# 中 cookie设置
// 将当前语言名称设置到cookie中
HttpCookie _cookie = new HttpCookie("cookieName", "cookieValue");
_cookie.Expires = DateTime.Now.AddYears(1); //set expires time
controller.HttpContext.Response.SetCookie(_cookie);

-- C# 中 cookie读取
HttpCookie cookie = controller.HttpContext.Request.Cookies["cookieName"]; //get cookie object
string ckValue = cookie.value; //get cookie value

-- C# 中设置和清空session变量
Session.Clear(); //清空
Session["varName"] = "varValue"; //设置值
Session["varName"] = null; //置空

-- C# 中的email发送
过程是先建立MailMessage对象[设置各个参数],然后通过SmtpClient对象[由设置各个参数]把MailMessage对象发送出去;

//部分关键程序集using System.Net.Mail;string emilSender = "Lisi";List<string> emailList = new List<string>();string mailSubject = "mailSubject";StringBuilder mailBody = new StringBuilder();emailList.Add("abc@163.com");emailList.Add("zhangsan@163.com");mailBody.Append("<div>用户Zhangsan:</div>");mailBody.Append("<div>Email内容:abcd text...</div>");MailMessage mailMessage = MyEMailSender.InitMail(emilSender, emailList, mailSubject, mailBody.ToString(), true);if (MyEMailSender.Sendmail(mailMessage)){return Json(new { isSuccess = true, message = "邮件发送成功!" }, JsonRequestBehavior.AllowGet);}else{return Json(new { isSuccess = false, message = "发送邮件失败!" }, JsonRequestBehavior.AllowGet);}

//支持类MyEMailSender//部分关键程序集using System;using System.Text;using System.Net.Mail;using System.Configuration;namespace com.myApp.Email{    public static class MyEMailSender    {        private static SmtpClient smtpClient = new SmtpClient();        // 发邮件SMTP服务器账户配置        private static string smtp_host = ConfigurationManager.AppSettings["smtpServer"]; //email server IP        private static int smtp_port = Convert.ToInt16(ConfigurationManager.AppSettings["smtpPort"]); //email server port        private static string smtp_user_name = ConfigurationManager.AppSettings["smtpUser"]; //email user name        private static string smtp_user_pwd = ConfigurationManager.AppSettings["smtpPassword"]; //email password        /// <summary>        /// 发送邮件        /// </summary>        /// <returns></returns>        public static bool Sendmail(MailMessage Mail)        {            smtpClient.Host = smtp_host;            smtpClient.Port = smtp_port;            smtpClient.Credentials = new System.Net.NetworkCredential(smtp_user_name, smtp_user_pwd); //邮箱的用户名和密码            smtpClient.EnableSsl = false; //ssl加密            try            {                smtpClient.Send(Mail);                return true;            }            catch (System.Net.Mail.SmtpException ex)            {                return false;            }        }        /// <summary>        /// 新建邮件对象        /// </summary>        /// <param name="FromAddress"></param>        /// <param name="ToAddressList"></param>        /// <param name="MailSubject"></param>        /// <param name="MailBody"></param>        /// <param name="IsBodyHtml"></param>        /// <returns></returns>        public static MailMessage InitMail(string FromAddress, List<string> ToAddressList, string MailSubject, string MailBody, bool IsBodyHtml = true)        {            MailMessage mail = new MailMessage();                        mail.From = new MailAddress(FromAddress); //发件人                        foreach (string toAddr in ToAddressList) //收件人            {                mail.To.Add(new MailAddress(toAddr));            }                        mail.Subject = MailSubject; //邮件主题                        mail.Body = MailBody; //邮件内容                       mail.SubjectEncoding = System.Text.Encoding.UTF8;  //邮件主题和正文编码格式            mail.BodyEncoding = System.Text.Encoding.UTF8;                        mail.IsBodyHtml = IsBodyHtml; //正文是否Html编码                        mail.Priority = MailPriority.High; //优先级            return mail;        }        /// <summary>        /// 新建邮件对象,含发送,抄送,密送邮件        /// </summary>        /// <param name="FromAddress"></param>        /// <param name="ToAddressList"></param>        /// <param name="MailSubject"></param>        /// <param name="MailBody"></param>        /// <param name="BccList"></param>        /// <param name="CcList"></param>        /// <param name="IsBodyHtml"></param>        /// <returns></returns>        public static MailMessage InitMail(string FromAddress, List<string> ToAddressList, string MailSubject, string MailBody,            List<string> BccList, List<string> CcList, bool IsBodyHtml = true)        {            MailMessage mail = new MailMessage();                        mail.From = new MailAddress(FromAddress); //发件人                        foreach (string mailAddr in ToAddressList) //收件人            {                mail.To.Add(new MailAddress(mailAddr));            }                        mail.Subject = MailSubject; //邮件主题                        mail.Body = MailBody; //邮件内容                        mail.SubjectEncoding = System.Text.Encoding.UTF8; //邮件主题和正文编码格式            mail.BodyEncoding = System.Text.Encoding.UTF8;                        mail.IsBodyHtml = IsBodyHtml; //正文是否Html编码                        mail.Priority = MailPriority.High; //优先级                       foreach (string mailAddr in BccList)  //密件抄送收件人            {                mail.Bcc.Add(new MailAddress(mailAddr));            }                        foreach (string mailAddr in CcList) //抄送收件人            {                mail.CC.Add(new MailAddress(mailAddr));            }                        //mail.Attachments.Add(new Attachment("d:\\tes.txt"));  //添加附件            return mail;        }    }}

-- 获取当前系统Url路径[asp.net 4.0 C#]
/// <summary>
/// 获取当前系统Url路径
/// </summary>
/// <returns></returns>
[AccessPrivilege(Type = AccessPrivilegeType.ANONYMOUS)]
public ActionResult GetWebPath()
{
      string result = String.Empty;
      result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
      if (string.IsNullOrEmpty(result))
      {
           result = "127.0.0.1:" + System.Web.HttpContext.Current.Request.Url.Authority; ;
      }
      result = "http://" + result;
      return Json(result);
}

-- C# 对应方法的测试用例

        /// <summary>        ///A test for CourseMore, 自动生成的完整例子        ///</summary>        [TestMethod()]        public void CourseMoreTest()        {    //ActionResult结果的判断            HomeController target = new HomeController(); // TODO: Initialize to an appropriate value            ActionResult expected = null; // TODO: Initialize to an appropriate value            ActionResult actual;            actual = target.CourseMore();            Assert.AreEqual(expected, actual);            Assert.Inconclusive("Verify the correctness of this test method.");         }        /// <summary>        ///A test for CourseCompetitiveList,手动修改的例子        ///</summary>        [TestMethod()]        public void CourseCompetitiveListTest()        {                //JSON结果的判断             JsonResult actual = target.CourseCompetitiveList() as JsonResult;            Assert.IsNotNull(actual);           }

-- Razor引擎的语法 [asp.net 4.0 MVC]

1, 单行代码 @xxxx 

example1:Razor style: <span>@model.Message</span>web forms style: <span> <%: model.Message %></span>  //仅作比较example2:Razor style: <span>ISBN@(isbn)</span>web forms style: <span>ISBN<%: isbn %></span>
2,代码块 @{xxxx}
//example1: Razor style: @{int x =123;string y = "ok.";}webForms style: <%int x =123;string y = "ok.";%>

//example2: Razor style: @foreach ( var item in items ){<span>Item @item.name. </span>}//webForms style:<% foreach ( var item in items ){ %><span>Item <%: item.name %>. </span><% } %>//example3: Razor style: @if(showMessage){<text>This is plain text.</text>}或者@if(showMessage){@:This is plain text.}//webForms style: <% if (showMessage) { %>This is plain text.<% } %>
-- Razor 语法的注释
@* 
...code block...
*@

-- webForm 语法注释

<%--
...code block...
--%>

-- 返回的视图有不同情况
1,没有参数的情况
public ActionResult Index(){
ViewBag.Message = "welcome to ASP.NET MVC 4";
return View();
}
//无参数时默认返回的视图为views文件夹里跟控制器同名的文件夹下的Index.cshtml,即Action方法名跟视图同名;

2,指定参数名称,返回同一文件夹下跟action方法不同名的视图
public ActionResult Index(){
ViewBag.Message = "welcome to ASP.NET MVC 4";
return View("welcome");
}
//有参数时默认返回的视图为views文件夹里跟控制器同名的文件夹下的welcome.cshtml,即Action方法名跟视图不同名,但视图在同一文件夹中;

3,指定参数名称,返回不同文件夹下跟action方法不同名的视图
public ActionResult Index(){
ViewBag.Message = "welcome to ASP.NET MVC 4";
return View("~/Views/Example/Index2.cshtml");
}
//有参数时默认返回的视图为views文件夹里Example文件夹下的Index2.cshtml,即Action方法名跟视图不同名,视图所在文件夹也不同;

--asp.net MVC 4.0 Razor [C#] 验证码问题

(1)生成验证码类

using System;using System.IO;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using System.Web.Caching;using System.Drawing;using System.Drawing.Imaging;namespace com.proNameSpace.Utils{    public static class ValidateCodeUtility    {        /// <summary>        /// 生成验证码图片        /// </summary>        /// <param name="validateCode"></param>        /// <returns></returns>        public static Bitmap CreateImage(string validateCode)        {            int iwidth = (int)(validateCode.Length * 14);            Bitmap image = new Bitmap(iwidth, 23);            Graphics graphics = Graphics.FromImage(image);            graphics.Clear(Color.White);            //定义颜色            Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };            //定义字体             string[] fonts = { "Verdana", "Georgia", "Comic Sans MS", "Tahoma", "宋体" };            Random rand = new Random();            //随机输出噪点            for (int i = 0; i < 50; i++)            {                int x = rand.Next(image.Width);                int y = rand.Next(image.Height);                graphics.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);            }            //输出不同字体和颜色的验证码字符            for (int i = 0; i < validateCode.Length; i++)            {                int cindex = rand.Next(7);                int findex = rand.Next(5);                int fsize = rand.Next(10,14);                Font font = new Font(fonts[findex], fsize, FontStyle.Bold);                Brush brush = new SolidBrush(colors[cindex]);                int j = 4;                if ((i + 1) % 2 == 0)                {                    j = 2;                }                graphics.DrawString(validateCode.Substring(i, 1), font, brush, 3 + (i * 12), j);            }            //画一个边框            graphics.DrawRectangle(new Pen(Color.Gray, 0), 0, 0, image.Width - 1, image.Height - 1);            graphics.Dispose();            //MemoryStream memoryStream = new MemoryStream();            //image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);            //image.Dispose();                        //输出到浏览器            //HttpContext.Current.Response.ClearContent();            //HttpContext.Current.Response.ContentType = "image/Jpeg";            //HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray());            return image;        }        /// <summary>        /// 生成验证码        /// </summary>        /// <param name="vCodeLength"></param>        /// <returns></returns>        public static string CreateValidateCode(int vCodeLength)        {            string Vchar = "1,2,3,4,5,6,7,8,9,Q,W,E,R,T,Y,U,I,P,A,S,D,F,G,H,J,K,L,Z,X,C,V,B,N,M,q,w,e,r,t,y,u,i,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";// 0,o,O 去掉            string[] VcArray = Vchar.Split(',');            //验证码内容            string ValidateCode = "";            int temp = -1;            Random rand = new Random();            for (int i = 1; i < vCodeLength + 1; i++)            {                if (temp != -1)                {                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));                }                int t = rand.Next(VcArray.Length);                if (temp != -1 && temp == t)                {                    return CreateValidateCode(vCodeLength);                }                temp = t;                ValidateCode += VcArray[t];            }            return ValidateCode;        }    }}

(2)对应控制器

//checkCodeController.csnamespace com.proNameSpace.Controller{    public class VerificationCodeController     {        public ActionResult index()        {            //ViewBag.inputMessage = "请输入";            return View();        }        /// <summary>        /// 默认获取验证码图片        /// </summary>        /// <returns></returns>        [AccessPrivilege(Type = AccessPrivilegeType.ANONYMOUS)]        public ActionResult GetCodeImg()        {            string verificationCode = ValidateCodeUtility.CreateValidateCode(4);            Bitmap verificationImage = ValidateCodeUtility.CreateImage(verificationCode);            MemoryStream memoryStream = new MemoryStream();            verificationImage.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);            verificationImage.Dispose();            Session["chkCode"] = verificationCode;            //输出到浏览器            HttpContext.Response.ClearContent();            HttpContext.Response.ContentType = "image/Jpeg";            HttpContext.Response.BinaryWrite(memoryStream.ToArray());            return null;        }        /// <summary>        /// 验证验证码        /// </summary>        /// <returns></returns>        [AccessPrivilege(Type = AccessPrivilegeType.ANONYMOUS)]        public ActionResult Validate()        {            string inputCode = Request.Params["inputCode"];            bool eq = false;            if (!string.IsNullOrEmpty(inputCode))            {                string serverCode = Session["chkCode"] as string;                if (string.IsNullOrEmpty(serverCode))                {                    return Json(new { isSuccess = false, message = "验证码已过期,请重新获取!" }, JsonRequestBehavior.AllowGet);                }                eq = inputCode.ToLower().Equals(serverCode.ToLower());            }            if (eq)            {                return Json(new { isSuccess = true, message = "验证成功" }, JsonRequestBehavior.AllowGet);            }            else            {                return Json(new { isSuccess = false, message = "验证码不正确,请重新输入!" }, JsonRequestBehavior.AllowGet);            }        }    }}

--asp.net mvc4.0 [Razor ,C# ] ,文件上传

(1)相关方法,

        /// <summary>        /// 上传文件        /// </summary>        /// <param name="file">文件</param>        /// <param name="type">xFile</param>        /// <returns></returns>        private string UploadFile(HttpPostedFileBase file)        {            UserSession userSession = Session["UserSession"] as UserSession;            //Logger.Debug(file.FileName + "... start to upload");            try            {                int fileLength = file.ContentLength;                string iniFileName = file.FileName;                string filePath = "d:\uploadFile\";                //时间戳 作为存储文件的名字                string timeFileName = DateUtils.GetTimeStamp() + iniFileName.Substring(iniFileName.LastIndexOf("."));                //insert into db                myFile mf = new myFile();                mf.filePath = timeFileName; // filePath + timeFileName;                mf.cName = iniFileName;                mf.size = (fileLength/1024);                DBxxxDAOService.Insert(mf);                saveFile(filePath, timeFileName, file);                return mf.Refid;                            }            catch (Exception ex) {                Logger.Error("upload file error" + file.FileName, ex);            }            Logger.Debug(file.FileName + "...  to upload success !");            return "";             }        /// <summary>        /// 保存文件        /// </summary>        /// <param name="filePath">保存的路径</param>        /// <param name="timeFileName">文件名</param>        /// <param name="file">文件</param>        private void saveFile(string filePath, string timeFileName, HttpPostedFileBase file)        {            if (file == null)            {                return;            }            FileStream writer = null;            Stream reader = null;            try            {                string fileName = file.FileName;                string dir = HttpRuntime.AppDomainAppPath + filePath;                //write to local file                DirectoryInfo directoryInfo = new DirectoryInfo(dir);                directoryInfo.Create();//自行判断一下是否存在                writer = new FileStream(dir + timeFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);                reader = file.InputStream;                byte[] buffer = new byte[10 * 1024];                int c = 0;                while ((c = reader.Read(buffer, 0, buffer.Length)) > 0)                {                    writer.Write(buffer, 0, c);                    writer.Flush();                }            }            catch (Exception ex)            {                Logger.Error("store file error" + file.FileName, ex);            }            finally {                reader.Close();                writer.Close();                GC.Collect();            }                  }

(2)相关控制器

//对应处理controller.cs        [HttpPost]        [ValidateInput(false)]        public ActionResult FileUpload(HttpPostedFileBase file)        {                      Logger.Debug(file.FileName + "... start to upload = " );            string iniFileName = UploadFile(file);            Logger.Debug(file.FileName + "... end to upload = " );            return Json(new { success = iniFileName }, JsonRequestBehavior.AllowGet);                    }