發表文章

目前顯示的是有「C#」標籤的文章

【C#】MVC WEB API 語法架構

 ASP.NET WEB API架構是以.NET Framework基礎,可用來建置RESTful 【註1】 應用程式,可建置HTTP服務並提供用戶端瀏覽器和行動裝置應用程式使用。 WEB API相較於Web Services和WCF來說,Web Services和WCF的資料內容不易辨識且傳送資料過於肥大,而WEB API提供XML和JSON的傳輸格式,同時可透過HTTP操作方法GET、POST、PUT、DELETE來操作服務,並提供輕量化與跨平台的特性。 本篇透過範例方式建立支援CRUD操作WEB API,在 Controllers加入控制器"具有讀取/寫入 Web Api 2" 之WEB API控制器。 部分WEB API控制器之程式碼(CustomerController.cs僅供參考)︰ using System.Linq;        //引用命名空間-LINQ using prjView.Models;  //引用命名空間-專案名稱.Models public class CustomerController : ApiController         //WEB API必須繼承自ApiController類別。 {      dbCustomerEntities db=new dbCustomerEntities();   //建立存取資料庫類別物件db        //當瀏覽器輸入「http://localhost/api/Customer」,會對此WEB API發出Get請求,Action方法回傳查詢結果            // GET: api/Customer      public List<tCustomer> Get()                         {     ...

【C#】解決MVC WEB API執行,出現404找不到資源

