2011年12月14日 星期三

jQuery 解決select 下拉被截斷(支援連動兩個select)

找了很久終於找到jquery改變select長度被截斷的問題

原程式網頁的網頁點我

但如果是連動例如DropDownList1連動DropDownList2就必需要用jquery live(邊學邊做系列有教大家可以去看看)

好像要jQuery 1.3.2版後才有這功能喔


2011年12月9日 星期五

心得 蘋果教父賈伯斯的傳奇人生

雖然我不是很喜歡apple產品
但我今天看了"賈伯斯的傳奇人生"
以下是我的心得

賈伯斯的成功原來並不是偶然的

天時:
剛好生在科技產品盛產研發時

地利:
剛好家附近住的都是一些工程師,開啟了他小時的興趣

人和:
1.剛好家附近那些工程師人都很好
2.認識到跟自己一樣的同好

先天條件:好學、多聞、多問、創新、大膽、不同於世

後天培養:語言溝通

自我心得:
我忽然發覺成功的人不會只從是一種工作
而是在做了許多不同工作累計經驗
也許是可以有計劃性的換工作學習技能
但也可能是偶然學到的技能
都無所謂自我本身必需要去"愛"自己每天做的工作
這樣才有辦法將技能學起來
不然技能就只是賺錢的工具罷了
越多技能就需要更多的時間思考整合成一種無與倫比的技能

堅持自己的信念不輕言放棄
別太在意別人的眼光

2011年12月8日 星期四

c# 三位一撇+小數點??位

最近做到有關金額的所以常用
就寫成function 來用比較快

這之前好像有了

///  
/// 判斷是否為數字 
/// 
/// 傳入判斷的字串。
public static bool IsNumeric(String pNumber)
{
Regex NumberPattern = new Regex("[^0-9.-]");
return !NumberPattern.IsMatch(pNumber);
}


/// 
/// 三位一撇 + 小數??位
///  
/// 傳入字串數字。
/// 傳入字串。
public static string ToThree(string pInt,string p0)
{

string mReturn = string.Empty;

if (pInt != "")
{
if (IsNumeric(pInt))
{
mReturn = string.Format("{0:N"+ p0+"}", Convert.ToDecimal(pInt));
}
}
else
{
mReturn = string.Format("{0:N" + p0 + "}", "0");

}
return mReturn;
}

2011年12月6日 星期二

Asp.net 關閉子視窗重整父視窗

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", "alert('完成');opener.location.reload();window.close();", true);

2011年12月2日 星期五

Asp.net UrlReWrite[附範例]

忽然想到UrlReWrite這個技術
網路找了一下還蠻多說明的
於是參考文章
http://www.dotblogs.com.tw/chhuang/archive/2008/03/26/2272.aspx
然後幾乎照copy啦
但是還是要自己去理解一下
還有正規表達示也要稍稍去看一下
[簡單範例下載]

2011年12月1日 星期四

Asp.net 匯出假Excel


protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();

System.Text.StringBuilder sb = new System.Text.StringBuilder(); //內容自行新增

string fileName = DropDownList1.SelectedValue.ToString() + DropDownList1.SelectedValue.ToString()+ ".xls";

if (Request.Browser.Browser == "IE")
{
fileName = Server.UrlPathEncode(fileName);
}
string style = " ";

Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName );

//Response.Write("");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Default;//.Unicode;//.UTF8;//

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

//文字格式處理 
Response.Write(style);
Response.Write(sb.ToString());//內容
Response.Write(stringWrite.ToString());
Response.End();
}
以下這段一定要加

public override void VerifyRenderingInServerForm(Control control)
{
//處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
}
ps如放在button放在updatepanel裡

T-SQL 更新主檔總金額(多次付款)

功用

在客戶分多次款可能不會一次付清時,在新增刪除修改時都會去更新到尚欠的金額

StatementList 主檔
StatementItem 明細檔

CX_Total : 原本的總金額
CX_Less_Money : 尚欠尾款
CX_Amount : 明細已付金額



update StatementList set CX_Less_Money = (CX_Total - ( select SUM( CONVERT(Decimal, CX_Amount ) ) from StatementItem where ID_Statement=@ID_Statement)) where ID_Statement =@ID_Statement

2011年11月30日 星期三

c# DatatableTo Linq Group by

找出dt1裡的以尺寸跟顏色來Group by
統計數量

下面是將文字變0

