1.JS獲取iframe下面的內容
document.getElementById('IFRAME1').contentDocument;javascript
2.dialog 彈出層,定位:postion:'bottom',['right','bottom'],['left','bottom'].html
3.IIS上部署WCF; 調用wcf或webapii必定要作安全認證。前端
cd d:java
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319node
aspnet_regiis.exe -imysql
4.項目之間如何調用WCF,怎麼調試? 好比A項目,調用B項目的wcf服務。
a.先把B項目的wcf部署到IIS上,具體怎麼部署? 看上面的3
b.在A項目引用B項目部署在IIS上的地址。
c.在B項目中,把IIS的wcf附加到進程,打斷點。
d.運行A項目,打斷點調試。jquery
寫wcf執行的時候,能夠做爲啓動想,選擇特定的頁爲wcf文件,就能夠直接輸入參數,點擊執行,返回執行結果。nginx
5.
string a="1";
if (!a.IsNullOrEmpty())
{
//這種寫法第一次看到,其實差很少。
}
if(!string.IsNullOrEmpty(a))
{
}web
6.添加wcf可能報錯,須要按以下圖設置:ajax
7.6.mysql 中能夠用,Show Create Table '表名',而後按F8,把建立腳步的語句拷貝出來。
8.用mysql客戶端工具SQLyog,導入腳步,Tools -> Execute sql script.
9.redis 緩存,須要安裝一個軟件,通常狀況下不須要作數據的持久化。
10.WCF 修改類具體實現的代碼,引用WCF不須要更新,前提是方法名和參數名稱沒有改。
12.webAPI POSt處理SON數組:(後臺是繼承的屬性,必定要用JSON.stringify,否則解析不了),並且前端只能穿一個參數,否則就會報500錯誤。get請求就沒這個限制。
前端代碼:
var mfItemStr = JSON.stringify({ mfItemStr: [{ "CreateId":1, "CreateName": "test1"},{ "CreateId":2, "CreateName": "test2"},{ "CreateId":3, "CreateName": "test3"}]}); $.ajax({ url: "/Test/Update", type: "post", dataType: "json", contentType: "application/json", data: mfItemStr, success: function (data) { console.log(data); alert("Ok"); } })
CSharp代碼:
[HttpPost] public HttpResponseMessage Update(JObject recordsSr) { var errMsg = new M_APIError(); try { if(recordsSr == null) { errMsg.ErrorCode = -1; errMsg.Message = "recordsSr不能爲空"; return Json.toJson(errMsg); } var str = recordsSr.ToObject<M_MFItem>(); if (str == null || str.mfItemStr == null || str.mfItemStr.Count <= 0) { errMsg.ErrorCode = -1; errMsg.Message = "已選擇的會員特性不能爲空"; return Json.toJson(errMsg); } //已選擇的會員特性 var records = str.mfItemStr; int patientId = records.Select(t=>t.PatientID).First(); if (patientId <= 0) { errMsg.ErrorCode = -1; errMsg.Message = "會員Id不能爲空"; return Json.toJson(errMsg); } //獲取當前會員的特性記錄 var exists = new List<M_MemberFeaturesRecord>(); AspectF.Define.LogAPI(false).Do(() => exists = bll.GetMemberFeaturesRecordByPatientID(patientId)); if (exists == null && exists.Count <= 0) { errMsg.ErrorCode = -4; errMsg.Message = "當前會員的特性記錄爲空"; } else { //待新增記錄(獲取選中的記錄不在當前會員的特性記錄中的數據) var adds = records.Where(c => !exists.Any(e => e.MFItemID == c.MFItemID)).ToList(); //給當前的特性記錄加上特性名稱,建立人和建立名稱 exists.ForEach(t => { var b = records.Where(a => a.MFItemID == t.MFItemID).FirstOrDefault(); if (b != null) { if (!string.IsNullOrWhiteSpace(b.MFItemName)) { t.MFItemName = b.MFItemName; } if (b.CreateID > 0) { t.CreateID = b.CreateID; } if (!string.IsNullOrWhiteSpace(b.CreateName)) { t.CreateName = b.CreateName; } } }); //待刪除記錄 var deletes = exists.Where(c => !records.Any(e => e.MFItemID == c.MFItemID)).ToList(); //新增 var addResult = 0; if (adds != null && adds.Count > 0) { AspectF.Define.LogAPI(false).Do(() => addResult = bll.BatchInsertMemberFeaturesRecord(adds)); if (addResult > 0) { AddmFRecordLog(patientId, adds, 1); } } //刪除 List<int> delList = new List<int>(); bool delResult = false; if (deletes != null && deletes.Count > 0) { string recordIdStr = string.Join(",", deletes); if (!string.IsNullOrWhiteSpace(recordIdStr)) { AspectF.Define.LogAPI(false).Do(() => delResult = bll.BatchDeleteMemberFeaturesRecord(recordIdStr)); if (delResult) { AddmFRecordLog(patientId, deletes, 2); } } } if (addResult > 0 && delResult) { errMsg.ErrorCode = 0; errMsg.Message = "成功"; errMsg.ReturnData = addResult; } else { errMsg.ErrorCode = -5; errMsg.Message = "失敗"; } } } catch (Exception ex) { errMsg.ErrorCode = 500; errMsg.Message = ex.Message; } return Json.toJson(errMsg); }
13.ADO.NET 執行批量Sql server 的SQL,而mysql不支持,只能把批量的MySQL寫在存儲過程裏面,而後調用。
sql server:
declare @result int; set @result=-1092 if exists(select top 1 1 from [Order] a where A.OrderCurrentStatus=1 and A.Code=@Code) begin update [Order] set OrderCurrentStatus=2,OrderType=0 where Code=@Code; --插入日誌 INSERT INTO [OrderTrans] ([OrderId],[TransType],[OrderType],[OrderCode], [IsResult],[Creater],[CreateDate],[Remark],[BusCode]) SELECT 0,3,0,@code,1,@Creater,GETDATE(), '郵費訂單審覈',@code set @result=@@error; end else begin set @result=1091 end select @result;
14.h5增長類jquery
document.querySelector(".")
15.優化mysql的SQL,能夠用explain,
EXPLAIN SELECT * FROM `accounts`
16.調試Wcf 和webAPI
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\WcfTestClient.exe 調試調用WCF
調試webapi:
1).能夠在chrome 添加插件Postman-REST-Client_v0.8.1
2).下載PC版 Postman-win64-5.0.0-Setup.exe https://download4os.com/postman-4-10-3-60258/
3).firefox 添加插件 httprequester
4).jmeter 參考地址: http://jingyan.baidu.com/article/14bd256e7e707cbb6d2612cf.html?qq-pf-to=pcqq.c2c
5).Fiddler 監控手機app程序和模擬post請求 參考以下:
http://www.javashuo.com/article/p-yihwzsrj-gu.html
https://blog.csdn.net/qq_28766327/article/details/52457926
6). 接口的生成工具
17.MySQL數據庫表字段生成對應的實體:
每一個表生成實體類型,若是表字段不少的話,一個一個寫很浪費時間,能夠用正則(或動軟代碼生成器)來處理,正則步驟以下:
1.從MySQL中查詢的信息中拿到createTable數據;SHOW CREATE TABLE sys_test 2.經過如下正則來替換 `(\S+)`\s+(\S+).*'(.*)', \t\t\/\/\/<summary>\n\t\t\/\/\/\t\3\n\t\t\/\/\/</summary>\n\t\t\[DataMember\]\n\t\tpublic \2 \1 \{ get; set;\}\n 經過正則以後,能夠將table信息統一變成這種格式: /// <summary> /// 是否接受短信:0-否,1-是 /// </summary> [DataMember] public sbyte IsAcceptSMS { get; set; } 3.整理一些類型 ,int\(\d+\)-->int int\(\d+\) nvarchar\(\d+\)/text/char/varchar\(\d+\)--->string tinyint --->sbyte date/datetime --->DateTime time ---> TimeSpan bigint-->long smallint ->short int(11) unsigned -> uint double -> double bit -> bool decimal -> decimal blob -> byte[] float-> float
(\S+) sInfo\.\1 = info\.\1; info\.\1 = sInfo\.\1; \s+
Creator,
CreateTime,
TestLen,
OrderTest,
PlayAmount
先把,逗號替換掉,而後用(\S+)替換成sInfo\.\1 = info\.\1;
注意:可空的上面的正則處理不了。處理方法: 非空類型沒有勾選(或爲DEFAULT NULL),C#定義須要可空類型。好比 tinyint 對 sbyte? 也能夠經過Show full fields from TableA 看的Null列是否爲YES,爲YES就加?(字符串類型的不用加)
去掉換行:\s+ 替換爲空格
18.uwp(Windows 10開發)
以前用到http://stackoverflow.com/questions/17049677/how-do-i-print-webview-content-in-a-windows-store-app 這個方法仍是不行,由於我要打印曲線圖。
a.打印頁面,分頁的方法:https://msdn.microsoft.com/zh-cn/library/windows/apps/xaml/hh465204
代碼:https://code.msdn.microsoft.com/windowsapps/Print-Sample-c544cce6
b.打印webview嵌入html頁面全部內容的方法(啓動程序,打開谷歌瀏覽器,採用window.print打印):
CSharp代碼:
/// <summary>
/// 打印功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void ButtonPrint_Click(object sender, RoutedEventArgs e)
{
try { await SaveFileAsync(@"Report\jscript\data.js", "var jsonData = " + jsonData); await LaunchFileAsync(@"Report\html\ReportDetail.html"); } catch (Exception ex) { await new MessageDialog("打印失敗").ShowAsync(); } } /// <summary> /// 保存文件 /// </summary> /// <param name="filePath">相對於localfilepath</param> /// <param name="contents">內容</param> /// <param name="options">選項m</param> /// <returns></returns> public static async Task SaveFileAsync(string filePath,string contents,CreationCollisionOption options= CreationCollisionOption.ReplaceExisting) { try { var localFolder = ApplicationData.Current.LocalFolder; var file = await localFolder.CreateFileAsync(filePath, options); await FileIO.AppendTextAsync(file, contents); } catch (Exception ex) { await FileLoger.WriteLog("savefile Error",ex,filePath); } } /// <summary> /// launch file /// </summary> /// <param name="filePath">相對於localfilepath</param> /// <returns></returns> public static async Task LaunchFileAsync(string filePath) { var localFolder = ApplicationData.Current.LocalFolder; var file = await localFolder.CreateFileAsync(filePath, CreationCollisionOption.OpenIfExists); await Windows.System.Launcher.LaunchFileAsync(file); }
JS:方法
function ExecutePrint() {
setTimeout(function () {
if ($.browser.mozilla) { document.getElementById("WebBrowserObj").execWB(7, 1); } else { window.print(); } }, 3000); } $(function () { LoadData(jsonData); ExecutePrint(); });
19. (1). mysql 能夠利用GROUP_CONCAT把個值拼接在一塊兒,默認以分號相隔。也能夠指定其分隔符號。
GROUP_CONCAT(DISTINCT Guardian SEPARATOR ';') Guardian 以分號顯示「a;b;c」
(2).mysql類型爲time類型的時候,對應的C#定義爲TimeSpan,賦值以下:
DateTime dt = DateTime.Parse("2016-6-29 19:20:30"); TimeSpan times = dt.TimeOfDay;//注意這裏賦值 或 var tt = 490; var ss = TimeSpan.FromMinutes(tt);
(3).C# 執行mysql腳本能夠這樣一塊兒寫:
INSERT INTO sys_log(`PatientID`,`MFItemID`,`MFItemName`,`CreateID`,`CreateName`,
`UpdateID`,`CreateTime`,`UpdateTime`,`DoctorID`,`DoctorName`,`DrID`,`DrName`,`OperationType`,`Remark`,`CARecordID`)
SELECT @NewPatientID,`MFItemID`,`MFItemName`,`CreateID`,`CreateName`,`UpdateID`,`CreateTime`,`UpdateTime`,`DoctorID`,`DoctorName`,`DrID`,`DrName`,`OperationType`,`Remark`,@RecordId FROM sys_log WHERE `RecordLogID`=@RecordLogID;
(4).用CONCAT拼接字符串 LIKE CONCAT('%',@Title,'%')
(5).mysql獲取自增的列的方法:區別能夠參考:MYSQL LAST_INSERT_ID() 自增列詳解 和 MySQL獲取自增主鍵ID的四種方法
SELECT @@IDENTITY;
SELECT LAST_INSERT_ID();
(6).寫方法,儘可能使用參數,而不用直接傳值,防止SQL注入,參數化安全性高些。 好比select * from A where id in(1,2,3),能夠select * from A where 1= 1 and (id=1 or id =2 or id=3) 。具體以下(注意紅色標註的代碼):
public List<M_MTest> GetTetItemIds(int[] itemId)
{
if (itemId == null || itemId.Length < 1) return null; const string sqlText = @"select * from Test where MFItemID=@ItemId"; var where = new StringBuilder(30, 30 * itemId.Length); var param = new List<MySqlParameter>(); where.Append(" AND "); if (itemId.Length == 1) { where.Append("MFItemID=@ItemId "); param.Add(new MySqlParameter("@ItemId", itemId[0])); } else { where.Append("( "); for (var i = 0; i < itemId.Length; i++) { where.Append("MFItemID=@ItemId"); where.Append(i); if (i < itemId.Length - 1) { where.Append(" OR "); } param.Add(new MySqlParameter("@ItemId" + i, itemId[i])); } where.Append(" )"); } var result = MySqlHelper.ExecuteDataTable( MySqlHelper.ConnectionStringRemp, CommandType.Text, sqlText + @where, param.ToArray() ); return result.ConvertToList<M_MTest>(); }
int[] orgId;
const string sql =
"SELECT `MFTypeID`,`MFTypeName`,`MFTypeParentID`,`MFTypePath`,`MFTypeLevel`,`MFTypeOrder`,`Description`,`IsSystem`,`IsPushApp`,`IsDeleted`,`OrgID`,`CreateID`,`CreateTime`,`UpdateID`,`UpdateTime`,IFNULL((SELECT MFTypeID FROM sys_memberfeaturestype WHERE MFTypeParentID = s.MFTypeID limit 0,1),0) IsHasSub FROM sys_memberfeaturestype s where MFTypeParentID != -1 AND IsDeleted = 0"; var where = new StringBuilder(); var param = new List<MySqlParameter>(); if (orgId != null && orgId.Any()) { if (orgId.Length == 1) { where.Append(" AND (OrgID = @OrgId OR OrgID = 0)"); param.Add(new MySqlParameter("@OrgId", orgId[0])); } else { where.Append(" AND ( OrgID = 0"); for (var i = 0; i < orgId.Length; i++) { where.Append(" OR"); where.Append(" OrgID = @OrgId"); where.Append(i); param.Add(new MySqlParameter("@OrgId" + i, orgId[i])); } where.Append(" )"); } }
對比:
if (orgIds != null && orgIds.Count > 0) { baseSql.AppendFormat(" and !d.IsDeleted and d.OrganizationID in ("); foreach (var orgId in orgIds) { baseSql.AppendFormat("{0},", orgId); } baseSql.Remove(baseSql.Length - 1, 1); baseSql.AppendFormat(")"); }
(7).mysql 批量新增:insert into Test(Id,name) value(1,"t"),(2,"test");
/// <summary>
///批量新增
/// </summary>
/// <param name="listTest">集合</param>
/// <returns></returns>
public int BatchInsertTEst(List<M_Test> listTest)
{
if (listTest == null || listTest.Count <= 0) { LogHelper.AddErrorLog("沒有記錄", "", ""); return -1; } var strSql = new StringBuilder( "INSERT INTO sys_Test(`PatientID`,`MFItemID`,`CreateID`,`CreateTime`) "); var mysqlParam = new List<MySqlParameter>(); for (var i = 0; i < listTest.Count; i++) { var item = listTest[i]; if (i == 0) { strSql.AppendFormat(" VALUES(@PatientID{0},@MFItemID{0},@CreateID{0},@CreateTime{0})", i); } if (i > 0) { strSql.AppendFormat(",(@PatientID{0},@MFItemID{0},@CreateID{0},@CreateTime{0})", i); } mysqlParam.Add(new MySqlParameter(string.Format("@PatientID{0}", i), item.PatientID)); mysqlParam.Add(new MySqlParameter(string.Format("@MFItemID{0}", i), item.MFItemID)); mysqlParam.Add(new MySqlParameter(string.Format("@CreateID{0}", i), item.CreateID)); mysqlParam.Add(new MySqlParameter(string.Format("@CreateTime{0}", i), item.CreateTime)); } try { var num = MySqlHelper.ExecuteNonQuery(MySqlHelper.connectionStringRemp, CommandType.Text, strSql.ToString(), mysqlParam.ToArray()); return num; } catch (Exception ex) { LogHelper.AddErrorLog("批量新增失敗", ex.ToString(), ""); return 0; } }
注意:這裏沒考慮大數據的問題,如一次性插入10萬數據,就不能這樣處理。 能夠經過多線程的方式,每次給DB中添加1000條,另外的話還須要加上事務。能夠參考下面的代碼:
//設置CPU給當前應用程序分配的最小線程數
System.Threading.ThreadPool.SetMinThreads(100, 100);
var list = new List<Task>(); var count = 10000*10000;//1千萬條 var num = 1000;//每次循環條數 for (int j = 0; j < count; j++) { //每次1000條數據 for (int i = 0; i < num; i++) { var result = Task.Run(() => { //插入DB }); list.Add(result); } //等待1000個線程跑完 Task.WaitAll(list.ToArray()); count = count - num; }
(8).批量修改:
/// <summary>
/// 批量修改
/// </summary>
/// <param name="listmfRecordlog"></param>
/// <returns>是否成功</returns>
public bool BatchUpdateTest(List<M_Test> listTest) { var strSql = new StringBuilder(); var mysqlParam = new List<MySqlParameter>(); for (var i = 0; i < listTest.Count; i++) { var item = listTest[i]; strSql.AppendFormat( "UPDATE sys_Test SET UpdateName = @UpdateName{0},UpdateTime=@UpdateTime{0},UpdateID=@UpdateID{0},OperationType=@OperationType{0} WHERE RecordLogID=@RecordLogID{0};", i); mysqlParam.Add(new MySqlParameter(string.Format("@UpdateName{0}", i), item.UpdateName)); mysqlParam.Add(new MySqlParameter(string.Format("@UpdateTime{0}", i), item.UpdateTime)); mysqlParam.Add(new MySqlParameter(string.Format("@UpdateID{0}", i), item.UpdateID)); mysqlParam.Add(new MySqlParameter(string.Format("@OperationType{0}", i), item.OperationType)); mysqlParam.Add(new MySqlParameter(string.Format("@CreateName{0}", i), item.CreateName)); mysqlParam.Add(new MySqlParameter(string.Format("@RecordLogID{0}", i), item.RecordLogID)); } try { var num = MySqlHelper.ExecuteNonQuery(MySqlHelper.ConnectionStringRemp, CommandType.Text, strSql.ToString(), mysqlParam.ToArray()); return num > 0; } catch (Exception ex) { LogHelper.AddErrorLog("批量修改失敗", ex.ToString(), ""); return false; } }
(9).拼接SQL別用where 1=1,而後再拼接and,where 1=1 會先檢索全表
const string sql = @"select * from table "; var where = new StringBuilder(); if (!string.IsNullOrWhiteSpace(xx)) { where.AppendFormat(" where id = {0}",xx); } if (!string.IsNullOrWhiteSpace(yy)) { where.Append(where.Length > 1 ? " and" : "where"); where.AppendFormat(" name = {0}",yy); } var sqlstr = sql + where;
20.SQL裏面若是排序不了,能夠多利用linq 或lamber表達式排序。
21.前端JS經過數組,傳一個對象給ASP.net MVC 的後臺方法。後臺定義一個實體類和前端的名稱一致,Mvc會自動轉化。
JS代碼:
function btnSave() {
var btnSave = document.getElementById("btnSave"); //將表單提交按鈕設置爲不可用,這樣就能夠避免用戶再次點擊提交按鈕 btnSave.disabled = true; if ($("#Remark").val() == "") { alert("備註不能爲空"); btnSave.disabled = false; return false; } var data = {}; data["data.CallStatus"] = $("#CallStatus").val(); data["data.ITime"] = $("#ITime").val(); data["data.Remark"] = $("#Remark").val(); data["data.IResult"] = $("#IResult").val(); $.ajax({ type: 'post', url: "/TestWeb/TestActivity/TestDetail", datatype: 'json',//返回json格式的數據 data: data, error: function (XHR) { alert('網絡異常,請稍候再試'); btnSave.disabled = false; }, success: function (data) { if (data.Success) { alert("添加成功"); } else { alert("添加失敗"); } } }); }
C#代碼:
[HttpPost]
public JsonResult TestDetail(M_TestDetail data)//這裏data要和前端的data["data.CallStatus"] 中括號裏面的data名稱同樣,對應的字段名該實體類字段名稱同樣。MVC會自動轉化 { var msg = new ResultMsgInfo(); msg.Msg = "保存成功"; msg.Success = true; return Json(msg, JsonRequestBehavior.AllowGet); }
M_TestDetail實體類:
[DataContract]
public class M_TestDetail { ///<summary> /// 邀約電話接通狀況:0 接聽成功 1 無人接聽 2 拒接 3 信息錯誤 4 空號 5 號碼過時 6 未接通 7 通話中 ///</summary> [DataMember] public sbyte? CallStatus { get; set; } ///<summary> /// 贊成到場時間 ///</summary> [DataMember] public string ITime { get; set; } ///<summary> /// 備註 ///</summary> [DataMember] public string Remark { get; set; } ///<summary> /// 邀約結果:0 無 1 來 2 不來 3 待定 4 從新邀約 ///</summary> [DataMember] public sbyte? IResult { get; set; } }
22.Json轉換實體,使用 Deserialize<M_TestDetail>(jsonData); 須要引入Newtonsoft.Json.dll
public T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>(); var result = JsonConvert.DeserializeObject<T>(json); return result; }
23.ASP.Net MVC
(1).頁面判斷,裏面的文本須要加<text></text>,以下:
<input type="checkbox" @if (dateAm != null && dateAm.Count > 0) {<text> checked="checked"</text> }/>
(2). Html.RenderAction的使用
cshtml 代碼:
@{Html.RenderAction("JudgementStatus", new { num = item.CallStatus, statusName = "CallStatus" });}
控制器的C#代碼:
/// <summary>
/// 獲取狀態描述
/// </summary>
/// <param name="num"></param>
/// <param name="statusName"></param>
/// <returns></returns>
public string JudgementStatus(sbyte? num, string statusName)
{
var str = string.Empty; switch (statusName) { case "CallStatus": if (num.HasValue) { switch (num.Value) { //0 接聽成功 1 無人接聽 2 信息錯誤 3 拒接 4 空號 5 號碼過時 6 未接通 7 通話中 case 0: str = "接聽成功"; break; case 1: str = "無人接聽"; break; case 2: str = "拒接"; break; case 3: str = "信息錯誤"; break; case 4: str = "空號"; break; case 5: str = "號碼過時"; break; case 6: str = "未接通"; break; case 7: str = "通話中"; break; default: str = ""; break; } } else { str = ""; break; } break; case "IsSign": if (num.HasValue) { switch (num.Value) { case 0: str = "未到場"; break; case 1: str = "已到場"; break; default: str = ""; break; } } else { str = "未到場"; break; } break; } return str; }
24.時間處理的時候,不要用js的toLocaleDateString(); 由於兼容性很差,還要考慮到服務器後臺解析的兼容性,在Microsoft Edge序列化數組的時候,傳到後臺mvc,反序列化DataTime直接報錯,並且把datatime改爲string,而後經過Convert.ToDateTime("2016-8-29")轉化不了,緣由是編碼的問題,當我把2016-8-29拷貝到記事本里面保存,而後從新打開直接出現?。能夠改爲拼接的寫法:
var start = new Date($("#StartDate").val());
new Date(start).toLocaleDateString(); 上面的寫法改爲以下: var month = new Date(start).getMonth() + 1; var datatostring = new Date(start).getFullYear() + "-" + month + "-" + new Date(start).getDate(); var _oneDay = new Date(start.setDate(start.getDate() + 1)); var month = new Date(_oneDay).getMonth() + 1; var datatostring = new Date(start).getFullYear() + "-" + month + "-" + new Date(start).getDate(); IE10出現兼容性能夠用下面的方法處理: .replace("年", "/").replace("月", "/").replace("日", "").replace(/\?/g, ""); .replace("-", "/") replace("/", "-")
25.JS: var re = /^[0-9]*[1-9][0-9]*$/; //正整數
.replace(/\?/g, "");去掉?
26.展現mysql變量的函數 SHOW VARIABLES LIKE '%skip%';
27.C#訪問本地mysql出現「 HOST 'test' IS NOT allowed TO connect TO this MySQL server」 ?
解決方法:(1).以下圖 (2).找到安排目錄的C:\Program Files\MySQL\MySQL Server 5.5\my.ini,打開my.ini,加上skip_name_resolve=1,重啓mysql服務。
28.jQuery 能夠經過commitForm提交表單,mvc接受值,建議使用FormCollection取值,不要使用request取值
<form id="f1" method="POST">
<h2>AddAddress</h2>
<input type="text" name="Address"/>
<input type="text" name="Name"/>
<input id="Submit1" type="submit" value="submit"/>
</form>
<script type="text/javascript">
$(function() { $("#f1").commitForm({ url: '/home/test', callBack:function(data) { alert(data); } }); }); </script>
29.大數據併發出來:a.負載均衡(建多個站點,nginx(參考https://lufficc.com/blog/configure-nginx-as-a-web-server) ) b.使用緩存
30.數據的同步能夠經過Quartz.net 寫job處理,須要按時間來升序,須要考慮到相同時間的數據。
31.mysql 調用存儲過程
SET @iDrID=2; SET @vPatientName=''; SET @vSchemeTitle=''; SET @dSCreateTime=''; SET @dECreateTime=''; SET @iCheckSuggestFlag=-1; SET @iCurrentPageIndex=0; SET @iPageSize=10; CALL proc_Scheme_QueryList(@iDrID,@vPatientName,@vSchemeTitle,@dSCreateTime,@dECreateTime,@iCheckSuggestFlag,@iCurrentPageIndex,@iPageSize,@iRowCount); SELECT @iRowCount;
32.C#發送http 請求:1.HttpWebRequest 2.HttpClient(webapi)
33.直接返回某列的list集合
public List<int> GetAlltestIds() { const string sql = " select testId from sys_test "; var ds = MySqlHelper.ExecuteDataSet(ConnectionStringConfig.DataCenter, CommandType.Text, sql, new MySqlParameter[] { }); var list = ds.Tables[0].Rows.Cast<object>().Select((r, i) => Convert.ToInt32(ds.Tables[0].Rows[i][0])).ToList(); return list; }
34.經過ASP.MVC自帶的傳參數到後臺進行新增
public ActionResult Register()
{
var vmodel = new M_UserTest();
return View(vmodel);
}
public ActionResult RegisterTest(M_UserTest data)
{
var result = bll.Add(data);
return View();
}
@using Model @model M_UserTest @{ ViewBag.Title = "Register"; } <h2>Register</h2> <div class="row"> <div class="col-md-8"> <section id="loginForm"> @using (Html.BeginForm("RegisterTest", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { <div class="form-group"> <label class="col-md-2 control-label">用戶名</label> <div class="col-md-10"> @Html.TextBoxFor(m => m.username, new { @class = "form-control" }) </div> </div> <div class="form-group"> <label class="col-md-2 control-label">帳號</label> <div class="col-md-10"> @Html.TextBoxFor(m => m.userAccount, new { @class = "form-control" }) </div> </div> <div class="form-group"> <label class="col-md-2 control-label">密碼</label> <div class="col-md-10"> @Html.PasswordFor(m => m.userPwd, new { @class = "form-control" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="註冊" class="btn btn-default" /> </div> </div> } </section> </div> </div>
35.MySQL修改字段默認值和修改字段長度
use `test_ch`; /*修改字段默認值*/ alter table hm_test modify AuditStatus tinyint not null default 1 comment '審覈狀態 0.未審覈,1.已審覈'; /*修改字段長度*/ alter table hm_test modify column Summary varchar(2000);
36.C#把字符串數組轉化成List
/// <summary> /// 把字符串數組轉化成List /// </summary> /// <param name="target">字符串</param> /// <returns></returns> public static List<int> AsList(this string[] target) { var arr = new List<int>(); if (target == null || target.Length == 0) return arr; Array.ForEach(target, id => { int tmpId; if (int.TryParse(id, out tmpId)) { arr.Add(tmpId); } }); return arr; }
string scGoodIds = "1,2,,3,4,5,6,7"; var ids = scGoodIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).AsList();
37.用EF寫出一條分頁語句,頁碼數是1,頁大學爲20. 可參考LINQ系列:LINQ to SQL Take/Skip
pageIndex PageSize
var reulst = (from u in uList
orderby u.toolingNo
select u).Skip(pageSize *(pageIndex -1)).Take(pageSize);
OrderBy 是排序(後面是條件)而後要查詢全部的,在全部的數據中在查詢你要分頁的數據,skip是在分頁在前有多少條數據,也就是在當前頁數據以前的數據總和,(跳過序列中指定數量的元素,而後返回剩餘的元素。)pageSize*(pageIndex-1),Take 是返回多少條數據,也就是pageSize!
38.ling分組,處理
var IaidList = times.GroupBy(p => p.IAId).ToDictionary(p => p.Key, r => r.Select(o => o)).OrderBy(p => p.Key).ToList();
2)linq 分組去除重複的某項
var result = testItem.GroupBy(t => t.TestItemCode).Select(t => t.OrderByDescending(p => p.CreatedTime).OrderByDescending(p => p.TestItemID).FirstOrDefault());
3).分組彙總
q = q.GroupBy(t => t.CreateDate).Select(g => new TestData { CreateDate = g.Key, Num = g.Sum(p => p.Num), });
39.Quartz.net 安裝服務和卸載服務
安裝服務:
@Test.exe install
@pause
@exit
保存記事本里面,後綴名爲.bat
卸載服務:
@Test.exe uninstall
@net start Test
@pause
@exit
40.C# 對象轉jSON 時 過濾 NULL 的屬性 參考:https://q.cnblogs.com/q/72031/ http://www.newtonsoft.com/json/help/html/ReducingSerializedJSONSize.htm 須要引用Newtonsoft.Json.dll
public class Person { public int Id { get; set; } public string Name { get; set; } }
static void Main(string[] args) { var list = new List<Person>(); for (int i = 1; i < 5; i++) { list.Add(new Person() { Id = i, Name = "test" + i }); } list.Add(new Person() { Id = 5, Name = null, }); string ignored = JsonConvert.SerializeObject(list, Formatting.Indented, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
//[{"Id":1,"Name":"test1"},{"Id":2,"Name":"test2"},{"Id":3,"Name":"test3"},{"Id":4,"Name":"test4"},{"Id":5}] var test = JsonConvert.DeserializeObject<List<Person>>(ignored); Console.ReadLine(); }
41.怎麼監控EF生成的sql
1).EntityFramework Profiler, 下載地址:https://hibernatingrhinos.com/products/EFProf
2). 若是是SQL server 能夠用SQL Server Profiler, 具體能夠參考:http://www.cnblogs.com/allenhua/p/3533975.html
42.去掉webapi的token驗證。在compilation 家debug="true" 。 <compilation debug="true" targetFramework="4.5" />
43. IIS初始化(預加載),解決第一次訪問慢,程序池被回收問題
44.計算時間
Stopwatch stopwatch = new Stopwatch(); //第一次計時 stopwatch.Start(); Console.WriteLine("Stopwatch is running:{0}",stopwatch.IsRunning);//判斷當前Stopwatch的狀態 System.Threading.Thread.Sleep(1000);//耗時操做 stopwatch.Stop(); Console.WriteLine("Using Elapsed output runTime:{0}", stopwatch.Elapsed.ToString());//這裏使用時間差來輸出 Console.WriteLine("Using ElapsedMilliseconds output runTime:{0}", stopwatch.ElapsedMilliseconds);//這裏面使用毫秒來輸出
45.調用數據庫或服務,必定要釋放。 能夠經過查看oracle的鏈接數來看是不是否資源 select count(*) from v$session;
1).單個寫
using (testService as IDisposable) { persont = testService.GetTest(name); }
2).在基類寫,實現IDisposable。
private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing && _context != null) { _context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
46. EF 修改數據出現:Attaching an entity of type 'HR_TEST' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
原先代碼:
public bool Update(TEntity entity) { _context.Entry<TEntity>(entity).State = EntityState.Modified; return _context.SaveChanges() > 0; }
改爲:
public bool Update(TEntity entity, Func<TEntity, int> getKey) { // Retreive the Id through reflection var entry = _context.Entry<TEntity>(entity); if (entry.State == EntityState.Detached) { var set = _context.Set<TEntity>(); TEntity attachedEntity = set.Find(getKey(entity)); // access the key if (attachedEntity != null) { var attachedEntry = _context.Entry(attachedEntity); attachedEntry.CurrentValues.SetValues(entity);
AttachedEntry.State = EntityState.Modified; } else {
set.Attach(entity); entry.State = EntityState.Modified; // attach the entity } } return _context.SaveChanges() > 0; }
47.能夠用action定義實體轉化
//定義動態映射函數 Action<Patient> action = (Patient member) => { person.Name = member.Name; person.Gender = member.Sex; person.BirthDate = !string.IsNullOrWhiteSpace(member.Birthday) ? member.Birthday.Replace("-", "") : person.BirthDate;//系統中的生日所有是yyyyMMdd格式 person.Nationality = member.Ethnic; person.CensusAddressName = member.Domicile; person.Country = country; person.IDNumber = idcard; person.IDType = idType; };
48.C#生成隨機流水號:
public static string GenerateOrderId() { string text = string.Empty; System.Random random = new System.Random(); for (int i = 0; i < 7; i++) { int num = random.Next(); text += ((char)(48 + (ushort)(num % 10))).ToString(); } return System.DateTime.Now.ToString("yyyyMMdd") + text; }
49.redis加入到Windows 服務
安裝命令:
redis-server.exe --service-install redis.windows.conf --loglevel verbose
卸載命令:
redis-server --service-uninstall
50.異步調用
1).
Task.Run(() =>
{
Test();
});
2).
Action act = () => Test(); act.BeginInvoke(t => act.EndInvoke(t), null);
51.C# 調用webApi
1).webpai Post
[Route("CheckUp"), HttpPost] public IHttpActionResult CheckUp(CheckUp request) { return Ok(new { Status = 0, Msg = "" }); }
調用代碼
1).
/// <summary> /// 須要引用 System.Net.dll,System.IO.dll /// </summary> /// <param name="url">url</param> /// <param name="headers">頭文信息</param> /// <param name="format">格式</param> /// <param name="formData">傳入數據格式</param> /// <returns></returns> public static string Post(string url, Dictionary<string, string> headers, string format, string formData) { byte[] postData = Encoding.UTF8.GetBytes(formData); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.AllowAutoRedirect = false; request.ContentType = format+";charset=utf-8"; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)"; if (headers != null) { foreach (KeyValuePair<string, string> item in headers) { request.Headers.Add(item.Key, item.Value); } } request.ContentLength = postData.Length; // 開始請求 using (Stream postStream = request.GetRequestStream()) { postStream.Write(postData, 0, postData.Length); } HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream s = response.GetResponseStream(); StreamReader reader = new StreamReader(s, Encoding.GetEncoding("UTF-8")); string result = reader.ReadToEnd(); reader.Close(); s.Close(); if (response != null) response.Close(); if (request != null) request.Abort(); return result; }
Post(url, new Dictionary<string, string>(), "application/json", JsonConvert.SerializeObject(checckup));
2).
//定義Request 並設置request的路徑 WebRequest request = WebRequest.Create(url); request.Method = "post"; //設置參數的編碼格式,解決中文亂碼 byte[] byteArray = Encoding.UTF8.GetBytes(data); //設置Request的MINE類型及內容長度 request.ContentType = "application/json"; request.ContentLength = byteArray.Length; //打開request字符流 Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //定義response爲前面的request響應 WebResponse response = request.GetResponse(); //獲取相應的狀態代碼 var str = ((HttpWebResponse)response).StatusCode; //定義response字符流 dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFormServer = reader.ReadToEnd();//讀取全部
3).
url = url + "/api/test/login"; var list = request.ToDictionary(); var data = new NameValueCollection(); foreach (var item in list) { if (item.Value != null) { data.Add(item.Key, item.Value.ToString()); } } WebClient wc = new WebClient(); byte[] result = wc.UploadValues(url, "POST", data); var response = System.Text.Encoding.UTF8.GetString(result);
4).http get 和post 調用webapi 方法
#region post信息 /* string content = Post('url', new Dictionary<string, string>(), "application/json", Utils.ModelToJson(new testModel { testcard = '', testtype = '' })) */ /// <summary> /// post信息 /// </summary> /// <param name="url"></param> /// <param name="headers"></param> /// <param name="format"></param> /// <param name="formData"></param> /// <returns></returns> public static string Post(string url, Dictionary<string, string> headers, string format, string formData) { byte[] postData = Encoding.UTF8.GetBytes(formData); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.AllowAutoRedirect = false; request.ContentType = format+";charset=utf-8"; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)"; if (headers != null) { foreach (KeyValuePair<string, string> item in headers) { request.Headers.Add(item.Key, item.Value); } } request.ContentLength = postData.Length; // 開始請求 using (Stream postStream = request.GetRequestStream()) { postStream.Write(postData, 0, postData.Length); } HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream s = response.GetResponseStream(); StreamReader reader = new StreamReader(s, Encoding.GetEncoding("UTF-8")); string result = reader.ReadToEnd(); reader.Close(); s.Close(); if (response != null) response.Close(); if (request != null) request.Abort(); return result; } #endregion #region 獲取get消息 /// <summary> /// 獲取get消息 /// </summary> /// <param name="format">xml,json選擇返回</param> /// <param name="url"></param> /// <param name="headers"></param> /// <returns> HttpHelper.Get("json", url + "/api/patient/getpatientbyphone?phone=" + phoneNo, null);</returns> public static string Get(string format, string url, Dictionary<string, string> headers) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.AllowAutoRedirect = false; request.ContentType = "text/" + format + ";charset=utf-8"; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)"; if (headers != null) { foreach (KeyValuePair<string, string> item in headers) { request.Headers.Add(item.Key, item.Value); } } HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream s = response.GetResponseStream(); StreamReader reader = new StreamReader(s, Encoding.GetEncoding("UTF-8")); string result = reader.ReadToEnd(); reader.Close(); if (s != null) s.Close(); response.Close(); request.Abort(); return result; } #endregion
5).webapi
[Route("CheckUp"), HttpPost] public IHttpActionResult CheckUp([FromBody] string baseRequest) { }
調用代碼
//設置HttpClientHandler的AutomaticDecompression var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; //建立HttpClient(注意傳入HttpClientHandler) using (var http = new HttpClient(handler)) { //使用FormUrlEncodedContent作HttpContent var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"",data}//鍵名必須爲空,data爲json字符串 }); //await異步等待迴應 var response = await http.PostAsync(url, content); //確保HTTP成功狀態值 response.EnsureSuccessStatusCode(); //await異步讀取最後的JSON(注意此時gzip已經被自動解壓縮了,由於上面的AutomaticDecompression = DecompressionMethods.GZip) await response.Content.ReadAsStringAsync(); }
52. C# async和await string 轉爲Task<string>
public static async Task<string> Test(string[] inputs) { StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < 10; i++) { sBuilder.Append(i.ToString("x2")); } return await Task.FromResult(sBuilder.ToString()); }
53. 實體轉化不用從新寫方法,能夠用委託(Action<T>)來實現,demo以下:
private void Test(PersonInfoModels data) { Action<PersonInfoModels> action = (PersonInfoModels m) => { person.Name = m.Name; } if (data != null) {
//調用 action(data); } }
54.Linq To Sql中實現Left Join與Inner Join使用Linq語法與lambda表達式
當前有兩個表,sgroup與sgroupuser,二者經過gKey關聯,而sgroup表記錄的是組,而sgroupuser記錄是組中的用戶,所以在sgroupuser中不必定有數據。須要使用Left Join獲取數據:
Linq語法以下:
var sg = (from g in dc.sgroup
join gu in dc.sgroupuser on g.gKey equals gu.gKey into l
from lgu in l.DefaultIfEmpty()
select new { g, lgu }).ToList();
Lambda表達式以下:
var sg = dc.sgroup.GroupJoin(dc.sgroupuser, g => g.gKey, gu => gu.gKey, (g, gu) => new { g, gu }).Select(o=>o).ToList() ;
注意:
Linq 與Lambda表達式取出的結果有所不一樣.Linq取出的結果的記錄數與Sql中的Left Join的結果相同,而Lambda表達式取出的記錄數是sgroup表中的記錄數,sgroupuser對應的記錄是以對象集合存在於結果中
附:
下面是Inner Join:
Linq語法以下:
var sg = (from g in dc.sgroup
join gu in dc.sgroupuser on g.gKey equals gu.gKey
select new { g, gu }).ToList();
Lambda表達式以下:
var sg = dc.sgroup.Join(dc.sgroupuser, g => g.gKey, gu => gu.gKey, (g, gu) => new { g, gu }).Select(o=>o).ToList() ;
注意:
上面最後都用到了ToList()方法 , 用ToList()是爲了一次性將數據取到本地
http://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html
55.
1).linq 實現left join,並在on 後面添加and
var list = from a in bloodlist join b in sugarlist on new { a.OrganizationID,a.MonitorDate } equals new { b.OrganizationID, b.MonitorDate } into sugarTemp from newb in sugarTemp.DefaultIfEmpty() select new DetectData { OrganizationID = a.OrganizationID, MonitorDate = a.MonitorDate, DayBloodPressureNum = a.DayBloodPressureNum, DaySugarPressureNum = newb != null ? newb.DaySugarPressureNum : 0 };
2).let
result = (from b in bloodlist join s in sugarlist on new { b.OrganizationID, b.MonitorDate } equals new { s.OrganizationID, s.MonitorDate } select new BI_IndexDetectData { MonitorDate = b.MonitorDate, OrganizationID = b.OrganizationID, DayBloodPressureNum = b.DayBloodPressureNum, DaySugarPressureNum = s.DaySugarPressureNum, }).ToList(); var result1 = (from b in bloodlist join s in sugarlist on new { b.OrganizationID, b.MonitorDate } equals new { s.OrganizationID, s.MonitorDate } let daySugarPressureNum = s.DaySugarPressureNum where s.DaySugarPressureNum > 0 select new BI_IndexDetectData { MonitorDate = b.MonitorDate, OrganizationID = b.OrganizationID, DayBloodPressureNum = b.DayBloodPressureNum, DaySugarPressureNum = daySugarPressureNum, }).ToList();
56.C#遞歸根據日期分頁獲取全部知足條件的體檢信息
調用 var dataresult = GetPageOfAllCheckUpRegInfo(pageIndex, pageSize, BeginCheckDate.Value, endCheckUpDate.Value,isVip);
#region 根據總檢日期和頁碼獲取全部知足條件的體檢登記信息 /// <summary> /// 根據總檢日期和頁碼獲取全部知足條件的體檢登記信息 /// </summary> /// <param name="pageIndex">當前頁碼</param> /// <param name="pageSize">頁大小</param> /// <param name="bcheckUpDate">總檢開始日期</param> /// <param name="echeckUpDate">總檢結束日期</param> /// <returns></returns> private List<CheckUpRegInfo> GetPageOfAllCheckUpRegInfo(int pageIndex, int pageSize, DateTime bcheckUpDate, DateTime echeckUpDate, string isVip) { var result = new List<CheckUpRegInfo>(); // 遞歸獲取全部知足條件的體檢登記信息 GetAllCheckUpRegInfo(pageIndex, pageSize, bcheckUpDate, echeckUpDate,isVip,result); return result; } #endregion #region 遞歸獲取體檢登記信息 /// <summary> /// 遞歸調用 /// </summary> /// <param name="pageIndex">當前頁碼</param> /// <param name="pageSize">頁大小</param> /// <param name="bcheckUpDate">總檢開始日期</param> /// <param name="echeckUpDate">總檢結束日期</param> /// <param name="isVip">是否vip</param> /// <param name="result">返回結果</param> private void GetAllCheckUpRegInfo(int pageIndex, int pageSize, DateTime bcheckUpDate, DateTime echeckUpDate,string isVip,List<CheckUpRegInfo> result) { try { var req = new CheckUpDataInput(); req.BeginCheckDate = bcheckUpDate; req.EndCheckDate = echeckUpDate; req.PageSize = pageSize; req.PageIndex = pageIndex; req.SortType = false; req.OrderBy = "JCRQ";//總檢日期 req.IsVip = isVip; CheckService = new AutoCheckService(req); var dataResult = CheckService.GetPageOfCheckUpRegInfo(); //釋放資源 using (CheckService as IDisposable) { } if (dataResult != null && dataResult.ResultCode == 100) { var list = dataResult.Result.ToList(); if (list != null && list.Count > 0) { var PageCount = dataResult.PageCount; //本頁執行完成,繼續執行下一頁 if (pageIndex <= PageCount) { pageIndex++; result.AddRange(list); GetAllCheckUpRegInfo(pageIndex, pageSize, bcheckUpDate, echeckUpDate, isVip, result); } } } } catch (Exception ex) { WriteLog("GetAllCheckUpRegInfo遞歸獲取體檢登記信息:" + ex.Message); } } #endregion
57.將字符串轉爲int,不然返回默認值
/// <summary> /// 將字符串轉爲int,不然返回默認值 /// </summary> /// <param name="values"></param> /// <returns></returns> public static int[] ToIntArray(this string[] values) { int len = values.Length; var indexIds = new int[len]; for (int i = 0; i < len; i++) { indexIds[i] = values[i].ToInt(0); } return indexIds; }
58.EF 中必須 AsEnumerable() 以後才能group by
1).IQueryable 有諸多限制, 只支持數據庫查詢語法, 沒法支持 Linq to object 的操做.
2).加了 AsEnumerable() 後運行正常, 由於 IEnumerable 支持 Linq to object 的操做.
簡述Linq中.ToList(), .AsEnumerable(), AsQueryable()的區別和用法
LINQ語句中的.AsEnumerable() 和 .AsQueryable()的區別
/// <summary> /// 分組查詢 /// </summary> /// <typeparam name="S"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="request"></param> /// <param name="whereAndOrderBy"></param> /// <returns></returns> public virtual BaseResponse<IList<T>> GroupQuery<S, T>(BaseRequest request, Func<IEnumerable<S>, IEnumerable<S>> whereAndOrderBy) where S : class { BaseResponse<IList<T>> response = new BaseResponse<IList<T>>(); //Mapper.CreateMap<S, T>(); var q = from m in unitOfWork.GetRepository<S>().dbSet.AsEnumerable() select m; if (whereAndOrderBy != null) { q = whereAndOrderBy(q); } //建立一個參數c ParameterExpression param = Expression.Parameter(typeof(S), "c"); //c.IsDeleted=="false" Expression left = Expression.Property(param, typeof(S).GetProperty("IsDeleted")); Expression right = Expression.Constant(false); Expression filter = Expression.Equal(left, right); Expression pred = Expression.Lambda(filter, param); //Where(c=>c.IsDeleted==false) //Expression expr = Expression.Call(typeof(Queryable), "Where", // new Type[] { typeof(S) }, // Expression.Constant(q), pred); //生成動態查詢 //q = q.Provider.CreateQuery<S>(expr); q = q.AsQueryable().Where((Expression<Func<S, bool>>)pred); response.RecordsCount = q.Count(); List<S> list = null; if (request != null && request.PageSize > 0) { list = q.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize).ToList(); response.PagesCount = GetPagesCount(request.PageSize, response.RecordsCount); } else { list = q.ToList(); } //response.Data = Mapper.Map<IList<T>>(list); response.Data = Mapper.DynamicMap<IList<T>>(list); return response; }
59.EF 傳實體,不能更新,須要先根據某個條件查詢實體,而後再把傳過來的值賦上,就能夠更新實體。
60.實現一個條記錄裏面兩個值要成對出現
思路:分別查出兩個結果集,進行union(MySQL 裏面用union),而後在根據主鍵ID分組,having count(Id)= 2,根據時間降序。
方法一 Linq 實現
var idlist = (from p in result group p by p.ExaminationID into h select new { key = h.Key, count = h.Count(), examDate = h.FirstOrDefault().ExaminationTime } into c where c.count == 2 orderby c.examDate descending select c).Select(t => t.key).Take(7).ToList();
對應mysql 語句表示
SELECT * result GROUP BY ExaminationID HAVING COUNT(ExaminationID ) = 2 ORDER BY ExaminationTime DESC LIMIT 7
方法二
var rest = (from height in resultHeight join weight in resultWeight on height.ExaminationID equals weight.ExaminationID select new { ExaminationTime = height.ExaminationTime, CheckValueHeight = height.CheckValue, CheckValueWeight = weight.CheckValue, }).OrderByDescending(t => t.ExaminationTime).Take(7).ToList()
61.C# 正則 匹配字符中整個url
string str="網址爲http://test.com/?key=123123 ,祝您生活愉快"; Regex re = new Regex("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"); MatchCollection mc = re.Matches(str); var url = ""; foreach (Match m in mc) { url = m.ToString(); }
62.監控網站,能夠監控EF生成的sql dynatrace
63.asp.net webapi 集成swagger 自動生成webapi文檔
64.C#上傳圖片從新命名圖片,防止重名。
65.篩選結果成對出現
1).linq
var list = (from item in testDataList where new List<string>() { "101", "102" }.Contains(item.TestCode) group item by item.testID into temp select new { key = temp.Key, count = temp.Count() } into c where c.count == 2 select c).ToList();
2).sql
SELECT COUNT(*),testCode,Value,Exid FROM CM_test WHERE testCode IN('101','102') GROUP BY Exid HAVING COUNT(*) = 2
66.C#int類型相乘
Math.Round((decimal)singeTotal / (decimal)totalResult * (decimal)100.0, 2)
67. /分割並去除空值
//分割並去除空值 "1,2,13,4,5,,".Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
68.Visual Studio 2017 單元測試運行不了的解決辦法
將測試項目的引用 Microsoft.VisualStudio.TestPlatform.TestFramework、Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions 刪掉
添加 Microsoft.VisualStudio.QualityTools.UnitTestFramework(經過Nuget添加) 既可
69.添加Debug測試
#if !DEBUG //不是debug模式 var account = CurrentAccount; if (account!=null) { return account.ID; } return -1; #else //是debug模式 return 6378; #endif
70.使用redis 實現Session["checkCode"] 的功能,參考 不用session的驗證碼。登陸實現圖片驗證碼功能爲例
ValidateCode.cs:
/// <summary> /// 驗證碼 /// </summary> public static class ValidateCode { #region 生成驗證碼 /// <summary> /// 生成驗證碼 /// </summary> /// <param name="length">指定驗證碼的長度</param> /// <returns>驗證碼</returns> public static string[] CreateValidateNumber(int length) { string Vchar = "1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,p" + ",q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q" + ",R,S,T,U,V,W,X,Y,Z"; string[] VcArray = Vchar.Split(new Char[] { ',' });//拆分紅數組 string[] num = new string[length]; int temp = -1;//記錄上次隨機數值,儘可能避避免生產幾個同樣的隨機數 Random rand = new Random(); //採用一個簡單的算法以保證生成隨機數的不一樣 for (int i = 1; i < length + 1; i++) { if (temp != -1) { rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks)); } int t = rand.Next(VcArray.Length - 1); if (temp != -1 && temp == t) { return CreateValidateNumber(length); } temp = t; num[i - 1] = VcArray[t]; } return num; } #endregion #region 生成圖片驗證碼 /// <summary> /// 生成圖片驗證碼 /// </summary> /// <param name="checkCode"></param> public static string CreateCheckCodeImage(string[] checkCode) { if (checkCode == null || checkCode.Length <= 0) return null; Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 32.5)), 60); Graphics g = Graphics.FromImage(image); try { //生成隨機生成器 Random random = new Random(); //清空圖片背景色 g.Clear(Color.White); //定義顏色 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //畫圖片的背景噪音線 for (int i = 0; i < 25; i++) { int cindex = random.Next(7); int findex = random.Next(5); int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); } //定義字體 string[] f = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋體" }; for (int k = 0; k <= checkCode.Length - 1; k++) { int cindex = random.Next(7); int findex = random.Next(5); Font drawFont = new Font(f[findex], 26, (System.Drawing.FontStyle.Bold)); SolidBrush drawBrush = new SolidBrush(c[cindex]); float x = 5.0F; float y = 0.0F; float width = 42.0F; float height = 48.0F; int sjx = random.Next(10); int sjy = random.Next(image.Height - (int)height); RectangleF drawRect = new RectangleF(x + sjx + (k * 25), y + sjy, width, height); StringFormat drawFormat = new StringFormat(); drawFormat.Alignment = StringAlignment.Center; g.DrawString(checkCode[k], drawFont, drawBrush, drawRect, drawFormat); } //畫圖片的前景噪音點 for (int i = 0; i < 500; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } int cindex1 = random.Next(7); //畫圖片的邊框線 g.DrawRectangle(new Pen(c[cindex1]), 0, 0, image.Width - 1, image.Height - 1); MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Jpeg); //return ms.ToArray(); // 圖片到byte[]再到base64string的轉換: string base64pic = "data:image/jpeg;base64,"+ Convert.ToBase64String(ms.ToArray()); return base64pic; } finally { g.Dispose(); image.Dispose(); } } #endregion }
控制器的代碼:
#region 隨機生成sessionid /// <summary> /// 隨機生成sessionid /// </summary> private string sessionId { get { return "__sessionName__" + Guid.NewGuid().ToString(); } } #endregion #region 登陸頁面 /// <summary> /// 登陸頁面 /// </summary> /// <returns></returns> public ActionResult Login() { ViewBag.sessionid = sessionId;//傳到頁面,放在隱藏域裏面 return View(); } #endregion #region 生成驗證碼 /// <summary> /// 生成驗證碼 /// </summary> /// <param name="sessionid">隨機的編碼</param> /// <returns></returns> [HttpGet] public JsonResult CheckCode(string sessionid) { //生成驗證碼 string[] str = ValidateCode.CreateValidateNumber(4); string strcode = string.Empty; for (int i = 0; i < str.Length; i++) { strcode += str[i]; } string base64Pic = ValidateCode.CreateCheckCodeImage(str); RedisHelper redisHelper = new RedisHelper(); if (redisHelper.IsConnected() && !String.IsNullOrEmpty(sessionid)) { redisHelper.StringSet(sessionid, strcode, new TimeSpan(0, 10, 0));//有效期10分鐘 } return Json(base64Pic, JsonRequestBehavior.AllowGet); } #endregion #region 登陸 /// <summary> /// 登陸 /// </summary> /// <param name="name">用戶名</param> /// <param name="pwd">密碼</param> /// <param name="isRemember">是否記住用戶名</param> /// <param name="verifycode">驗證碼</param> /// <returns></returns> [HttpPost] public ActionResult Login(string name, string pwd, string verifycode, string sessionid) { string redisCheckCode = string.Empty; RedisHelper redisHelper = new RedisHelper(); if (redisHelper.IsConnected() && !string.IsNullOrEmpty(sessionid)) { redisCheckCode = redisHelper.StringGet(sessionid); } !string.IsNullOrEmpty(redisCheckCode) && verifycode.ToUpper() == redisCheckCode.ToUpper() } #endregion
Html:
<div id="verifycodeWrapper" class="mgt20"> <input maxlength="4" id="txtVerifycode" type="text" class="input-code" name="verifycode" placeholder="驗證碼" required="required" /> <img id="imgCode" alt="單擊可刷新" style="height:35px;" onclick="ChangeCode()" /> </div> <input type="hidden" id="sessionid" name="sessionid" value="@ViewBag.sessionid">
JS:
//單擊從新改變驗證碼 function ChangeCode() { var seid = '@ViewBag.sessionid'; $.ajax({ url: "/Home/CheckCode", type: "get", dataType: "json", contentType: "application/json", data: { sessionid: seid}, success: function (data) { if (data) { var img = document.getElementById("imgCode"); img.setAttribute("src", data); } } }); } $(document).ready(function () { setTimeout(ChangeCode(),5000); });
71. web api 自動生成文檔
1).swagger集成。
2). apidoc,參考:http://apidocjs.com/#install http://apidoc.tools/#docs
npm install apidoc -g
apidoc -i controllers -o dest 具體以下:
72. ORM 框架 sqlsugar
js 模板框架 arttemplate
前端 sui.js
73.WebAPI防篡改簽名驗證抽象基類Attribute
/// <summary> /// WebAPI防篡改簽名驗證抽象基類Attribute /// </summary> public class AuthenticationAttribute : ActionFilterAttribute { //獲取Asp.Net對應的Request /// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context</param> public override void OnActionExecuting(HttpActionContext actionContext) { //Referer請求頭驗證 if(actionContext.Request==null || actionContext.Request.Headers==null || actionContext.Request.Headers.Referrer == null || string.IsNullOrWhiteSpace(actionContext.Request.Headers.Referrer.ToString())) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "非法調用"); return; } var Referer = ConfigurationManager.AppSettings["Referer"]; if (string.IsNullOrWhiteSpace(Referer)) { return; } var flag = false; var list = Referer.Split(';'); foreach (var item in list) { if (actionContext.Request.Headers.Referrer.ToString().Contains(item)) { flag = true; break; } } if (!flag) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "非法調用"); } } } public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Filters.Add(new AuthenticationAttribute()); } }
2).
public class DExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { //能夠記錄一些日誌 string fLog = context.Exception.StackTrace; DateTime EndTime = DateTime.Now; LogHelper.WriteError(string.Format("{0}調用出錯結束時間:{1:yyyy-MM-dd HH:mm:ss:fff};\r\n出錯的URL:<{2}>;\r\n報出的錯誤:{3}",context.Request.RequestUri.PathAndQuery,EndTime, context.Request.RequestUri.ToString(), fLog)); Action act = () => ErrorLogHelper.AddErrorLog(context, null, null); act.BeginInvoke(ar => act.EndInvoke(ar), null); context.Response = new HttpResponseMessage(HttpStatusCode.OK); context.Response.Content = new StringContent(JsonConvert.SerializeObject(new HISResponse() { Status = -1})); } } public static class WebApiConfig { public static void Register(HttpConfiguration config) { //加入異常過濾器,統一集中處理異常報錯和異常日誌記錄,系統異常時統一返回的結果 config.Filters.Add(new DExceptionFilterAttribute()); } }
74.C#啓動線程的幾種方法
什麼線程有幾種啓動方式,怎麼優化sql語句,
Mvc頁面生命週期
結構和類的區別,結構的做用
數據庫的優化
.net core與mvc區別,有哪些優缺點
MVC 過濾器
75.linq 兩個基礎數據成對出現
linst.Where(p => && CodeList.Contains(p.Code)) .OrderByDescending(p => p.TestDate) .GroupBy(x => new { x.TestID, x.TestDate }) .Select(g => new { TestID = g.Key.TestID, TestDate = g.Key.TestDate, Count = g.Count() }).Where(g => g.Count == 2).OrderByDescending(p => p.TestDate).Take(30).ToList()
76. C# 將字符串轉爲int,不然返回默認值
/// <summary> /// 將字符串轉爲int,不然返回默認值 var ids = request.Data.HealthTypeIDs.Split(',').ToIntArray(); /// </summary> /// <param name="values"></param> /// <returns></returns> public static int[] ToIntArray(this string[] values) { int len = values.Length; var indexIds = new int[len]; for (int i = 0; i < len; i++) { indexIds[i] = values[i].ToInt(0); } return indexIds; }
77.List<int> 的結果集,除了用循環,怎麼轉爲List<string>的結果集
int[] id = new int[] { 1, 2, 3, 4, 5, 6, 7 }; var ids = id.ToList(); List<string> ArryIds = new List<string>(); ArryIds = ids.ConvertAll<string>(x => x.ToString());
或
ArryIds = new List<string>(ids.Select(x => x.ToString()));
1.List<string> 轉 List<int> var strList = new List<string>{"1","2","3"}; var intList = strList.Select<string,int>(x =>Convert.ToInt32(x)); 2.List<string> 轉 List<long> var strList = new List<string>{"1","2","3"}; var longList = strList.Select<string,long>(x =>Convert.ToInt64(x));
78.優化查詢,能夠用SQL把結果集查出來(toList()),而後在分組(GroupBy)
79.C# switch case 的優化方式
#region 1的性別轉換2的性別 /// <summary> /// 1性別轉換2的性別 /// </summary> /// <param name="sex">性別 (0:男,1女)</param> /// <returns></returns> private string SexTGender(int? sex) { //性別[1:男,2:女,0:未知的性別,9:未說明的性別] string gender = "9"; if (sex.HasValue) { switch (sex.Value) { case 0: gender = "1"; break; case 1: gender = "2"; break; } } return gender; } #endregion
調用以下:
var person = new PersonModel(); MemberModel request = new MemberModel(); person.Gender = SexTGender(request.sex);
可使用反射來改造
#region 實體轉換 /// <summary> /// 實體轉換 /// </summary> /// <typeparam name="T">目標實體</typeparam> /// <typeparam name="S">源實體</typeparam> /// <param name="t">目標實體</param> /// <param name="s">源實體</param> /// <param name="tfiled">目標具體實體字段</param> /// <param name="sfield">源具體實體字段</param> /// <param name="dic">字典項</param> public static void mapToField<T, S>(T t, S s, string tfiled, string sfield, Dictionary<string, string> dic) { var tt = typeof(T); var tf = tt.GetProperty(tfiled); var ts = typeof(S); var sf = ts.GetProperty(sfield); var v = sf.GetValue(s).ToString(); var n_v = dic.Where(a => a.Key == v).FirstOrDefault().Value; tf.SetValue(t, n_v); } #endregion
調用,這樣實現的方式不用每次轉換都要寫一個方法
var person = new PersonModel(); MemberModel request = new MemberModel(); Dictionary<string, string> dic = new Dictionary<string, string>(); if (request.sex.HasValue) { //key 性別 (0:男,1女) //value 性別[1:男,2:女,0:未知的性別,9:未說明的性別] dic.Add("0", "1"); dic.Add("1", "2"); mapToField<PersonModel, MemberModel>(person, request, "Gender", "sex", dic); }
80.C# unity http://www.javashuo.com/article/p-bxeuezdd-gy.html
81.C# 實現redis 分佈式鎖 ,另外的實現:https://www.oddity.cn/6190714.html
須要引入Redlock.CSharp.dll 和RedLock.dll
public class RedlockHelper { public void Lock(Action<bool> action, string val, string key = "IdNo") { Redlock.CSharp.Redlock dlm = new Redlock.CSharp.Redlock(RedisConnectionHelp.Instance); Lock lockObject; string resourceName = string.Format("Redlock_{0}_{1}", key, val); var locked = dlm.Lock(resourceName, new TimeSpan(0, 0, 10), out lockObject); try { action.Invoke(locked); } finally { if (lockObject != null) dlm.Unlock(lockObject); } } }
調用:
new RedlockHelper().Lock((locked) => { if (locked) { ID = obj.addTest(); } });
82.sql server 經過建立存儲過程,生成表對應的model
1).建立一個類別表
CREATE TABLE [dbo].[Catalogue]( [CatalogueId] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](126) NOT NULL, [Description] [varchar](256) NULL, [ParentCatalogueId] [int] NOT NULL, [CreatedTime] [datetime] NOT NULL, [ModifiedTime] [datetime] NOT NULL, [IsDeleted] [bit] NOT NULL, PRIMARY KEY CLUSTERED ( [CatalogueId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER TABLE [dbo].[Catalogue] ADD DEFAULT (NULL) FOR [Description] GO ALTER TABLE [dbo].[Catalogue] ADD DEFAULT ('0') FOR [ParentCatalogueId] GO ALTER TABLE [dbo].[Catalogue] ADD DEFAULT ('0') FOR [IsDeleted] GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'類別Id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue', @level2type=N'COLUMN',@level2name=N'CatalogueId' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'類別名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue', @level2type=N'COLUMN',@level2name=N'Name' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'描述' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue', @level2type=N'COLUMN',@level2name=N'Description' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'父類別ID' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue', @level2type=N'COLUMN',@level2name=N'ParentCatalogueId' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'建立時間' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue', @level2type=N'COLUMN',@level2name=N'CreatedTime' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'修改時間' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue', @level2type=N'COLUMN',@level2name=N'ModifiedTime' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否刪除,0:否,1:是' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue', @level2type=N'COLUMN',@level2name=N'IsDeleted' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'產品類別' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Catalogue' GO
2).建立存儲過程
============================================= --表結構生成model -- ============================================= CREATE PROCEDURE [dbo].[Sys_ViewModel] @TableName nvarchar(64), @KeyWord nvarchar(64) AS BEGIN SELECT CASE WHEN col.colorder = 1 THEN obj.name ELSE @TableName END AS 表名, '/// <summary>' as lie1, '///'+CONVERT(nvarchar(50), ISNULL(ep.[value], '')) as lie2, '/// </summary>'as lie3, ' public ' + CASE WHEN t.name = 'bigint' THEN 'int' WHEN t.name = 'nvarchar' THEN 'string' WHEN t.name = 'int' THEN 'int' WHEN t.name = 'bit' THEN 'bool' WHEN t.name='datetime' THEN 'DateTime' WHEN t.name='tinyint' THEN 'int' else t.name END +' '+col.name +' { get; set; }' as lie4 into #Temp FROM dbo.syscolumns col LEFT JOIN dbo.systypes t ON col.xtype = t.xusertype inner JOIN dbo.sysobjects obj ON col.id = obj.id AND obj.xtype = 'U' AND obj.status >= 0 LEFT JOIN dbo.syscomments comm ON col.cdefault = comm.id LEFT JOIN sys.extended_properties ep ON col.id = ep.major_id AND col.colid = ep.minor_id AND ep.name = 'MS_Description' LEFT JOIN sys.extended_properties epTwo ON obj.id = epTwo.major_id AND epTwo.minor_id = 0 AND epTwo.name = 'MS_Description' WHERE obj.name = @TableName--表名 AND col.name LIKE '%'+@KeyWord+'%' ORDER BY col.colorder ; declare @lie0 nvarchar(50), @lie1 nvarchar(50), @lie2 nvarchar(50), @lie3 nvarchar(50), @lie4 nvarchar(50) declare mycursor cursor for select* from #Temp open mycursor while 1=1 begin fetch next from mycursor into @lie0,@lie1,@lie2,@lie3,@lie4 if @@fetch_status <>0 break print @lie1+char(10)+@lie2+char(10)+@lie3+char(10)+@lie4+char(13); end close mycursor; deallocate mycursor; END
3). 調用存儲過程
exec Sys_ViewModel 'Catalogue',''
83.get set 的理解:https://www.jb51.net/article/37960.htm
84. 站點目錄下怎麼指定favicon.ico圖標, <link rel="icon" href="~/favicontest1.ico">
85. 詳解C#中==、Equals、ReferenceEquals的區別
86. var where = new StringBuilder(30, 30 * itemId.Length); //設置合適的初始長度,能夠顯著提升效率(避免了屢次內存申請)
87. 使用C#實現字符串反轉算法,例如:輸入"12345", 輸出"54321"
public static string Reverse(string str) { if (string.IsNullOrEmpty(str)) { throw new ArgumentException("參數不合法"); } StringBuilder sb = new StringBuilder(str.Length); //注意:設置合適的初始長度,能夠顯著提升效率(避免了屢次內存申請) for (int index = str.Length - 1; index >= 0; index--) { sb.Append(str[index]); } return sb.ToString(); } public static string Reverse(string str) { if (string.IsNullOrEmpty(str)) { throw new ArgumentException("參數不合法"); } char[] chars = str.ToCharArray(); int begin = 0; int end = chars.Length - 1; char tempChar; while (begin < end) { tempChar = chars[begin]; chars[begin] = chars[end]; chars[end] = tempChar; begin++; end--; } string strResult = new string(chars); return strResult; } 還有一個比較簡單也挺有效的方法: public static string Reverse(string str) { char[] arr = str.ToCharArray(); Array.Reverse(arr); return new string(arr); }
88. 布式id生成器: http://www.javashuo.com/article/p-axnbwgvt-ma.html http://www.javashuo.com/article/p-uzspcxqi-hd.html
89.C# 獲取時間戳 參考:http://www.javashuo.com/article/p-fihdmjbs-hk.html
public static int ToTimeStamp(this DateTime time) { DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); var result = (int)(time - startTime).TotalSeconds; return result; } public static long ToJavascriptTimestamp(this DateTime input) { var reuslt = ((input - new DateTime(1970, 1, 1, 0, 0, 0, 0)).Ticks / 10000); //毫秒 return reuslt; }
var currentTime = DateTime.Now;//2019/10/8 16:17:15 var result1 = DateTimeExtend.ToTimeStamp(currentTime);//1570522635 var result2 = DateTimeExtend.ToJavascriptTimestamp(currentTime);//1570551435012
對比js
var currentTime = new Date('2019/10/8 16:17:15'); var result1 = Date.parse(currentTime);//1570522635000 var result2 = currentTime.valueOf();//1570522635000 var result3 = currentTime.getTime();//1570522635000
90.AutoMapper和EmitMapper