圖片
在MVC專案中新加入WEB API功能,在 Controllers加入控制器"具有讀取/寫入 Web Api 2" , 第一次加入後假設加入"Customer"(範例參考),會跳出一個txt檔。 專案中的 Global.asax.cs 檔案需做調整,才能正常啟用ASP.NET Web API 。 1.新增下列命名空間參考︰   using System.Web.Http;   using System.Web.Routing; 2.Application_Start()方法,加入下方 標示藍色字體 的方法且位置要在AreaRegistration.RegisterAllAreas()之後,RouteConfig.RegisterRoutes(RouteTable.Routes)之前︰ protected void Application_Start() {     AreaRegistration.RegisterAllAreas();     GlobalConfiguration.Configure(WebApiConfig.Register);    // web api擺放位置     RouteConfig.RegisterRoutes(RouteTable.Routes); }   執行畫面(調整前)︰ 執行畫面(調整後)︰

【C#】ADO.NET 常用資料存取用法

程式碼(Sample): using System.Data;                      //使用ADO.NET,引用命名空間 using System.Data.SqlClient;    //使用ADO.NET,引用命名空間 //(方法一)連接SQL Server資料庫檔案 //constr連接字串指定連接dbStudent.mdf資料庫   string constr = @"Data Source= (LocalDB)\MSSQLLocalDB ;" +                                     "AttachDbFilename=|DataDirectory| dbStudent.mdf ;" +                                     "Integrated Security=True";    //(方法二)連接SQL Server資料庫來源  //使用SqlClient進行SQL Server驗證   //string constr = @"Server= localhost ;Database= Student ;uid= sa_test ;pwd= test1234 ;Persist Security Info=False";    //使用SqlClient進行Windows驗證   //string constr = @"Server= localhost ;Database= Student ;Persist Security Inf...

【C#】讀取CSV文中包含逗號(,)的例外處理

圖片
CSV Sample內容: "F0406891","2017/01","E-0221","260041","wo","1.20000004768372"    "F0406892","2017/02","E-0221","260041"," wo,ac ","2.30000004768356"   部分程式碼(Sample): //先用\n把資料分行 string[] CSVSec=CSV.Split('\n'); .... 省略之 ... //逐行抓出結果,並切割後排除事廢排除項目 for(int i=0;i<CSVSec.Length;i++) {      //先判斷雙引號(")中的字串是否含有逗號(,),需做特別處理      string[] CSVItem = CSVstrToArry (CSVSec[i]);     .... 省略之 ... } 函式: #region  先判斷雙引號(")中的字串是否含有逗號(,),需做特別處理 /// <summary> /// 跳過引號中的逗號,進行逗號分隔(字段內容中的逗號不加入分隔) /// </summary> /// <param name="strLine"></param> /// <returns></returns> public static string[] CSVstrToArry (string splitStr) {     var newstr = string.Empty;     List<string> sList = new List<string>();     bool isSplice = false;     string[] array = splitStr.Split(new char[] { ',' });     foreach (var str in a...

【JQuery】BlockUI燈箱(LightBox)效果

使用JQuery前,需要引用Jquery元件及BlockUI元件 。 BlockUI燈箱與先前介紹的 FancyBox燈箱 功能效果是一樣的,但就擴充性應用來說,FancyBox燈箱略勝一籌,本人也比較偏愛使用,但為何要介紹呢? 因為工作上維護別人寫的系統,進而去了解熟悉BlockUI燈箱插件語法,詳細語法詳見 官網 。 ● 載入目前進度 HTML(參考): <!-- 載入目前進度 start --> <div id="maskprogress" class="maskprogress">   //此DIV 預設隱藏 display:none;     <table style="text-align:center; width:35%; height:100%; vertical-align:middle">         <tr>             <td style="height:45%">             </td>         </tr>         <tr>             <td style="background-color:White; height:10%; vertical-align:middle; text-align: center;">                 <asp:Image ID="img_load" runat="server" ImageUrl="~/images/ajax-loading.gif" />   //載入圖片             </td>   ...

【C#】Class類別–子類別覆寫父類別同名的屬性與方法

圖片
設定父類別可以被覆寫的方法為 virtual 設定子類別覆寫父類別同名的方法為 override 如果子類別想加強父類別的方法,卻不想重新撰寫父類別中相同程式,只要在子類別中的方法呼叫父類別,並加上 base 語法( base.方法或base.屬性 )即可。 延伸 : Class(類別)應用 範例作強化 程式碼:     class Employee // 定義Employee員工類別     {         //_salary宣告為Protected保護層級,此欄位可以在子類別中使用         protected int _salary;         //底薪20000~40000         public virtual int Salary         {             get             {                 return _salary;             }             set             {                 if ((value >= 20000) & (value <= 40000))                 {                     ...

【C#】ListView內容輸出到Word

假設條件:ListView繫結於SqlDataSource1   if (ListView1.Items.Count > 0)   //判斷ListView是否有資料 {   StringWriter sw = new StringWriter();   HtmlTextWriter hw = new HtmlTextWriter(sw);   Response.Clear();   Response.Buffer = true;   Response.ContentEncoding = System.Text.Encoding.UTF8;   Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", DateTime.Now.ToFileTimeUtc() + ".doc" , System.Text.Encoding.UTF8));   Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");   Response.ContentType = " application/vnd.ms-word ";   ListView1.RenderControl(hw);   Response.Write(sw.ToString());   Response.End(); } else {   ScriptManager.RegisterClientScriptBlock(this, typeof(string), "alert", "alert('沒有任何資料可輸出!');", true); }

【C#】Interface(介面)應用

圖片
由於C#只有單一繼承,若要使用多個類別中的方法時,可以透過Interface方式來實現。 介面的宣告方法: Interface中不能包含方法的實作 Interface 介面名稱{    介面方法 } 範例程式碼:     interface IFly //定義IFly介面      {         void Fly(int n); //宣告Fly方法     }     class Car : IFly     //Car類別實作IFly介面     {         public void SpeedUp(int n)         {             Console.WriteLine("車子加速前進 {0} 公里", n);         }         //Car類別的Fly方法實作IFly介面的Fly方法         public void Fly(int n)         {             Console.WriteLine("車子飛上天前進 {0} 公里", n);         }     }     class Bird : IFly //Bird類別實作IFly介面     {         public void Eat(int n)         {             Console.WriteLine...

【C#】Class(類別)應用

圖片
這陣子到台大資工所上.net C#課程,本人覺得不錯的題目會放上來,供日後工作所需之參考應用。 題目: □ 建立empolyee 類別 □ 類別中含有baseSalary(底薪)、salary(薪水) 及benefit(獎金)屬性 □ baseSalary 屬性必須大於等於0 □ salary 為唯讀屬性,其值為baseSalary 加上benefit   程式功能: ■ 主程式中請使用者輸入底薪及獎金值 ■ 列印出類別salary 屬性值 程式碼:       class empolyee         {             public int baseSalaryField; //欄位             public int baseSalary //類別屬性 (property)             {                 get                 {                     return baseSalaryField;                 }                 set                 {                     //判斷設定值         ...

【C#】@符號的多種使用方式

1. 當成限定字串時,加在字串前面表示其中的轉義字元“不”被處理。 Ex︰寫/讀 一個特定路徑檔案 (不加@寫法) string fileName= "D:\\Jason\\test_log.txt"; (加@寫法)  string fileName= @ "D:\Jason\test_log.txt";  2. 當連接符號讓字串跨行,詳 MyBlog:【C#】換行、連接符號 。 3. 當識別字中的用法,C#是不允許關鍵字作為識別字(類名、變數名、方法名、表空間名等)使用的,但如果加上@之後就可以了。 Ex︰ string @ string="Jason"; int @ int = 123456789;

【C#】換行、連接符號

寫程式過程中,會遇到需要串很多字串或一行中需要寫很長,為了增加閱讀及維護性,通常會採用換行、連接符號。 範例參考︰ 1. 使用【 + 】符號   -  連接符號 string strSQL= "SELECT * FROM Flight_Schedule AS F"                          + " INNER JOIN System_Code AS S"                          + " ON F.Formno = c.Code_Desc1"                          + " ORDER BY F.Formno";                 2.使用【 @ 】符號 -  連接符號 string strSQL= @" SELECT * FROM Flight_Schedule AS F                                 INNER JOIN System_Code AS S                                 ON F.Formno = c.Code_Desc1                      ...

【ASP.NET】VB、C#在同一個專案內共用VB/C#類別

圖片
● 首先,在Web.Config中<system.web></system.web>加入以下語法 ● 在App_Code中分別建立兩個資料夾VB跟CSharp。接著並針對VB、CSharp各建立一個類別(僅供參考Class1.cs及Class2.vb) ● Class1.cs程式碼(僅供參考) ● Class2.vb程式碼(僅供參考) ● 最後,呼叫部份分別針對VB、CSharp各建立一個Aspx頁面(僅供參考Default.aspx及Default2.aspx) ● CSharp呼叫vb類別頁面(僅供參考Default.aspx及Default.aspx.cs) ● vb呼叫CSharp類別頁面(僅供參考Default2.aspx及Default2.aspx.vb)

【C#】Enum(列舉)應用

圖片
說明 : enum 關鍵字用來宣告列舉型別 (Enumeration),是由一組名為列舉值清單的具名常數所構成的獨特型別 。 public enum Days { 禮拜一 = 1, 禮拜二 = 2, 禮拜三 = 3, 禮拜四 = 4, 禮拜五 = 5, 禮拜六 = 6, 禮拜日 = 7 }; public enum engDays { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }; static void Main(string[] args) {        int nValue = (int)Enum.Parse(typeof(engDays), "Friday");  // 結果: 5        //與上句結果一樣  int nValue = (int)engDays.Friday;        string strDays = Enum.GetName(typeof(Days), nValue);    // 結果: 禮拜五        Console.WriteLine(strDays);  //輸出變數        Console.ReadLine();  //讓視窗暫停 } 執行畫面 :

【C#】字串有效轉成超連結

圖片
透過正規化表示式有效的判斷 RegularExpressionValidator,將含有Http(s)字串轉成HyperLink表示之 Aspx頁面(部份程式碼參考) : 置入一個標籤及一個按鈕     <asp:Label ID="Label1" runat="server" Text="網址 http://blog.xuite.net 是嗎?"></asp:Label>                    <br /><br /><br />       <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="轉換" />   CS程式碼(參考) :    if ( Regex.Match(this.Label1.Text, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?") != Match.Empty )      {                    Response.Write("原始網址字串 : " + Regex.Match(this.Label1.Text, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?").Value );         this.Label1.Text = Regex.Replace(this.Label1.Text, @"(?<link>http(s)?://([...

【ASP.NET】DB連線字串參考

連接 SQL Server 方式一: .NET Framework Data Provider for SQL Server Type: .NET Framework Class Library Usage: System.Data.SqlClient.SqlConnection Manufacturer: Microsoft Ex1: Data Source=192.168.0.1;Initial Catalog=testDB;User Id=sa;Password=12345; Ex2: Server=192.168.0.1;Database=testDB;User ID=sa;Password=12345;Trusted_Connection=False; 方式二(SQL Server 2008 Express): SQL Server Native Client 10.0 OLE DB Provider Type: OLE DB Provider Usage: Provider=SQLNCLI10 Manufacturer: Microsoft Ex: Provider=SQLNCLI10;Server=192.168.0.1;Database=testDB;Uid=sa; Pwd=12345; ------------------------------------------------------------------------------------------------ 連接 Access 方式一(*.accdb): ACE OLEDB 12.0 Type: OLE DB Provider Usage: Provider=Microsoft.ACE.OLEDB.12.0 Manufacturer: Microsoft Ex: Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\db\myAccess.accdb;Persist Security Info=False; 方式二(*.mdb, *.accdb): Microsoft Access accdb ODBC Driver Type: ODBC Driver Usage: Driver={Microsoft Access Driver (*...

【ASP.NET】GridView 頁碼換成上下頁模式

圖片
只要在Aspx檔案內<asp:GridView ID="GridView1".....> 插入頁碼模式語法 </asp:GridView> 插入頁碼模式語法: 文字模式 <PagerSettings                   Mode = "NextPreviousFirstLast"                   FirstPageText = "第一頁"                   PreviousPagetext="上一頁"                   NextPagetext="下一頁"                   LastPageText = "末頁"> </PagerSettings> OR 圖片模式 <PagerSettings                 Mode = "NextPreviousFirstLast"              ...

【ASP.NET】在GridView中加入自動編號的序號

圖片
在Aspx檔案中GridView表格內插入一個欄位,在第一欄加上TemplateField的欄位,語法如下: 流水號從第一筆編起   <asp:TemplateField HeaderText="序號">           <ItemTemplate>              <%# GridView1.PageIndex * GridView1.PageSize + GridView1.Rows.Count + 1 %>            </ItemTemplate>            <HeaderStyle Wrap="False"  />             <ItemStyle  HorizontalAlign="Center" VerticalAlign="Middle" />   </asp:TemplateField> OR   <asp:TemplateField HeaderText="序號">          <ItemTemplate>             <%# Container.DataItemIndex + 1 %>          </ItemTemplate...