///  
/// 回傳數字Decimal,非數字及空白都變成0 
///  
/// 傳入字串。
public static Decimal ToDecimal(string pInt)
{
Decimal mReturn = 0;
if (pInt == "")
{
mReturn = 0;
}
else
{
if (IsNumeric(pInt))
{
mReturn = Convert.ToDecimal(pInt);
}
else
{
mReturn = 0;
}
}
return mReturn;
}


var QueryA =( from u in dt1.AsEnumerable() 
group u by new { CX_Size = u["CX_Size"], CX_Color_Name = u["CX_Color_Name"] } into g
select new
{
CX_Size = g.Key.CX_Size,
CX_Color_Name = g.Key.CX_Color_Name,
CX_Quantity = g.Sum(p => Convert.ToDecimal(PublicClass.ToDecimal(p["CX_Quantity"].ToString()))),
CX_Amount = g.Sum(p => Convert.ToDecimal(PublicClass.ToDecimal(p["CX_Amount"].ToString())))
}).ToList();
最後再用迴圈來統計

foreach (var mRowA in QueryA)
{
//做處理 

}

c# 簡單做流水號的方法

註我的流水號是 (民國年三碼) + 月月 + 三碼流水號
所以後面有-1911
這是做月份的方式以此類推後面可以有日的


//取得流水號
string Sql1 = " select top 1 convert(int,substring(CX_Order_No,6,3)) as maxNo from QuoteList where substring(CX_Order_No,1,5)=@yyyMM order by convert(int,substring(CX_Order_No,6,3)) desc ";
SqlCommand cmd1 = new SqlCommand(Sql1, conn);

decimal myyy = PublicClass.ToDecimal(DateTime.Now.Year.ToString() )- 1911;
myyyyMM = myyy.ToString() + int.Parse(DateTime.Now.Month.ToString()).ToString("00");
cmd1.Parameters.AddWithValue("@yyyMM", myyyyMM);
DataTable dt1 = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);

if (dt1.Rows.Count > 0)
{
myyyyMM = myyyyMM + int.Parse( ( PublicClass.ToDecimal(dt1.Rows[0]["maxNo"].ToString()) + 1).ToString()).ToString("000");//有時給他加1
}
else
{
myyyyMM = myyyyMM + "001";//沒有時就給他001
}

c# 不足位數補0

月份補成兩位數
string test = int.Parse(DateTime.Now.Month.ToString()).ToString("00");


string test = string.Format("{0:00}", Convert.ToInt16(mNow.Month));

Asp.net 簡單的提示訊息視窗

在ap裡有msgbox
在asp.net雖然現在有很多方法
但最簡單的方是就是下面的方式啦
因為常用!!

c#
protected void AJaxShowMessage(string Message)
{
string scriptA = string.Empty;
string messageA = string.Empty;
messageA = Message.Replace("'", "\\");
messageA = messageA.Replace("\r\n", "\\n"); 
scriptA = string.Format("alert('{0}');", messageA);
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", scriptA, true);
}

2011年11月28日 星期一

c# 驗證日期

以下程式碼為網路上找的
但因日期時間過久所以無法知道出處
記得先using阿!!
using System.Text.RegularExpressions;//導入命名空間(正規表達式)



