2013年5月28日 星期二

[C#] Linq extension: GroupJoin By

///查詢每個月需要用膳的數目
///GroupJoin by CheckInOn月份,
var B = db.Reservations.Where(x => x.IsDinner == true);
var _dinnerInfo = A.GroupJoin( B,
                 x => x, //母體Ajoin key
                 y => y.CheckInOn.Month, //子體Bjoin key
                 (x, y) =>
                 new
                 {
                    Month = x,
                    IsDinner = "需要用餐的訂房數",
                    Count = y.Count()
                  });

[C#] Linq extension: Group By

GROUP BY 範例(1)

from a in SM_ISET_PARAM_Ds
where a.SYS_ID=="TM"
group a by new {a.SYS_ID, a.PARAM_ID} into p
select p

GROUP BY 範例(2) :  使用Linq Extension

///取得目前Reservations裡面所有有訂房紀錄的房號
//Group by RoomId
var _rooms = db.Reservations.GroupBy(x => x.RoomId).
Select(
group => new
{
RoomId = group.Key
}).OrderBy(x => x.RoomId);


GROUP BY 範例(3) :  使用Linq Extension

///取得某房號某月份的訂房次數
///Select RoomId, COUNT(1) as ResCount
///from db.Reservations
///WHERE SUBSTRING(CheckInOn,1,6)=months[i]
///Group by RoomId
var _roomInfo =
db.Reservations.
Where(x => x.RoomId == _room.RoomId).
Where(y => (
y.CheckInOn.Year == _year && y.CheckInOn.Month==_mon)).
GroupBy( x => x.RoomId).
Select(
group => new
{
RoomId=group.
Key,
ResCount = group.
Count()
});

PS. 使用關鍵字Key來取得Group By的欄位值
PS. 使用關鍵字Count()來做計數


GROUP BY 範例(4) :  使用Linq Extension

///查詢每個月需要/不需要用膳的數目
///Group by CheckInOn月份, IsDinner
int _year = DateTime.Now.Year;
var _dinnerInfo =
db.Reservations.
Where(x => x.CheckInOn.Year == _year).
GroupBy(x => new { mon = x.CheckInOn.Month, IsDinner = x.IsDinner }).
Select(
   group => new
   {
        Month = group.Key.mon,
        IsDinner = group.Key.IsDinner,
        Count = group.Count()
}).OrderBy(x => x.Month);

PS. 此範例Group by兩個欄位
PS. 如果Group by的欄位超過一個,請使用 Key.{欄位名稱} 來取得值

2013年5月24日 星期五

[C#] Enum用法

public enum EnumWeek
{
        Monday=1,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday = 0
}


///將字串轉換成Enum
var day1 = (EnumWeek)Enum.Parse(typeof(EnumWeek), "monday", true);
var day2 = (EnumWeek)Enum.Parse(typeof(EnumWeek), "tuesday", true);
var day7 = (EnumWeek)Enum.Parse(typeof(EnumWeek), "sunday", true);

//取得Enum的值(字串)
Console.WriteLine(day1.ToString());
Console.WriteLine(day2.ToString());
Console.WriteLine(day7.ToString());

//取得Enum的值(數字)
Console.WriteLine((int)day1);
Console.WriteLine((int)day2);
Console.WriteLine((int)day7);



Output :

Monday
Tuesday
Sunday
1
2
0

2013年4月24日 星期三

[ASP.NET] 使用IIS Express開發

常常開發Web系統上遇到在本機執行沒有問題,但是部屬到正式環境就有問題的情況。
此時可以考慮採用IIS Express來做開發與測試,

請參考保哥的文章
ASP.NET 開發人員應使用 IIS Express 進行開發與測試

到專案屬性裡面,將[Web]頁籤裡面的[伺服器]設定為使用IIS Express偵錯



點選[建立虛擬目錄]按鈕後,相關Site設定便會寫入到預設的Config檔:
C:\Users\[使用者名稱]\Documents\IISExpress\config\applicationhost.config

<Site></Site> 標籤就會多出一組開發中 Site的設定,例如


<site name="WebApplication1" id="3">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="D:\WORK\CODE\Visual Studio 2010\Projects\WebApplication1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:4863:localhost" />
                </bindings>
            </site>



打開Command,先指到IIS Express資料夾路徑 (預設  C:\Program Files (x86)\IIS Express)
再打入  iisexpress.exe /site:[Site名稱]
此例是  iisexpress.exe /site:WebApplication1

Command就會出現以下訊息,表示已經啟動IIS Express ...

C:\Program Files (x86)\IIS Express>iisexpress.exe /site:WebApplication1
Starting IIS Express ...
Successfully registered URL "http://localhost:4863/" for site "WebApplication1"
application "/"
Registration completed for site "WebApplication1"
IIS Express is running.
Enter 'Q' to stop IIS Express



打開瀏覽器後,打入我們設定好的網址和PORT,就可以看到我們的網站。
也可以在Command即時看到相關Http的訊息。


2013年4月17日 星期三

[C#] 設定程式使用權限


原來程式碼也是可以設定使用權限的~~
雖然實務上不曾用過,不過還滿有趣的。

1.
使用Windows登入腳色
2. 使用自訂使用者

一、                使用Windows登入腳色
l   在需要設定呼叫權限的Class (或方法) 加上以下Attribute
[PrincipalPermission(SecurityAction.Demand, Role = @"Administrator")]
class MyClass
{
  …
}
表示只有登入者為Administrator才有權限。

l   在主程式使用此Class時,需先宣告並設定目前識別的方法為Windows登入腳色:
//設定目前執行緒識別的方法:對應Windows登入腳色AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
try
{
  using (MyClass score = new Score())
  {  //
取出所有學生成績
  
}
}
catch (SecurityException ex)
{
  Console.WriteLine(ex.Message);
}

※若登入腳色非Administrator,則會引發SecurityException : 主要使用權限的要求失敗。
[PrincipalPermission]  Attribute只能加在 Class or Method

l   結束

二、                使用自訂使用者
l   MyClass的建構函式(或是要限制的方法)中,先加入以下程式碼判斷目前執行緒的使用腳色是否有權限:
public MyClass()
{

  
try
   
{
        //
設定主體的所需權限的群組/使用者/腳色
       
PrincipalPermission MyPermission = new PrincipalPermission ("Teacher");
        //
判斷權限是否足夠
       
MyPermission.Demand();
       
        //
Iniitial ...
   
}
    catch (Exception)
    { throw; }
  }

若目前執行緒設定的使用者/腳色非 Teacher,則會引發SecurityException : 主要使用權限的要求失敗。

l   在主程式設定目前執行緒的使用者/腳色,再宣告MyClass物件:

//Create a GenericIdentity object with no authentication type specified.
//
設定泛用無權限使用者 : ExamUser
GenericIdentity examIdentity = new GenericIdentity("DefaultUser");

//
目前使用者腳色
String[] users = new String[2] { "Teacher", "Student" };
//String[] users = new String[1] { "Student" };

//
設定泛用的主體(泛用使用者, 目前腳色)
GenericPrincipal examPrincipal = new GenericPrincipal(examIdentity, users);

//
設定目前執行緒的原則
Thread.CurrentPrincipal = examPrincipal;

try
{
     //
使用MyClass
     using (MyClass _myclass = new MyClass())
     {   //…
    
}
 }

當主程式設定的users包含Teacher,則可正常宣告及使用MyClass ,若只設定使用者為Student則會造成權限失敗。
l   結束。