參考網址
https://www.dotblogs.com.tw/mis2000lab/archive/2015/06/29/npoi_2131_sample_export_to_excel.aspx
2015年12月16日 星期三
2015年8月21日 星期五
[C#]使用泛型實作Entity Framework DbContext的增修刪查
參考
利用EF和C#泛型实现通用分页查询
Entity與DataTable互轉
Entity Framework 5 Updating a Record
回傳結果
public class Return_Msg
{
public bool Status;
public string Message;
public Return_Msg(bool status, string message)
{
Status = status;
Message = message;
}
}
1.新增
public Return_Msg InsertData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Add(entity);
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.InsertData<Sys_Menu>(menu);
2.修改
public Return_Msg UpdateData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Attach(entity);
var entry = context.Entry(entity);
context.Entry(entity).State = EntityState.Modified;
// other changed properties
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.UpdateData<Sys_Menu>(menu);
3.刪除
public Return_Msg DeleteData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Remove(entity);
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.DeleteData<Sys_Menu>(menu);
4.查詢
依條件查詢
public DataTable GetDataByWhere<T>(Expression<Func<T, bool>> predicate) where T : class
{
using (var context = new DbContext())
{
return EntityToDataTable<T>(context.Set<T>().Where<T>(predicate).AsEnumerable<T>());
}
}
用法:DataTable dt = dbService.GetDataByWhere<Sys_Menu>(p => p.MenuName.Contains(txtMenuName.Text));
單一Table全部資料
public DataTable GetDataAll<T>() where T : class
{
using (var context = new HDContext())
{
return EntityToDataTable<T>(context.Set<T>().AsEnumerable());
}
}
用法:DataTable dt = dbService.GetDataAll<Sys_Menu>();
利用EF和C#泛型实现通用分页查询
Entity與DataTable互轉
Entity Framework 5 Updating a Record
回傳結果
public class Return_Msg
{
public bool Status;
public string Message;
public Return_Msg(bool status, string message)
{
Status = status;
Message = message;
}
}
1.新增
public Return_Msg InsertData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Add(entity);
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.InsertData<Sys_Menu>(menu);
2.修改
public Return_Msg UpdateData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Attach(entity);
var entry = context.Entry(entity);
context.Entry(entity).State = EntityState.Modified;
// other changed properties
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.UpdateData<Sys_Menu>(menu);
3.刪除
public Return_Msg DeleteData<T>(T entity) where T : class
{
Return_Msg r = new Return_Msg(true, string.Empty);
using (var context = new DbContext())
{
try
{
context.Set<T>().Remove(entity);
context.SaveChanges();
}
catch (Exception e)
{
r.Status = false;
r.Message = e.ToString();
}
}
return r;
}
用法:Return_Msg r = dbService.DeleteData<Sys_Menu>(menu);
4.查詢
依條件查詢
public DataTable GetDataByWhere<T>(Expression<Func<T, bool>> predicate) where T : class
{
using (var context = new DbContext())
{
return EntityToDataTable<T>(context.Set<T>().Where<T>(predicate).AsEnumerable<T>());
}
}
用法:DataTable dt = dbService.GetDataByWhere<Sys_Menu>(p => p.MenuName.Contains(txtMenuName.Text));
單一Table全部資料
public DataTable GetDataAll<T>() where T : class
{
using (var context = new HDContext())
{
return EntityToDataTable<T>(context.Set<T>().AsEnumerable());
}
}
用法:DataTable dt = dbService.GetDataAll<Sys_Menu>();
2015年8月6日 星期四
2015年7月19日 星期日
[C#]取得類別成員的屬性
參考
How do I get the custom attribute value of a field? [duplicate]
以取得字串最大長度為例子,取得成員的StringLength屬性
程式碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace RetriveClassAttribute
{
class Program
{
static void Main(string[] args)
{
foreach (var prop in typeof(RetriveClassAttribute).GetProperties())
{
var attrs = (StringLengthAttribute[])prop.GetCustomAttributes
(typeof(StringLengthAttribute), false);
foreach (var attr in attrs)
{
Console.WriteLine("{0}: {1}", prop.Name, attr.MaximumLength);
}
}
Console.ReadLine();
}
}
class RetriveClassAttribute
{
[StringLength(30)]
public string FirstMember { get; set; }
}
}
How do I get the custom attribute value of a field? [duplicate]
以取得字串最大長度為例子,取得成員的StringLength屬性
程式碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace RetriveClassAttribute
{
class Program
{
static void Main(string[] args)
{
foreach (var prop in typeof(RetriveClassAttribute).GetProperties())
{
var attrs = (StringLengthAttribute[])prop.GetCustomAttributes
(typeof(StringLengthAttribute), false);
foreach (var attr in attrs)
{
Console.WriteLine("{0}: {1}", prop.Name, attr.MaximumLength);
}
}
Console.ReadLine();
}
}
class RetriveClassAttribute
{
[StringLength(30)]
public string FirstMember { get; set; }
}
}
2015年7月15日 星期三
[C#]WCF Service 傳遞XML Data
參考
逐步解說:建立和存取 WCF 服務
WCF服務程式庫與WCF服務應用程式的不同
WCF服務應用程式原始碼
ISendXmlWcfService.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Xml.Linq;
namespace SendXmlWcfService
{
public class SendXmlWcfService : ISendXmlWcfService
{
public string GetData(string value)
{
XDocument xml = XDocument.Parse(value);
return string.Format("To {0}\r\n {1}\r\n {2} {3}", xml.Root.Element("to").Value, xml.Root.Element("body").Value,xml.Root.Element("heading").Value,xml.Root.Element("from").Value);
}
}
}
逐步解說:建立和存取 WCF 服務
WCF服務程式庫與WCF服務應用程式的不同
WCF服務應用程式原始碼
ISendXmlWcfService.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Xml.Linq;
namespace SendXmlWcfService
{
public class SendXmlWcfService : ISendXmlWcfService
{
public string GetData(string value)
{
XDocument xml = XDocument.Parse(value);
return string.Format("To {0}\r\n {1}\r\n {2} {3}", xml.Root.Element("to").Value, xml.Root.Element("body").Value,xml.Root.Element("heading").Value,xml.Root.Element("from").Value);
}
}
}
ISendXmlWcfService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace SendXmlWcfService
{
[ServiceContract]
public interface ISendXmlWcfService
{
[OperationContract]
string GetData(string value);
}
}
測試WCF服務應用程式-主控台應用程式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StringBuilder builder = new StringBuilder("<note>" +
"<to>Tove</to>" +
"<from>Jani</from>" +
"<heading>Reminder</heading>" +
"<body>Don't forget me this weekend!</body>" +
"</note>");
ServiceReference1.SendXmlWcfServiceClient client = new ServiceReference1.SendXmlWcfServiceClient();
Console.WriteLine(client.GetData(builder.ToString()));
Console.ReadLine();
}
}
}
2015年7月8日 星期三
[C#]WebRequest 遠端伺服器傳回一個錯誤: (407) 必須 Proxy 驗證
參考
[WCF]遠端伺服器傳回未預期的回應: (407) Proxy Authentication Reqiured
在Web.config或App.config內加上
<system.net>
<defaultProxy useDefaultCredentials="true"></defaultProxy>
</system.net>
[WCF]遠端伺服器傳回未預期的回應: (407) Proxy Authentication Reqiured
在Web.config或App.config內加上
<system.net>
<defaultProxy useDefaultCredentials="true"></defaultProxy>
</system.net>
2015年6月30日 星期二
[C#]計算Tiff檔頁數,使用BitMiracle.LibTiff.Net
用NuGet下載BitMiracle.LibTiff.Net,Version:2.4.511.0
官方網頁
原始碼如下
using BitMiracle.LibTiff.Classic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculate_Tiff_page_with_BitMiracle.LibTiff.Net
{
class Program
{
static void Main(string[] args)
{
string path = @"C:\Users\owlin\Downloads\test.tif";
using (Tiff image = Tiff.Open(path, "r"))
{
Console.WriteLine(CalculatePageNumber(image));
Console.ReadLine();
}
}
private static int CalculatePageNumber(Tiff image)
{
int pageCount = 0;
do
{
++pageCount;
} while (image.ReadDirectory());
return pageCount;
}
}
}
官方網頁
原始碼如下
using BitMiracle.LibTiff.Classic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculate_Tiff_page_with_BitMiracle.LibTiff.Net
{
class Program
{
static void Main(string[] args)
{
string path = @"C:\Users\owlin\Downloads\test.tif";
using (Tiff image = Tiff.Open(path, "r"))
{
Console.WriteLine(CalculatePageNumber(image));
Console.ReadLine();
}
}
private static int CalculatePageNumber(Tiff image)
{
int pageCount = 0;
do
{
++pageCount;
} while (image.ReadDirectory());
return pageCount;
}
}
}
[C#]FTP上下傳檔案,使用WinSCP
用NuGet下載WinSCP .Net Assembly,Version:5.7.4
官方網頁
原始碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinSCP;
namespace FTP_download_and_upload_with_WinSCP
{
class Program
{
static string ftpUploadUrl = "IP或domain"; //不可以有ftp:\
static string ftpAccount = "Ftp帳號";
static string ftpPassword = "Ftp密碼";
static string localPath = @"D:\temp\";
static string remotePath = "/work/";
static void Main(string[] args)
{
Download();
Upload();
}
private static void Upload()
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = ftpUploadUrl,
UserName = ftpAccount,
Password = ftpPassword,
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.PutFiles(localPath + "*", remotePath, true, transferOptions); //*表示全部檔案
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
session.Close();
}
}
catch (Exception e)
{
throw e;
}
}
private static void Download()
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = ftpUploadUrl,
UserName = ftpAccount,
Password = ftpPassword,
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.GetFiles(remotePath + "*", localPath, false, transferOptions);//*表示全部檔案
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded", transfer.FileName);
}
session.Close();
}
}
catch (Exception e)
{
throw e;
}
}
}
}
官方網頁
原始碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinSCP;
namespace FTP_download_and_upload_with_WinSCP
{
class Program
{
static string ftpUploadUrl = "IP或domain"; //不可以有ftp:\
static string ftpAccount = "Ftp帳號";
static string ftpPassword = "Ftp密碼";
static string localPath = @"D:\temp\";
static string remotePath = "/work/";
static void Main(string[] args)
{
Download();
Upload();
}
private static void Upload()
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = ftpUploadUrl,
UserName = ftpAccount,
Password = ftpPassword,
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.PutFiles(localPath + "*", remotePath, true, transferOptions); //*表示全部檔案
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
session.Close();
}
}
catch (Exception e)
{
throw e;
}
}
private static void Download()
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = ftpUploadUrl,
UserName = ftpAccount,
Password = ftpPassword,
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.GetFiles(remotePath + "*", localPath, false, transferOptions);//*表示全部檔案
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded", transfer.FileName);
}
session.Close();
}
}
catch (Exception e)
{
throw e;
}
}
}
}
2015年4月18日 星期六
[C#]複寫SignalR OnConnected、OnDisconnected、OnReconnected
若要複寫SignalR Hub的OnConnected、OnDisconnected、OnReconnected
JavaScript
var chat = $.connection.chatHub;
// Need at least one callback for events to be raised on the hub
chat.client.void = function () { };//這行非加不可 否則不會自動執行Server的OnConnected跟OnDisconnected
// Start the connection.
$.connection.hub.start();
JavaScript
var chat = $.connection.chatHub;
// Need at least one callback for events to be raised on the hub
chat.client.void = function () { };//這行非加不可 否則不會自動執行Server的OnConnected跟OnDisconnected
// Start the connection.
$.connection.hub.start();
[C#]SignalR聊天室使用MVC5
參考微軟官方文件
Tutorial: Getting Started with SignalR 2 and MVC 5
新增專案,選擇C# ASP.Net應用程式
選擇MVC範本
變更驗證,若選擇不驗證,則需要自己建立Startup.cs,這邊選擇個別使用者帳戶
工具>程式庫套件管理員>套件管理器主控台,輸入指令安裝SignalR Libraries
install-package Mircosoft.AspNet.SignalR
在專案新增【Hubs】資料夾
在【Hubs】資料夾新增SignalR Hub類別
在【ChatHub.cs】增加Send Method
在【Startup.cs】註冊SignalR設定
在【HomeController】增加Chat的ActionResult
使用SignalR Client需安裝Microsoft.AspNet.SignalR.Client
在View>Home資料夾,增加View
修改【Chat.cshtml】的內容
聊天室展示
Tutorial: Getting Started with SignalR 2 and MVC 5
新增專案,選擇C# ASP.Net應用程式
選擇MVC範本
變更驗證,若選擇不驗證,則需要自己建立Startup.cs,這邊選擇個別使用者帳戶
工具>程式庫套件管理員>套件管理器主控台,輸入指令安裝SignalR Libraries
install-package Mircosoft.AspNet.SignalR
專案將安裝這些套件 |
在【Hubs】資料夾新增SignalR Hub類別
在【ChatHub.cs】增加Send Method
在【Startup.cs】註冊SignalR設定
在【HomeController】增加Chat的ActionResult
使用SignalR Client需安裝Microsoft.AspNet.SignalR.Client
在View>Home資料夾,增加View
修改【Chat.cshtml】的內容
訂閱:
文章 (Atom)