/// <summary>
/// 判斷是否為日期
/// </summary>
/// <param name="pDate">傳入字串。</param>
public static bool IsDate(string pDate)
{
return Regex.IsMatch(pDate, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
}



/// <summary>
/// 判斷是否為時間
/// </summary>
/// <param name="pTime">傳入字串。</param>
public static bool IsTime(string pTime)
{
return Regex.IsMatch(pTime, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$");
}



/// <summary>
/// 判斷是否日期+時間
/// </summary>
/// <param name="pDateTime"></param>
public static bool IsDateTime(string pDateTime)
{
return Regex.IsMatch(pDateTime, @"^(((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$ ");
}



/// <summary>
/// 回傳yyyy/MM/dd
/// </summary>
/// <param name="pDate">傳入字串。</param>
public static string ToyyyyMMdd(string pDate)
{
string mReturn = string.Empty;

if (pDate != "")
{
mReturn = DateTime.Parse(pDate).ToString("yyyy/MM/dd");
}
return mReturn;
}

c# 使用System.Net.Mail.SmtpClient寄信(無需帳密)

用樣寄是很好啦不需要登入帳密
但垃圾信太多小心被封了哈!!


1.web.config要加下面這段


<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network defaultCredentials="false" host="msa.hinet.net" port="25"/>
</smtp>
</mailSettings>
</system.net>


2.收件人的格式為

<abc@gmail.com> ,<def@gmail.com> ,


3.使用時要new出來喔

PublicClass Class = new PublicClass();//假如這function放在PublicClass裡時
Class.SendByMail(收件人,標題,內文, 寄件人會顯示的標題, 寄件的Email);


4.Function

/// <summary>
/// 用Client寄信 需New出來
/// </summary>
/// <param name="pMail">收件者可以,分格寄多人</param>
/// <param name="pSubject">信件標題</param>
/// <param name="pBody">信件內容</param>
/// <param name="pFromMailName">寄件人會顯示的標題</param>
/// <param name="pFromMail">寄件的Email</param>
public void SendByMail(string pMail, string pSubject, string pBody, string pFromMailName, string pFromMail)
{
System.Net.Mail.MailMessage Mail = new System.Net.Mail.MailMessage();
Mail.From = new System.Net.Mail.MailAddress(pFromMail, pFromMailName);
Mail.Subject = pSubject;
Mail.IsBodyHtml = true;
Mail.BodyEncoding = System.Text.Encoding.UTF8;
Mail.SubjectEncoding = System.Text.Encoding.UTF8;
Mail.Body = pBody;
//這邊多人可以回圈
char[] delimiterChars = { ',' };

string[] words = pMail.Split(delimiterChars);

foreach (string s in words)
{
if (s.Trim() != "")
{
Mail.To.Add(s);
}
}

System.Net.Mail.SmtpClient SMTPServer = new System.Net.Mail.SmtpClient(System.Web.Configuration.WebConfigurationManager.AppSettings["SmtpHost"]);
SMTPServer.Send(Mail);
System.Threading.Thread.Sleep(5);
GC.Collect();
GC.WaitForPendingFinalizers();
}

c# 去除string中重複的值

例如有一個string mStr = "1,2,3,2,4,62,24,64,1,4,75,3,2,4,75";
要去除重覆的值時可用到
string mStr = string.Join(",", mStr.Split(',').Distinct().ToArray());

c# 資料庫查詢like寫法


/// <summary>
/// 查產品
/// </summary>
/// <param name="pTitle)">產品名稱</param>
public static DataTable GetPoducts(string pTitle)
{
DataTable dt = new DataTable();

using (SqlConnection conn = new SqlConnection(ConnectionString()))
{

string Sql = "select * from Products where 1 = 1 and Title=@Title";
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.Parameters.Add("@Title", SqlDbType.VarChar).Value = "%" + pTitle + "%";

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);

cmd.Dispose();
da.Dispose();

}
return dt;
}

c# 將圖片轉為二進位

 
using System.IO;
using System.Drawing;

/// <summary>
/// 將 Image 轉換為 Byte 陣列。 /// </summary>
/// <param name="ImgPath">圖片路徑 。</param> public byte[] ImageToBuffer(string ImgPath) { byte[] _ImageBytes;
if (File.Exists(ImgPath)) {
Image _Image = Image.FromFile(ImgPath); MemoryStream ms = new MemoryStream(); _Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); _ImageBytes = ms.GetBuffer(); ms.Dispose(); _Image.Dispose(); } else { _ImageBytes = null; } return _ImageBytes; }

c# 判斷是否為數字

之前在VB中有IsNumeric可判斷是否為數字
現在換到c#時忽然沒這含數
之前在網路上找到正規表達式來判斷


using System.Text.RegularExpressions;//導入命名空間(正規表達式)

/// <summary>
/// 判斷是否為數字
/// </summary>
/// <param name="pNumber">傳入判斷的字串。</param>
public static bool IsNumeric(String pNumber)
{
Regex NumberPattern = new Regex("[^0-9.-]");
return !NumberPattern.IsMatch(pNumber);
}

T-SQL insert 後取得IDENTITY

如果上傳一筆產品+圖片時
需要抓到產品的products id後再來新增圖片所對應的 products id

在資料庫中必需要設一個識別規格(identity)


insert into abc ( ProductsName )
VALUES (ProductsName )
;SELECT @@IDENTITY;

Asp.net Web.config設定上傳檔案大小跟TimeOut的時間

近來常遇到無法上傳檔案問題
發現大概有幾個原因
問題1.資料夾權限沒設定(這當然要記得去設定)
問題2.上傳最大檔案長度超過(預設好像4mb)
問題3.上傳時間過長(預設好像90秒)

