Analytics

2011年3月31日 星期四

[C#]使用 String取Byte從第n位以後n個byte(Use String Byte taken from the n bits after the n-th byte)


問題

使用 String取Byte從第n位以後n個byte



解決方法

常在寫一些資料交換系統的工程師都知道,最常用來交換資料的就是TXT格式,
然而格式大概都是如下:

欄位 位置 長度
NAME 1 20
ID 21 10
AGE 31 2
SEX 33 1
交換格式都採用這種方式,而在取資料的時候,常常會遇到"中文字" 
而一個中文字有2個BYTE的大小,因此若欄位有夾雜中英文的話,常常會取錯資料,因此貢獻出自己的class用來處理! 

此擷取資料的方式很簡單,所見即所得,也就是將文件上的欄位對抄餵給function就可以了!! 
namespace B2c.DataEngine.Core
{
    public class GetChar
    {
        private int totalLenght = 0;
        public GetChar(int TotalLenght)
        {
            //if (TotalLenght == 0)
            //    throw new ArgumentException("Can't be zero");
            totalLenght = TotalLenght;
        }
        /// 
        /// 取得字串,字串,幾位,開始以後幾位
        /// 
        public string Position(string stringLine, int startPosition, int afterNumber)
        {
            byte[] _byte = System.Text.Encoding.Default.GetBytes(stringLine);
            string _string = string.Empty;
            if (_byte.Length >= totalLenght)
            {
                int _sp = startPosition-1;
                int _ep = afterNumber;
                _string = System.Text.Encoding.Default.GetString(_byte, _sp, _ep);
            }
            return _string;
        }
    }
}

2011年3月29日 星期二

[ASP.NET]解決 無法在 Web 伺服器上啟動偵錯,物件識別元不是一個正確物件。(Unable to solve start debugging on the Web server, object identifier element is not the right thing.)


問題

無法在 Web 伺服器上啟動偵錯,物件識別元不是一個正確物件。
錯誤畫面如下:
Capture




解決方法

網站上右鍵=>驗證=>啟用Windows驗證
2

[ASP.NET]解決 執行 Process.Start() 存取被拒。(Implementation of the settlement Process.Start () Access denied.)


問題

執行 Process.Start() 存取被拒。



解決方法

參考:http://www.dotblogs.com.tw/huanlin/archive/2008/04/23/3255.aspx
MSDN說明:http://support.microsoft.com/kb/555134/en-us
最快的方法還是將IIS裡的ApplicationPools裡的執行權限改為SystemMachine
,但這部分權限就很大了,因此此方式可以救急用於開發程式階段使用,但上線前記得將權限做適當調整!
我的電腦=>右鍵"管理"=點開IIS
dsd
選擇Application Pools=>進階設定
7
點開"身分識別"
8
選取以"本機服務"身分啟動程式
9
選服務=>IIS管理(IISAdmins)=>右鍵"內容"=>勾選允許與桌面互動
3
5

2011年3月25日 星期五

[ASP.NET]解決 GridView 匯出Excel 發生Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."


問題

GridView 匯出Excel 發生Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."



解決方法

語法如下:
protected void btnExportExcel_Click(object sender, EventArgs e)
{ 
 if (GridView1.Rows.Count > 0) 
 { 
  string attachment = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss"))); 
  Response.ClearContent(); 
  Response.AddHeader("content-disposition", attachment); 
  Response.ContentType = "application/ms-excel";
  StringWriter sw = new StringWriter(); 
  HtmlTextWriter htw = new HtmlTextWriter(sw);
  GridView1.RenderControl(htw); 
  Response.Write(sw.ToString()); 
  Response.End(); 
 } 
}
但是會發生錯誤下:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
解決方式override 原有的function:
public override void VerifyRenderingInServerForm(Control control)
{
 
}

[ASP.NET]使用 GridView 匯出完整EXCEL 解決Gridview分頁顯示不完全(Use Export GridView complete EXCEL solve Gridview Pagination incomplete)


問題
GridView 匯出完整EXCEL 解決Gridview分頁顯示不完全
當GridView有設定分頁的時候,會發生多頁的時候,EXCEL卻只會出某一頁,如下:
string attachment  = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss")));
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();




解決方法
解決方式其實很簡單,在respose到client前,重新指定GridView的PageSize就可以了!如下:
ReportViewPool.allocationInvoiceDataTable tb = DataLoad();//自訂義tb GridView1.DataSource = tb;
GridView1.PageSize = tb.Rows.Count;//重新指定頁面筆數
GridView1.DataBind();//指定以後依定要bind一次
string attachment = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss")));
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

2011年3月24日 星期四

[ADO.Net]使用 TableAdapter 隨心所欲變更SqlCommand(Use TableAdapter arbitrary change SqlCommand)


問題

使用 TableAdapter 隨心所欲變更SqlCommand



解決方法

TableAdapter是由強型別DataSet所賦予的功能,而方便在於不需要太多的程式碼就可以將資料的新增/修改/刪除,一次搞定
這次要分享的就是如何隨心所欲調整SqlCommand,並傳回資料
1.選取要操作的資料表進dataset,變更名稱
1
2.會自行建立TableAdapter(預設為資料表名稱+TableAdapter)
2
3.實體化TableAdapter
3
4.自行調整語法
3.1
5.將原本的Connection指派給自己(你也可以新增一個連線若需要的話),叫用Fill方法將資料填進指定的DataSet(強行別或弱型別都可以歐)
4



2011年3月22日 星期二

[ASP.NET]使用 request取得Client IP(Client IP using the request made)


問題

使用 request取得Client IP



解決方法

於WebService or WebSite or ASP.NET Application:
using MyWebToolkit;
string ip=MyWebToolkit.GetClientIP(this.Context);

.cs:
using System;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyWebToolkit
{
    public static class MyWebToolkit
    {
        public static string GetClientIP(System.Web.HttpContext context)
        {
            string ip = null;
            if (string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
                || Convert.ToString(context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]).Contains("UNKNOWN"))
            {
                ip = context.Request.ServerVariables["REMOTE_ADDR"];
            }
            else if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") > 0)
            { ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(1, context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") - 1); }
            else if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") > 0)
            { ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(1, context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") - 1); }
            else { ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; }
            return ip.Replace(" ", string.Empty);
        }
    }
}

2011年3月21日 星期一

[MS SQL]使用 Update From 小技巧(Use Update From tips)


問題
使用 Update From 小技巧



解決方法
常在下SQL語法的人常常會發生需要更新某些資料,而需要跟新的資料又與很多資料表有相關聯性,因此不懂小技巧的人,常常會更新錯資料,造成一些災害,在此提供一個小技巧,讓你可以邊查詢資料,邊驗證要更新的資料是否正確
一般來說,多個TABLE之間的相關聯我們會用JOIN的方式:
SELECT A.UserName,B.Company
FROM User as A INNER JOIN Company as B ON A.CompanyID=B.CompanyID
當我們想要將某個使用者的公司更新,我們只要稍微做個變更就可以:
UPDATE Company
SET Company.CompanyID=’Microsoft’
--SELECT A.UserName,B.Company
FROM User as A INNER JOIN Company as B ON A.CompanyID=B.CompanyID
看得懂嗎?只是將更新語法加在原本SELECT 之上,所以在更新之前可以先SELECT資料是不是跟想像的一樣,可確保災害降低

2011年3月14日 星期一

[ASP.NET]使用 GridView.TemplateField實作Link Button觸發下載檔案的動作(Use GridView.TemplateField implementation Linkbutton trigger action download files)


問題
使用 GridView.TemplateField實作Link Button觸發下載檔案的動作



解決方法
在LinkButton事件哩,加入程式碼: .cs
protected void lbtFileName_Click(object sender, EventArgs e)
{    
 LinkButton btn = (LinkButton)sender;
    TableCell tc = (TableCell)btn.Parent;
    GridViewRow gvr = (GridViewRow)tc.Parent;
    int rowindex = gvr.RowIndex;
        //資料來源
    DataTable tb = db.GetContentByGID(Convert.ToInt32(gvNotice.DataKeys[rowindex].Value));
    DataRow row = tb [0];    //下載檔案
    Response.Clear();
    string fileName = Server.UrlPathEncode(Convert.ToString(row["FileName"]));
    Response.Expires = 0;
    Response.Buffer = true;
    Response.AddHeader("Accept-Language", "zh-tw");
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));     //Response.Cache.SetNoStore();
    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Length", row.NContent.Length.ToString());
    Response.BinaryWrite(row.NContent);
    Response.End();
}
.aspx
設定LinkButton顯示的文字:
<asp:TemplateField HeaderText="文件名稱" SortExpression="FileName">
<ItemTemplate>
<asp:LinkButton ID="lbtFileName" runat="server" CommandName="OpenFile" onclick="lbtFileName_Click"  > <%#Eval("FileName") %></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

[AJAX]解決 Sys.WebForms.PageRequestManagerParserErrorException: 無法剖析從伺服器收到的訊息。這項錯誤通常的原因是回應被 Response.Write()、回應篩選條件、HttpModules 的呼叫修改了,或是已啟用伺服器追蹤。 詳細資料: 剖析 near 'xxx' 時發生錯誤。(Solve Sys.WebForms.PageRequestManagerParserErrorException: Unable to parse the message received from the server. This error usually occurs because the response is Response.Write (), to respond to the filter criteria, HttpModules call modified, or server trace is enabled. Details: Error parsing near 'xxx'.)


問題
Sys.WebForms.PageRequestManagerParserErrorException: 無法剖析從伺服器收到的訊息。這項錯誤通常的原因是回應被 Response.Write()、回應篩選條件、HttpModules 的呼叫修改了,或是已啟用伺服器追蹤。 詳細資料: 剖析 near 'xxx' 時發生錯誤。



解決方法
在使用ajax開發時,當頁面使用update panel時,而頁面如果有檔案下載的動作,就發出現這樣的問題,因此現有的解決方式就是將update panel移除,就可以避免這樣的問題出現

2011年3月10日 星期四

[C#]使用 WebClient下載其他網站的資料(Use WebClient to download information from other sites)


問題
使用 WebClient下載其他網站的資料



解決方法
public string GetHtmlCodeSaved(string savePath,string saveFileName)
{
if (savePath.Length == 0)
throw new ArgumentException("Save Path can't empty!");  
if (saveFileName.Length == 0)
throw new ArgumentException("Save File Name can't empty!");  
try
    {
using (WebClient client = new WebClient())
{          string localPath = savePath + saveFileName;
client.DownloadFile(htmlAddress, localPath);
return localPath;
}
    }
catch (Exception ex)
    {
        throw ex;
    }
  }

[ASP.NET]使用 httpRuntime.maxRequestLenght 設定檔案上傳上限(Use httpRuntime.maxRequestLength setup file upload limit)


問題
使用 httpRuntime.maxRequestLenght 設定檔案上傳上限



解決方法
<system.web>
<!-- 單位為K,預設是4 MB -->
<httpRuntime maxRequestLength="4096"/>
</system.web>

2011年3月7日 星期一

[VISUAL STUDIO]解決 IIS已設定為應用程式,卻仍出現"在應用程式層級之外使用註冊為 allowDefinition='MachineToApplication' 的區段發生錯誤。錯誤的原因可能是虛擬目錄尚未在 IIS 中設定為應用程式。"(IIS has been set to resolve apps still appear in addition to using the app level registered as allowDefinition = 'MachineToApplication' segment error. It may be the cause of the error has not been set for the virtual directory in IIS app.)


問題

IIS已設定為應用程式,卻仍出現"在應用程式層級之外使用註冊為 allowDefinition='MachineToApplication' 的區段發生錯誤。錯誤的原因可能是虛擬目錄尚未在 IIS 中設定為應用程式。



解決方法

由於網路上都說要註冊IIS為應用程式就可以解決,但這方法試過卻不行,所以檢查了一下自己的方案,發現WebSite的網站裡,不知道被誰又包了一個WebSite,也就是WebSite裡有另一個Website,所以將另一個WebSiet提出來,問題就解決了!!
如果有這樣的問題解決不了,也可以試著找一下是否有跟我一樣的狀況

[VISUAL STUDIO]解決 Crystal Report發生"混合模式組件是針對版本 'v2.0.50727' 的執行階段建置的,無法在沒有其他組態資訊的情況下載入 4.0 執行階段中。"(Crystal Report resolve when mixed-mode component for version 'v2.0.50727' of the implementation phase of the build, can not be downloaded into the implementation phase 4.0 no other configuration information in the case of)


問題

Crystal Report發生"混合模式組件是針對版本 'v2.0.50727' 的執行階段建置的,無法在沒有其他組態資訊的情況下載入 4.0 執行階段中。
在使用VISUAL STUDIO 2010開發程式時,使用Crystal Report後,發生以下錯誤訊息:
2

解決方法


1.於config裡,找到<startup>的tag3
2.加上useLegacyV2RuntimeActivationPolicy=”true”,如下:
4

[Crystal Report]解決 發生"無法載入檔案或組件'file:///C:\Program Files\SAP BusinessObject\Crystal Report for .Net Framework 4.0\Common\SAP BusinessObject Enterprise XI 4.0\win32_x86\donet1\crdb_adoplus.dll'或其相依性的其中之一 系統找不到指定的檔案"


問題

發生"無法載入檔案或組件'file:///C:\Program Files\SAP BusinessObject\Crystal Report for .Net Framework 4.0\Common\SAP BusinessObject Enterprise XI 4.0\win32_x86\donet1\crdb_adoplus.dll'或其相依性的其中之一 系統找不到指定的檔案"
1


解決方法

在VISUAL STUDIO 2010環境下開發Crystal Report需檢查是否裝有底下程式:
官方下載網頁
SAP Crystal Reports, version for Visual Studio 2010 -
在所需要的的crdb_adoplus.dll'在以下安裝檔:
SAP Crystal Reports runtime engine for .NET Framework 4 (32-bit)
安裝完後,到目錄C:\Program Files\SAP BusinessObject\Crystal Report for .Net Framework 4.0\Common\SAP BusinessObject Enterprise XI 4.0\win32_x86資料夾底下,找到crdb_adoplus.dll
將檔案加入到參考,另外屬性copy to local設為true,如此一來就可以解決此問題

2011年3月5日 星期六

[MS Access]使用 Access 2003 vs. Access 2007(含以上版本)於VS2010使用TableAdapter 參數化查詢的用法(Use Access 2003 vs. Access 2007 (including above) in VS2010 using TableAdapter query parameter usage)


問題

使用 Access 2003 vs. Access 2007(含以上版本)於VS2010使用TableAdapter 參數化查詢的用法

'@'附近的WHERE子句錯誤

解決方法

MS Access 2003的版本所建出來的資料庫副檔名為.mdf
MS Access 2007的版本所建出來的資料庫副檔名為.accdb


VS 2010在使用TableAdapter做查詢資料的時候,以符號
'@'表示為參數如下:
1
但這方式在VS 2010可不管用,會發生如下訊息: 2
由於VS 2010內部有做些許的變動,因此參數符號請改用'?'且不須給取名稱: 3
4
當然,產生了以後,一如往常的可以使用TableAdapter作為查詢,如下 5














2011年3月1日 星期二

[Windows7]解決 Error code:0x80070035 The network path was not found(Solve Error code: 0x80070035 The network path was not found)


問題

Error code:0x80070035 The network path was not found
在存取區域網路的時候,發生以下訊息:
3

解決方法

Winsows 開始=>我的電腦"右鍵"=>管理
2.0
展開"服務"=>選Services
2.1
找到TCP/IP NetBIOS Helper雙擊點開=>選擇"自動"(這邊依個人需求,但必定不是停用)=>確定
4
會回到上一層,這時候左手邊會有個Start的link,點一下啟用服務




[Windows7]解決 The Server Service is not started.(Resolved The Server Service is not started.)


問題

The Server Service is not started.

在Windows 7底下使用網路芳鄰時,出現"The Server Service is not started."錯誤訊息如下:
1

解決方法

Winsows 開始=>我的電腦"右鍵"=>管理
2.0
展開"服務"=>選Services
2.1
找到Server雙擊點開=>選擇"自動"(這邊依個人需求,但必定不是停用)=>確定
2
會回到上一層,這時候左手邊會有個Start的link,點一下啟用服務




熱門文章