顯示包含「c#」標籤的文章。顯示所有文章
顯示包含「c#」標籤的文章。顯示所有文章

C# ~ parse JSON to dynamic object

這範例是抓取youtube影片的資訊

透過youtube api提供的json來解析取得想要的data

這邊是直接把json轉成dynamic

個人比較喜歡這樣....因為我真的搞不懂.net的Dictionary還是甚麼List的0rz

dynamic寫法就很像php

反正你知道他的json長甚麼樣子再下去寫就好

也不用為此創一個物件去弄些543麻煩要命

所以我討厭寫.net.......php這邊只要json_decode($xxx)就可以把他轉成陣列

真的不用幾秒的時間....

c#這邊則是要透過一堆物件做些奇奇怪怪的事才完成

雖然人家物件導向比較屌.....

但我就是懶....還是prefer用php簡單coding就可達成所要的結果

---------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://gdata.youtube.com/feeds/api/videos/UlNO5CpVbhk?v=2&alt=json";
var webRequest = WebRequest.Create(url);
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
var strContent = reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic d = jss.Deserialize<dynamic>(strContent);
Label1.Text = d["entry"]["yt$statistics"]["viewCount"].ToString();
}
}
}

---------------------------------------------------------

C# ~ is request exists


if (Request.QueryString["xxxx"] != null)
{
// it exists
}
else
{
// it doesn't
}

reference
http://www.velocityreviews.com/forums/t107127-querystring-exists.html

LINQ ~ where like


x = (from r in ctx.xxxxxx
where r.name.Contains("adasdad")
select (new KeyValuePair(r.id.ToString(), r.name))
).ToDictionary(t => t.Key, t => t.Value);


reference
http://stackoverflow.com/questions/5374481/like-operator-in-linq

LINQ ~ where clause example

dynamic labor = ctx.Qoo.Where(l => l.xxxID== xxxID).Select(l => l).ToList().Select(l =>
{
dynamic aaa = new ExpandoObject();
aaa.ooo= l.ooo;
aaa.yyy= l.yyy;
aaa.hhh= l.hhh;
return aaa;
}).ToArray();

reference
http://stackoverflow.com/questions/8663897/why-is-linq-wherepredicate-first-faster-than-firstpredicate

PDF Sharp ~ 亂碼問題

這問題是在對方server輸出pdf

出現亂碼的問題

但由於我們都跑得很正常

所以就推估應該是字型問題

嘗試改了幾個字型確實可以working~~

遇到這問題的就試試看囉

Style style = document.Styles[StyleNames.Normal];
style.Font.Name = "微軟正黑體";

一開始的設定是

style.Font.Name = "Arial Unicode MS";

而人家的Server 2008 R2跑不出來

我們是Win7才如此推估

好在確實是這問題XD


c# ~ ashx get post data


string reportTypeKey = context.Request.Params["reportTypeKey"].ToString();


reference
http://stackoverflow.com/questions/3991894/ashx-c-sharp-for-each-loop-on-post-vars

C# ~ delete file

protected void deleteFile(string fileName) {
string path = Server.MapPath("~/bulletin/");
try {
System.IO.File.Delete(path + fileName);
} catch (System.IO.IOException e) {
return;
}
}

reference
http://msdn.microsoft.com/zh-tw/library/cc148994.aspx

C# ~ output Date from DateTime

txtFrom.Text = string.Format("{0:yyyy/M/dd}", template.ValidDateTime);

reference
http://www.dotblogs.com.tw/skyline0217/archive/2011/01/26/21047.aspx

C# ~ rtrim TrinEnd

作陣列輸出時可能會用個,做區隔

到最後一個輸出的時候都要把多餘的,拿掉

以下是寫法XD

char[] trimchars = { ',', ' ' };
string DiagnosiseText = "";
List<string> DiagnosiseNames = Referral.DiagnosisesNames;
DiagnosiseNames.ForEach(delegate(string i) {
    DiagnosiseText += i + ", ";
});
SetReportValue("DiagnoseName", DiagnosiseText.TrimEnd(trimchars));

C# ~ List example

List<int> ProcessStatusIds = Referral.ReferralSheet_ProcessStatusIDs;
List<string> ProcessStatusOtherTexts = Referral.ReferralSheet_ProcessStatusOtherTexts;
ProcessStatusIds.ForEach(delegate(int i) {
    if (i <= 7) {
        SetReportValue("ProcessStatusID" + i, CheckString);
        switch (i) {
            case 2:
            case 3:
            case 6:
            case 7:
                if (!String.IsNullOrEmpty(ProcessStatusOtherTexts[i])) {
                    SetReportValue("ProcessStatusOtherTexts" + i, ProcessStatusOtherTexts[i]);
                }
                break;
        }
 
    }
});

http://msdn.microsoft.com/en-us/library/bwabdf9z.aspx

C# ~ Send mail example

感謝張睪大大提供code @0@

--------------------------------------------------------------------------------------------

using System.Net.Mail;
using System.Net;


private const string MailHost = "mail.ggyy.com";
private const string MailAccount = "ggyy@ggyy.com";
private const string MailPassword = "ggyy0204";


try
{
SmtpClient smtp = new SmtpClient();
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
smtp.Host = (MailHost);
smtp.Credentials = new NetworkCredential(MailAccount, MailPassword);
msg.From = new MailAddress("xdxd@xdxdxdxdxd.com", "GGYY Notify");
msg.IsBodyHtml = true;
msg.Subject = "GGYY Notify";
msg.Body = string.Format("Hi, this is a test, lol");
msg.To.Add(new MailAddress(Email));
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(msg);
msg.Dispose();

}
catch (Exception ex)
{

}