問題1的話只要進去設定權限就好
問題2 3 的話可以從web.config去修改我覺得蠻快的
在system.web標籤中加入或修改

<system.web>
<!-- 最大上傳檔案大小100MB(100*1024) TimeOut時間300秒 -->
<httpRuntime maxRequestLength="102400" executionTimeout="300"/>
</system.web>

Asp.net StreamReader 讀取純文字檔

最近常會做到一些寫固定提示語
例如公司標題之類
但是又不常修改,不常不帶表不會
為了不浪費資料庫效能所以都寫在txt裡面
這樣以後要改也可以改
string Path = Server.MapPath("txt/abcd.txt");//檔案路徑

using (StreamReader sr = File.OpenText(Path))
{
String input;
while ((input = sr.ReadLine()) != null)
{
//input如果不是null的話就會是一行文字
//做處理
}
}

2011年11月27日 星期日

Blogger 上貼上html或程式碼

最會影響到的就

"<" 改成
& l t ;


">" 改成

& g t ;

ps. 記得把空白拿掉!!

更多符號編碼點我

Blogger 安裝Facebook按讚的功能

繼上一篇後
繼續增加功能下面網址教的很詳細
http://micnet.blogspot.com/2010/05/facebook-like-button.html

但我的板模有點不一樣
所以是找到

h3 class='post-title
下一行加上
<script>
document.write('<iframe src="http://www.facebook.com/plugins/like.php?href=<data:post.url/>&layout=standard&show_faces=true&width=450&action=like&font=verdana&colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:450px; height:20px"></iframe>');
</script>

Blogger 安裝Facebook 留言功能

剛無意想到想加入這個功能
就是在每篇文章下面多一個Facebook可留言的功能
如果用asp.net我之前有寫過了
但套用在Blooger裡沒用過於是找到下面的網址有教
而且很詳細就分享給大家
http://blog.seo-tw.org/2011/04/bloggerfacebook-commentsfacebook.html

找到
<b:includable id='comments' var='post'>
下面加上
<div id='fb-root'/><script src='http://connect.facebook.net/zh_TW/all.js#appId=appid&xfbml=1'/><fb:comments expr:href='data:post.url' num_posts='2' width='500'/>

appid請換上自己申請的

2011年11月26日 星期六

ThickBox 解決在Updatepanel裡的問題

在thickbox.js裡
找到

$(function () {
tb_init('a.thickbox, area.thickbox, input.thickbox');
imgLoader = new Image(); // preload image
imgLoader.src = tb_pathToImage;
});

改成
function pageLoad(sender, args) {
tb_init('a.thickbox, area.thickbox, input.thickbox');
imgLoader = new Image(); // preload image
imgLoader.src = tb_pathToImage;

}

參考http://www.cnblogs.com/lion/archive/2010/10/08/1845732.html

ThickBox 解決在iframe裡的問題

如果放在iframe裡跳出來只會在iframe裡
在thickbox.js裡
找到原始


function tb_init(domChunk){
$(domChunk).click(function(){
var t = this.title || this.name || null;
var a = this.href || this.alt;
var g = this.rel || false;
tb_show(t,a,g);
this.blur();
return false;
});
}

改成
function tb_init(domChunk) {
$(domChunk).click(function() {
var t = this.title || this.name || null;
var a = this.href || this.alt;
var g = this.rel || false;
self.parent.tb_show(t, a, g);
this.blur();
return false;
});
}

忘記在那找到的方法了

jQuery 改變iframe的src

做這個卡了一早上

myiframe 是iframe的id


Google 使用Google產QR Code

原本有找到元件可以產生QR Code的

但後來在這個網站偶然發覺Google可以幫我產生

所以就拿來使用了不愧是Google大神

.aspx

<asp:literal id="Literal1" runat="server"></asp:literal>


.cs


