TOP

[C#]Get DataView Value(取DataView欄位資料)


取得DataView欄位資料的方式:

        DataView dv  = new DataView();
        dvOrgMapping = GetData() //在GetData裡面取得資料

        如果要取某一Row內的Name欄位的值

        dv.Table.Rows[i]["Name"].ToString()
        也可以寫成
        dv[0]["Name"].ToString()

        兩個方式是一樣的。

參考資料:http://wangshifuola.blogspot.tw/2010/11/aspnetdataviewindex.html
TOP

[C#]初學Class,如何建立一個簡單的Class,以及field,property的差別。



初學者最常遇到的一個狀況,知道怎麼使用別人已經建立好的Class,但不知道該如何自已建立一個新的Class。
該如何建立一個簡單的Class,以及field,property的差別。

1.先建立一個新的UserDataModel.cs。
(1)新增一層UserDetailModel的class,且使用field/欄位的方式。


public class UserDataModel
{
    public class UserDetailModel
    {
        public string account;
        public string firstName;
        public string lastName;
        public DateTime createDate;
        public string createUser;
    }
}


(2)property/屬性的方式。


public UserDataModel
{
    private DateTime _myBirthday


    public DateTime myBirthday
    {
        get
        {
                return _myBirthday;
        }
        set
        {
            if (Value <= DateTime.UtcNow)
           {
              _myBirthday = Value;
           }
           else
           {
              throw new Exception("Birthday Fail.")
           }
        }
    }


}

(3)property/屬性的方式,將資料存在Session內。

    public static string account
    {
        get
        {
            if (HttpContext.Current.Session["account"] == null)
                return string.Empty;
            else
                return HttpContext.Current.Session["account"].ToString();
        }
        set
        {
            HttpContext.Current.Session["account"] = value;
        }
    }

2.如何將資料存入Class內,使用前一定要先New Class。


    protected void Page_Load(object sender, EventArgs e)
    {

       UserDataModel.UserDetail = SetUser ();
    }


    public static UserDataModel.UserDetailModel SetUser ()
    {

        UserDataModel.UserDetailModel myUser = new UserDataModel.UserDetailModel();
        myUser.account = "UserAccount";
        myUser.firstName= "ABC";
        myUser.lastName= "DEF";
        myUser.createDate= "account";
        myUser.createUser= "ABC";
        return myUser;
    }

參考資料:
http://www.allenkuo.com/EBook5/view.aspx?a=1&TreeNodeID=123&id=279
http://www.allenkuo.com/EBook5/view.aspx?a=1&TreeNodeID=123&id=969



TOP

[C#] Key Value Collection(NameValueCollection、SortedList、Dictionary)

Key Value Collection最重要的用法就是利用Key及值去儲存想要的資料
因為在C# 3.5版本內沒有提供Optional 參數的功能,如果要傳送不固定參數時,會很麻煩。
因此利用Collection的方式記錄參數,就不用擔心非固定參數傳值的問題。

using System.Collections.Specialized;


protected void Page_Load(object sender, EventArgs e)
        {


            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("FirstName", "ABC");
            nvc.Add("LastName", "DEF");
            nvc.Add("Phone", "123456789");
            nvc.Add("Status", "10");

           UpdateNvcData(nvc);
    }

 
public static string UpdateNvcData(NameValueCollection nvc)
    {

       foreach (string i in nvc.Keys)
          {
            Console.WriteLine("Key:{0}", i)
            Console.WriteLine("Value:{0}",  nvc.GetValues(i))
           }

    }



NameValueCollection
參考資料:
http://www.dotblogs.com.tw/yc421206/archive/2009/04/06/7886.aspx

SortedList
參考資料:
http://msdn.microsoft.com/zh-tw/library/system.collections.sortedlist(VS.80).aspx
http://www.dotblogs.com.tw/chris0920/archive/2010/03/24/14205.aspx

Dictionary
參考資料:
http://blog.csdn.net/sunnykaho/article/details/4435568
TOP

[C#] C# 4.0 Optional Parameters VS C#3.5 SortedList 替代Optional Parameters (變動參數)

很殘酷的問題,因為無法將專案升級到C#4.0 (VS2010)開發的原因,造成最新的 Optional Parameters功能無法使用,只好找替代方案解決這個問題。

C#3.5未提供Optional Parameters的方式,因此使用SortedList的方式輸入參數值。


            SortedList mySL = new SortedList();
            mySL.Add("First", "Hello");
            mySL.Add("Second", "World");
            mySL.Add("Third", "!");
            PrintKeysAndValues(mySL);


        public static void PrintKeysAndValues(SortedList myList)
        {
            Console.WriteLine("\t-KEY-\t-VALUE-");
            for (int i = 0; i < myList.Count; i++)
            {
                Console.WriteLine("\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i));
            }
            Console.WriteLine();
        }



參考資料:
http://msdn.microsoft.com/zh-tw/library/system.collections.sortedlist(VS.80).aspx
http://www.dotblogs.com.tw/chris0920/archive/2010/03/24/14205.aspx

C# 4.0 Optional Parameters 
參考資料:
http://www.dotblogs.com.tw/larrynung/archive/2009/07/29/9720.aspx


相同的變動參數,但如果是不清楚有多少個相同的參數要輸入,就可以使用這個方法。

public static void Main()
{
   ShowName("ABC");
   ShowName("ABC", "DEF");
}

public static void ShowName(params string[] names)
{
   foreach (string name in names)
   {
     Console.WriteLine(name);
    }
}
一維的變動參數參考資料:
http://tw.myblog.yahoo.com/coolong_chen/article?mid=240
TOP

[C#]用txt增加Exception Log檔(FileStream,StreamReader,StreamWriter)

因為系統一直出現無法理解的Exception ,因此增加Exception 的模組來記錄。
string ExceptionFileName = "D:\\Exception.txt";
//利用File.Exists判斷是否已經存在該檔案

        if (!File.Exists(ExceptionFileName))
        {
            //利用StreamWriter就可以新增一個txt檔,並且將Exception的資料填寫至txt檔內。
            using (StreamWriter sw = File.CreateText(ExceptionFileName))
            {
                sw.WriteLine("Message={0}。", message);
                sw.Close();
            }
        }
        else
        {
            //已經有這個檔案,因此只開啟這個檔案
            using (StreamWriter sw = new StreamWriter(ExceptionFileName))
            {

                sw.WriteLine("Message={0}。", message);
                sw.Close();

            }
        }


但在這裡就會遇到一個問題了,每次log都會被覆蓋,只保留最後一次的log而已。
因此換另一個方式來處理。

先讀取檔案內的資料。

FileStream FsRead = File.Open(ExceptionFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader Sreader = new StreamReader(FsRead);
string strSr = Sreader.ReadToEnd();
Sreader.Dispose();
FsRead.Dispose();

將讀取出來的資料加上新的錯誤訊息,再回寫至原檔案內。

FileStream FsWrite = File.Open(ExceptionFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter Swriter = new StreamWriter(FsWrite);
Swriter.WriteLine("{0}", strSr);
Swriter.WriteLine("Message={0}。", message);
Swriter.Dispose();
FsWrite.Dispose();

參考資料:http://dnowba.blogspot.tw/2012/07/streamwriter-io.html
http://www.dotblogs.com.tw/yc421206/archive/2009/01/18/6862.aspx

補充:
也可以利用FileMode.Append直接從檔案的最後加上要填寫的資料。

        FileStream FsWrite = File.Open(ExceptionLogFileLocation, FileMode.Append);
        StreamWriter Swriter = new StreamWriter(FsWrite);
        Swriter.WriteLine("Message={0}。", message);
        Swriter.Dispose();
        FsWrite.Dispose();

http://www.dotblogs.com.tw/yc421206/archive/2009/01/18/6862.aspx

TOP

[C#]Select Data into DataView from Database


解決從SQL取得資料後無法直接存至DataView,需從DataSet轉至DataView

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
string sqlstr = "select * from table";
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataView dv = ds.Tables[0].DefaultView;
conn.Close();
da.Dispose();
TOP

[Apple] iframe in ipad safari


目前在開發的程式是使用 的方式。

掛在別人的主機平台上使用產品,因此使用了iframe掛載。

結果遇到IOS6.1版本的 ipad 及 iphone 使用safari瀏灠器時 iframe不受控制的超過原本平台上的網頁寬度。

目前的解決方式是加上<Div>

<div id="scrollee" style="-webkit-overflow-scrolling:touch; overflow: scroll;">
 
 <iframe id="object" height="90%" width="100%" type="text/html" src="http://en.wikipedia.org/">
 </iframe>
</div>


參考網頁:
http://stackoverflow.com/questions/5267996/how-to-properly-display-an-iframe-in-mobile-safari


因為加入Div變成右在IE、Chrome、及Firefox右邊及下面都會多出 scroll
所以將右邊 Y軸Hidden起來,X軸不能Hidden,因為如果Hideen的話在touch上面就不能左右移動了。

<div style=”overflow-x:scroll ;overflow-y:hidden;overflow:-moz-scrollbars-horizontal !important;”></div>

參考網頁:
http://blog.xuite.net/linriva/blog/52358732-%5BCSS%5DDiv+with+Scroll+bar+~++%E8%BD%89%E8%B2%BC
TOP

[C#] Select Data into DataTable from Database


最主要是要將資料取得的資料存在DataTable。

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string sqlstr = "select * from " + strtable;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
da.Dispose();

參考資料:http://www.wretch.cc/blog/s0341969/33051318
TOP

[C#] Insert Data to DataBase with SQL Parameter

使用Parameter 最主要的原因是為了防止SQL Injection

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string strSql = "insert into Table (Name,Id)";
strSql += "VALUES (@Name, @Id)";
conn.Open();
SqlCommand sqlcom = new SqlCommand(strSql, conn);
sqlcom.Parameters.AddWithValue("@Name", Name);
sqlcom.Parameters.AddWithValue("@Id", Id);
SqlDataReader sqldr = sqlcom.ExecuteReader();
sqldr.Close();
conn.Close();
TOP

[C#]SQL Parameter defense SQL injection

最容易被SQL injection 的語法如下:

SqlConnection conn = new SqlConnection("");
conn.ConnectionString =    System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string sqlstr = "select * from table where name = '" + strName + "'";
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlstr, conn);
conn.Close();
da.Dispose();

目前利用SQL Parameter 就可以避免此問題

SqlConnection conn = new SqlConnection("");
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string strSql = "select * from table where Name=@Name";
conn.Open();
SqlCommand sqlcom = new SqlCommand(strSql, conn);
sqlcom.Parameters.AddWithValue("@Name", strName );
SqlDataReader sqldr = sqlcom.ExecuteReader();
sqldr.Close();
conn.Close();