C# ~ DataTable get column value

public Egg[] GetEggs()
{
string sql = "SELECT TOP 100 * FROM xxxxxxxxxx";
DataTable dt = base.SqlExecuteSelect(sql);
dt.TableName = "ggyy5566";

Egg[] eggs= new Egg[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
Egg egg= new Egg();
egg.Name= dt.Rows[i][1].ToString();
egg.Size= dt.Rows[i][2].ToString();

eggs[i] = egg;
}

return eggs;

}

C# ~ Object array ~

c# ~ object array by List

this example is return GGYY's array from SQL

----------------------------------------------------------------------------------------
public GGYY[] GetGGYY() {

string sql = @"SELECT xxxxxxxxxxxxx";

List<GGYY> GGYYList = new List<GGYY>();
string connectString = ConfigurationManager.ConnectionStrings["GivenConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
try {
SqlDataReader r = cmd.ExecuteReader();
while (r.Read()) {
GGYY item = new GGYY();
item.id = (int)r["ID"];
item.gg = r["gg"].ToString();
item.yy =r["yy"].ToString();
GGYYList.Add(item);
}
r.Close();
} catch (Exception e) {
}
conn.Close();

return GGYYList.ToArray();
}
----------------------------------------------------------------------------------------

C# ~ SQL query

an example query sql by SqlCommand, SqlDataReader, SqlConnection

------------------------------------------------------------------------------------------------
string sql = "select * from ggyy";

string connectString = ConfigurationManager.ConnectionStrings["ggyyConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectString);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
string qq = "";
try {
SqlDataReader r = cmd.ExecuteReader();

while (r.Read()) {
qq += (string)r["fieldName"].ToString();
}
r.Close();

} catch (Exception e) {
qq = e.Message;
}
conn.Close();
------------------------------------------------------------------------------------------------

first time i got message

ExecuteReader requires an open and available Connection. The connection's current state is closed.

because i didn't open the connection.....

conn.Open();

LINQ ~ select COUNT example

int q = (from b in XXXX
where b.PartID == partID
select b).Count();

if (q > 0) {
//blablablablablablablablablablablablablablabla
}else{
//blablablablablablablablablablablablablablabla
}

感謝張搞Q_Q

C# ~ SQL update by SqlExecuteUpdate

感謝張睪Q_Q

const string sql = @"UPDATE Ap_Parts SET Name = @Name, GroupSku = @GroupSku, MainSkuID = @MainSkuID WHERE PartID = @PartID";

bool s = SqlExecuteUpdate(sql, new[] {
new SqlParameter("Name", name),
new SqlParameter("GroupSku", groupSku),
new SqlParameter("MainSkuID", mainSkuID),
new SqlParameter("PartID", partID)
});

LINQ ~ example

今天張睪幫我寫的LINQ.......

我只能說太屌了XD

var blockItem = from b in context.Ap_LobbyBlocks
                            from bi in context.Ap_LobbyParts
                            where b.BlockID == bi.BlockID && bi.ShowOnLobby == true
                            select new BlockItem
                            {
                                key = bi.SkuID.ToString(),
                                imgSrc = bi.Ap_Skus.MainImg,
                                descName = bi.Ap_Skus.DescName,
                                price1 = (decimal)bi.Ap_Skus.Price1,
                                price2 = (decimal)bi.Ap_Skus.Price2,
                                b = bi.BlockID,
                                o = (from op in context.Ap_OptionSkus
                                     where op.SkuID == bi.SkuID
                                    select op.MenuOptionID).First()
                            };

            var block = from b in context.Ap_LobbyBlocks
                        select new Block
                        {
                            key = b.BlockID.ToString(),
                            title = b.Name,
                            items = (from bi in blockItem
                                      where b.BlockID == bi.b 
                                      select bi).ToArray()
                        }; 

ASP.NET SQL~資料庫連線程式~ by c#

因為學弟阿帕...........找到了想當年的專題程式= =

這個是我寫的資料庫連線物件~~~~記得是我寫的吧XD

myConnection.ConnectionString = @"Data Source=163.18.22.142;Initial Catalog=msngps;Persist Security Info=True;User ID=sa;Password=8051";

這段程式是資料庫的連線字串~~~~~

我的設定是
連線163.18.22.142
資料庫msngps
帳號sa
密碼8051


用法.........總覺得好鳥.........因為還要另外創SqlDataReader ..........= =
------------------------------------------------------------------------------------
MyDB mydb = new MyDB();
mydb.Query(sql);
SqlDataReader myReader = mydb.DbFetchArray();

string latitude = "";
string longitude = "";
while (myReader.Read())
{
latitude = myReader.GetString(0);
longitude = myReader.GetString(1);
}


------------------------------------------------------------------------------------

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public class MyDB
{
private SqlConnection myConnection = new SqlConnection();
private SqlCommand myCommand;

public MyDB()
{
myConnection.ConnectionString = @"Data Source=163.18.22.142;Initial Catalog=msngps;Persist Security Info=True;User ID=sa;Password=8051";

myConnection.Open();
}
public void query(string sql)
{
myCommand = new SqlCommand(sql, myConnection);
}
public void executeReader()
{
myCommand.ExecuteReader();
}
public SqlDataReader dbFetchArray()
{
return myCommand.ExecuteReader();
}
public void closeConnect()
{
myConnection.Close();
}
public bool hasRows()
{
SqlDataReader dr = this.dbFetchArray();
if (dr.HasRows)
{
return true;
}
else
{
return false;
}
}
public void closeDB()
{
myConnection.Close();
}

}