string mUrl = Request.Url.AbsoluteUri;// 取得目前網址
Literal1.Text = string.Format("<img alt="簡單使用" src="https://chart.googleapis.com/chart?chs=120x120&cht=qr&chl={0}&choe=UTF-8&chld=M|2">", mUrl);


參數說明 其中:

chs: QR code 圖片大小

cht: 圖片類型,google

charts用這個參數產生各種圖片,這裡當然就填qr

chl: 要藏在QR code裡的文字,必須編成punycode(urlencode)。

choe: 編碼。請注意只支援iso-8859-1, sjis, utf8。詳見API說明網頁。

chld: 其他參數。M是錯誤修正層次,有L, M, Q, H等四級;後面的數字是QR code周圍白邊的寬度。

參考網站:http://www.dotblogs.com.tw/shadow/archive/2011/02/24/21557.aspx

Javascript 簡單的Google搜尋語法

因為最近客戶剛好需要google查詢的按紐 找了一下這樣寫很簡單吧


<script type="text/javascript">
function wopen(word) {
window.open('http://www.google.com/#hl=zh-TW&source=hp&q=' + word, 'Google');
                     }
</script>
 
 <input class="submit" onclick="wopen(this.form.text.value);return true;" type="submit" value="Google搜尋">
<input id="text" name="keyword" type="text">

Ckeditor 自定義字型跟ToolBar

網路上有許多相關的 找到ckeditor.js 加入字體

CKEDITOR.editorConfig = function(config) {
config.font_names = 'Arial;Arial Black;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana;新細明體;細明體;標楷體;微軟正黑體';
}


自訂義ToolBar ,網路上有許多ToolBar的說可自行找找

CKEDITOR.editorConfig = function(config) {
config.toolbar = 'MyToolbar';

config.toolbar_MyToolbar =
[
['Source', 'Preview', '-'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord'],
['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Link', 'Unlink', 'Anchor'],
['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'],
['Styles', 'Format', 'Font', 'FontSize'],
['TextColor', 'BGColor'],
['Maximize', 'ShowBlocks']

];

}

ThickBox 用程式關閉ThickBox加一些處理

關閉跳出來的ThickBox
ScriptManager.RegisterStartupScript(this, this.GetType(), "提示訊息", "alert('完成');parent.tb_remove()", true);


關閉跳出來的ThickBox並重新整理
ScriptManager.RegisterStartupScript(this, this.GetType(), "提示訊息", "alert('完成');parent.tb_remove();var win = top.window; try{ if(win){ win.location.reload(); } }catch(ex){} ;", true);


關閉跳出來的ThickBox並重新整理iframe(myiframe)
ScriptManager.RegisterStartupScript(this, this.GetType(), "提示訊息", "alert('完成');parent.tb_remove();parent.myiframe.location.reload();", true);


關閉後點選母視窗的查詢按紐重整 s為判斷重整(看個人使用) b為button的id
ScriptManager.RegisterStartupScript(this, this.GetType(), "提示訊息", "alert('完成');parent.tb_remove();parent.document.getElementById('" + Request.QueryString["s"].ToString() + "').value=1;parent.document.getElementById('" + Request.QueryString["b"].ToString() + "').click(); ", true);


關閉後到指定的網頁

ScriptManager.RegisterStartupScript(this, this.GetType(), "提示訊息", "alert('完成');parent.tb_remove();var win = top.window; try{ if(win){ win.location.href='code.aspx'; } }catch(ex){};", true);


不關閉重整父頁面(b為父頁面的查詢 s為父頁面的一個隱藏欄位用來判段是查詢還是重整用的)
<input type="button" value="Detail" style="text-align: center;" onclick="tb_show('Detail','_Statement.aspx?type=modify&id=<%# Eval("ID_Statement") %>&b=<%# this.Button2.ClientID %>&s=<%# this.HiddenFieldStatus.ClientID %>&KeepThis=true&TB_iframe=true&height=550&width=750',null);" />

ScriptManager.RegisterStartupScript(this, this.GetType(), "提示訊息", "alert('完成');parent.document.getElementById('" + Request.QueryString["s"].ToString() + "').value=1;parent.document.getElementById('" + Request.QueryString["b"].ToString() + "').click(); ", true);

Asp.net 去除Html<>裡標籤

因為常使用CKEditor,所以在如果字數很多的時後會常做到More這個功能

這時就必需要將Html標籤給去除掉才有辦法只顯示出純文字,這時就需要這個Function啦

傳入一整個Ckeidtor文字。
///  
/// 去除Html標籤 
///  
///
傳入一整個Ckeidtor文字。
public static string ReplaceHtmlTag(string Html)
{
Html = Regex.Replace(Html, "<[^>]*>", "");
return Html;
}

Blogger 主題下載網站

你的blogger 是不是還是用預設那麼簡單呢
btemplates有相當多的模版可以套用
只要上傳xml就可以喔相當簡單