---
2025年9月23日 星期二
2025年9月19日 星期五
2025年9月18日 星期四
2025年9月17日 星期三
VB.NET 檔案是否被鎖定
--
Try
Dim fs AsFileStream = NewFileStream(excelFileName, FileMode.OpenOrCreate, FileAccess.Read)
fs.Close()
Catch ex AsException
MessageBox.Show(excelFileName & "文件当前已经打开,请先关闭")
Return ' 退出
End Try
----
Imports System.IO
Imports System.Runtime.InteropServices
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str_thispath As String = String.Empty '完整檔案路徑
str_thispath = TextBox1.Text
TextBox2.Text = ""
If File.Exists(str_thispath) Then
IsFileOpen(str_thispath)
Else
TextBox2.Text = "檔案不存在:" & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " 結束執行。" & vbNewLine & TextBox2.Text
End If
TextBox2.Text = "系統於 " & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " 結束執行。" & vbNewLine & TextBox2.Text
End Sub
Function IsFileOpen(ByVal str_thispath As String) As Boolean
Dim stream As FileStream = Nothing
Try
stream = File.Open(str_thispath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
stream.Close()
TextBox2.Text = "檔案可開啟:" & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " " & vbNewLine & TextBox2.Text
Catch ex As Exception
If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
TextBox2.Text = "發生例外錯誤:原因可能檔案正在使用中已上鎖..." & Date.Now.ToString("yyyy/MM/dd HH:mm:ss.fffffff") & " " & vbNewLine & TextBox2.Text
Return True
End If
End Try
Return False
End Function
Function IsFileLocked(exception As Exception) As Boolean
Dim ERROR_SHARING_VIOLATION As Integer = 32, ERROR_LOCK_VIOLATION As Integer = 33
Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
Return errorCode = ERROR_SHARING_VIOLATION OrElse errorCode = ERROR_LOCK_VIOLATION
End Function
End Class
2025年9月1日 星期一
vb ping get domain
Imports System.Net.NetworkInformation
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim url As String = "https://xxx/xxx/xxxx"
Dim utl_Donaim = GetDomainFromUrl(url)
'If My.Computer.Network.Ping("198.01.01.01") Then
'End If
Using pinger As New Ping()
Dim reply As PingReply = pinger.Send(utl_Donaim, 5000)
If reply.Status = IPStatus.Success Then
MessageBox.Show("Ping to {targetHost} successful! Roundtrip time: {reply.RoundtripTime}ms", "Ping Result")
Else
MessageBox.Show("Ping to {targetHost} failed. Status: {reply.Status}", "Ping Result")
End If
End Using
End Sub
Public Function GetDomainFromUrl(ByVal urlString As String) As String
Try
Dim uri As New Uri(urlString)
Return uri.Host
Catch ex As UriFormatException
Return String.Empty
End Try
End Function
2025年8月29日 星期五
ASP.NET System.Threading.ThreadAbortException: 執行緒已經中止
參考引用來源:ASP.NET System.Threading.ThreadAbortException: 執行緒已經中止
---
發生錯誤:執行緒已經中止。
於 System.Threading.Thread.AbortInternal()
於 System.Threading.Thread.Abort(Object stateInfo)
於 System.Web.HttpResponse.AbortCurrentThread()
於 System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)
---
解決方案:https://support.microsoft.com/zh-tw/kb/918181
<%@ Page Language="C#" Async="true"%>
當 HttpResponse.Redirect 方法 endResponse 參數不設為 false 時,就會發生這個問題。 根據預設值,endResponse 參數設定為 true。
轉貼連結:http://www.dotblogs.com.tw/boei/archive/2010/07/11/16485.aspx
將網頁轉出成word的時候,最後會來個Response.End()來結束它的輸出,但都會發生<System.Threading.ThreadAbortException> 執行緒已經中止,雖然不會造成系統上的什麼問題。
解決方法:
1. 繼續用Response.End(),外面用try – catch包住,但try – catch會比較消耗資源,所以不考慮。
2. 改用HttpContext.Current.ApplicationInstance.CompleteRequest(),可以跳過Application_EndRequest 事件的執行。
如果使用Response.Redirect 或 Server.Transfer 方法也發生一樣狀況的話,就可以使用Response.Redirect(String url, bool endResponse),endResponse就設為False,因為Response.Redirect內部會用到Response.End(),設為False就是要停用Response.End()方法。
2025年8月28日 星期四
2025年8月27日 星期三
2025年8月26日 星期二
webclient 無法建立 SSL/TLS 的安全通道
在 framework 4.0 無法建立 tls12
只能自己新增:
in .net Framework 4.0 add
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2
2025年8月25日 星期一
ASP.NET C# URL 網址參數解析,取得網址參數
引用來源:ASP.NET C# URL 網址參數解析,取得網址參數
- 底下分別列出解屬性及解析結果
參數 | 結果 |
---|---|
Request.ApplicationPath | / |
Request.Url.Host | my.url.com |
Request.Url.Port | 8080 |
Request.Url.Scheme | https |
Request.Url.Authority | my.url.com:8080 |
Request.Path | /Detail/Page/List.aspx/showmore |
Request.Url.LocalPath | /Detail/Page/List.aspx/showmore |
Request.PathInfo | /showmore |
Request.Url.Query | ?mid=20 |
Request.CurrentExecutionFilePath | /Detail/Page/List.aspx |
Request.FilePath | /Detail/Page/List.aspx |
Request.RawUrl | /Detail/Page/List.aspx/showmore?mid=20 |
Request.Url.PathAndQuery | /Detail/Page/List.aspx/showmore?mid=20 |
Request.Url.AbsoluteUri | https://my.url.com:8080/Detail/Page/List.aspx/showmore?mid=20 |
Request.Url.AbsolutePath | /Detail/Page/List.aspx/showmore |
- 取得系統路徑
參數 | 結果 |
---|---|
Request.PhysicalPath | C:\wwwroot\Detail\Page\List.aspx |
System.IO.Path.GetDirectoryName(Request.PhysicalPath) | C:\wwwroot\Detail\Page |
Request.PhysicalApplicationPath | C:\wwwroot\ |
System.IO.Path.GetFileName(Request.PhysicalPath) | List.aspx |
- 解析參數
參數 | 結果 |
---|---|
Request.Url.Segments | /, Detail/, Page/, List.aspx/, showmore |
2025年8月23日 星期六
跳轉頁面發生 RegisterForEventValidation 只能在 Render(); 期間呼叫
跳轉頁面發生:
System.InvalidOperationException: 'RegisterForEventValidation 只能在 Render(); 期間呼叫'
這個問題,可以設定aspx原始檔中<%Page%>的以下兩個設定解決
EnableEventValidation = "false" AutoEventWireup="true"
2025年8月21日 星期四
windows 11 pdf 小圖示不見
一、在C:\Users\ABC\AppData\Local的路徑下的IconCache.db刪除(其中ABC為你自己設定的使用者名稱)
二、然後在工作管理員中將「Windows檔案總管」重新啟動,或是重新開機即可恢復
2025年8月20日 星期三
確認 applicationhost.config 或 web.config 檔案中的requestLimits@maxQueryString 設定
---
底下方法還是不行!
發生錯誤:執行緒已經中止。
看來是須要改寫方法了...(無法偷懶...)
---
引用記錄一下:
在项目的web.config里,<system.webServer>路径下添加如下配置:
<security>
<requestFiltering>
<requestLimits maxQueryString="4080" />
</requestFiltering>
</security>
打开项目中的Web.config,在<system.web>节点下设置httpRuntime节点的maxQueryStringLength属性,Web.config中的设置如下:
<system.web>
<httpRuntime maxQueryStringLength="9999"/>
</system.web>
------------
2025年8月18日 星期一
MSSQL DATALENGTH 尾端空白字串
select '0022000114693',len('0022000114693'),len('0022000114693 '),DATALENGTH('0022000114693'),DATALENGTH('0022000114693 ')
值變化:
2025年8月15日 星期五
2025年8月14日 星期四
2025年8月12日 星期二
JSON HTTP POST Request In Visual Basic .NET
JSON HTTP POST Request In Visual Basic .NET
---
引用來源:
'Install Newtonsoft.json '----------------------- ' 'PM> Install-Package Newtonsoft.Json -Version 6.0.8 'Sample Usage '------------ 'Dim jsonPost As New JsonPost("http://192.168.254.104:8000") 'Dim dictData As New Dictionary(Of String, Object) 'dictData.Add("test_key", "test_value") 'jsonPost.postData(dictData) Imports Newtonsoft.Json Imports System.Net Imports System.Text Public Class JsonPost Private urlToPost As String = "" Public Sub New(ByVal urlToPost As String) Me.urlToPost = urlToPost End Sub Public Function postData(ByVal dictData As Dictionary(Of String, Object)) As Boolean Dim webClient As New WebClient() Dim resByte As Byte() Dim resString As String Dim reqString() As Byte Try webClient.Headers("content-type") = "application/json" reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dictData, Formatting.Indented)) resByte = webClient.UploadData(Me.urlToPost, "post", reqString) resString = Encoding.Default.GetString(resByte) Console.WriteLine(resString) webClient.Dispose() Return True Catch ex As Exception Console.WriteLine(ex.Message) End Try Return False End Function End Class
Making a post request with data in vb.net
Making a post request with data in vb.net
---
引用來源:
Dim postdata As New JObject
postdata.Add("service_id", "value 1")
postdata.Add("template_id", "Value 2")
postdata.Add("user_id", "Value 3")
'postdata contains data which will be posted with the request
Dim finalString as String = postdata.ToString
Dim httpWebRequest = CType(WebRequest.Create("Api address Here"), HttpWebRequest)
httpWebRequest.ContentType = "application/json"
httpWebRequest.Method = "POST"
Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())
streamWriter.Write(finalString)
End Using
Dim httpResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)
Using streamReader = New StreamReader(httpResponse.GetResponseStream())
Dim responseText as String = streamReader.ReadToEnd()
'responseText contains the response received by the request
End Using
Here the data format is:
{
service_id: 'YOUR_SERVICE_ID',
template_id: 'YOUR_TEMPLATE_ID',
user_id: 'YOUR_USER_ID'
}
VB.NET REST API call with Basic Authorization
VB.NET REST API call with Basic Authorization
---
引用來源:
Dim origResponse As HttpWebResponse
Dim objResponse As HttpWebResponse
Dim origReader As StreamReader
Dim objReader As StreamReader
Dim origRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://api.orls.voxeo.net/files/exports/2017/10/31?"), HttpWebRequest)
origRequest.Headers.Add("Authorization", "Basic c3NhX2RzdDpBc3AzY3RfMTIzNA==")
origRequest.AllowAutoRedirect = False
origRequest.Method = "GET"
Try
origResponse = DirectCast(origRequest.GetResponse(), HttpWebResponse)
Dim Stream As Stream = origResponse.GetResponseStream()
Dim sr As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))
Dim str As String = sr.ReadToEnd()
MessageBox.Show(str)
Catch ex As WebException
MsgBox(ex.Status)
Dim myRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://api.orls.voxeo.net/files/exports/2017/10/31/Export-production-202715_20171030.zip.gpg"), HttpWebRequest)
myRequest.Headers.Add("Authorization", "Basic c3NhX2RzdDpBc3AzY3RfMTIzNA==")
Try
objResponse = DirectCast(myRequest.GetResponse(), HttpWebResponse)
Catch ex2 As WebException
objReader = New StreamReader(objResponse.GetResponseStream())
MsgBox(objReader.ReadToEnd())
MsgBox(ex2.Status)
End Try
End Try
Calling REST API from Visual Basic
Calling REST API from Visual Basic
---
引用來源:
Public Sub Try01(URL)
Try
Dim myReq As HttpWebRequest
Dim myResp As HttpWebResponse
Dim myReader As StreamReader
myReq = HttpWebRequest.Create(URL)
myReq.Method = "POST"
myReq.ContentType = "application/json"
myReq.Accept = "application/json"
myReq.Headers.Add("Authorization", "Bearer LKJLMLKJLHLMKLJLM839800K=")
Dim myData As String = "{""riskLevelStatus"":""0001"",""userId"":""10000004030"",""applicationName"":""MyTestRESTAPI""}"
myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)
myResp = myReq.GetResponse
myReader = New System.IO.StreamReader(myResp.GetResponseStream)
TextBox1.Text = myReader.ReadToEnd
Catch ex As Exception
TextBox1.Text = TextBox1.Text & "Error: " & ex.Message
End Try
End Sub
2025年8月10日 星期日
vs 2022 webform BC30451: Name '' is not declared
微軟:BC30451: Name '<name>' is not declared
看官網還是看不懂...是什麼問題!
----
看了這篇,有些懂了! 是複製造成的!?
也不全然這樣的問題造成 BC30451
同1支code , A PC Error 但 B PC 卻 OK
我還在找差異性到底是在哪?
自從開發 webform + web api restful for framework 就都感覺全不順
單純的 .Net Core 較順...
---------
20250811:
將 B PC OK 的專案(經過更動+儲存)改到 A PC 也OK了...
所以這個 BC30451: Name '<name>' is not declared
應該是無解了...
2025年8月7日 星期四
2025年8月6日 星期三
未將物件參考設定為物件的執行個體
引用來源: [C#]未將物件參考設定為物件的執行個體-個人經驗
[C#]未將物件參考設定為物件的執行個體-個人經驗
當出現此訊息,標準說明網路很多"物件尚未實體化就呼叫它的屬性或方法",
以下為自己遇到的以及處理方式,作為紀錄
表示有設定的物件,可能是DataTable、Int、String、陣列、object等等,未設定值(沒有值),就直接使用
1.一般的
EX
DataTable dt = null ;
Q_txtBNKNM.Text = dt.Rows[0]["BNKNM"].ToString(); \\這裡就會出錯
這種debug會直接斷在這裡,很好處理
--------------------------------------------------------------------------------
2. 比較難查的,通常是已經包在dll的程式,吐回來的訊息,不會說明斷哪裡
a. 利用搜尋,查找相關的程式檔案(關鍵字是自己會用到datatable or 陣列等等名稱)
b. 程式前後文,也有可能造成此問題,前半寫好,後段尚未完成,但只想驗證前面時,也會 發生,會發生在有參數互相傳遞的程式間
做為紀錄方便自己查詢
2025年8月5日 星期二
C# IIs 新增應用程式 web api
c# Web API區域網IIS部署
(一)點選圖中"模組", 需要幫iis安裝運行API的模組(https://dotnet.microsoft.com/en-us/download/dotnet/3.1
[C#][ASP.NET] Web API 開發心得 (1) - WebForm 搭配 Web API
ASP.NET Web API
使用 OWIN 自我裝載 ASP.NET Web API
自我託管 ASP.NET Web API 1 (C#)
https://learn.microsoft.com/zh-tw/aspnet/web-api/overview/older-versions/self-host-a-web-api
使用 ASP.NET Web API 建立 RESTful API
VBNET dataGridView當掉問題
private void InvokeGridViewAddRows(String str)
{
if (this.InvokeRequired)
{
GridViewAddRows addRows = new GridViewAddRows((InvokeGridViewAddRows));
this.Invoke(addRows, str);
}
else
{
// 在這裡寫入原本取到str後要對dataGridView做的事
}
}
--
我的問題是在 CellClick
程式調整:
Private Sub DGridV_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGridV.CellClick
Try
If Me.InvokeRequired Then '加這一行即可防止整個form當掉
If e.ColumnIndex = 0 Then
2025年8月4日 星期一
2025年8月3日 星期日
Windows Form 設計工具錯誤頁面
---
引用:
首先嘗試什麼
您通常可以透過清理並重建專案或解決方案來排除錯誤。
尋找 方案總管視窗。
在解決方案或專案上按右鍵,然後選取 [清除]。
在解決方案或專案上按右鍵,然後選取 [重建]。
----
*** 在 VS 2022 只要關掉[方案]再重新開啟方案 就可以正常了
2025年7月31日 星期四
STEAM 教育學習網
----
內容超棒的! 值得去看看學習
引用官網資訊:
關於 STEAM 教育
STEAM 教育由五個單字組成,分別是 Science ( 科學 )、Technology ( 技術 )、Engineering ( 工程 )、Arts ( 藝術 ) 和 Mathematics ( 數學 ),因此 STEAM 教育也稱作「跨學科教育」。STEAM 教育延伸 STEM 的精神,除了強調「動手做」以及「解決問題」的能力,更將藝術 Art、技術、工程和數學整合,創造出能夠應用於真實生活的應用。
STEAM 教育學習網秉持著 STEAM/STEM 的精神,透過一系列免費且高品質的教學與範例,讓所有人都能輕鬆跨入 STEAM 的學習領域。
Netstat 查 port 連線
參考引用:Windows Netstat | Display Active TCP / UDP Ports & Connections
說明
netstat -aon
可以搭配 findstr 篩選搜尋結果,例如只搜尋 443 port (TCP HTTPS) 相關的 Connections。
netstat -aon | findstr :443
2025年7月29日 星期二
[IIS]架設ASP.NET網站發生HTTP 錯誤 500.19 - Internal Server Error
HTTP 錯誤 500.19 - Internal Server Error
設定錯誤 這個設定區段不能在這個路徑中使用。
當區段在父層級被鎖定時就會發生這種情況。
鎖定可能是預設 (overrideModeDefault="Deny"),或是由位置標記使用 overrideMode="Deny" 或繼承的 allowOverride="false" 明確設定。
IIS 沒有安裝ASP.NET
補裝後,就正常了
2025年7月28日 星期一
VS2022 JSON 結構轉成 C# 的 Class
--
真是好用的工具
在 Visual Studio 中,您可以從 JSON 或 XML 檔案複製文字,然後將文本作為類粘貼到 C# 或 Visual Basic 代碼中。 為此,請選擇Edit>Paste Special 並選擇 Paste JSON As Classes 或 Paste XML As Classes。
在您的環境中啟用 TLS 1.2 的支援,以因應 Microsoft Entra TLS 1.1 和 1.0 的淘汰
在您的環境中啟用 TLS 1.2 的支援,以因應 Microsoft Entra TLS 1.1 和 1.0 的淘汰
Microsoft Entra Connect 的 TLS 1.2 強制
---
OS / windows Server
現一些線上串金流都被要求必須採用較新的密碼套件+HTTPS +TLS
2025年7月10日 星期四
關於購買本工作室研發產品程式碼
程式碼:
對於本工作室產品研發的程式碼有興趣購買的,可以寫信詢洽!
專案開發:
歡迎各行各業,有需求須要軟體客製開發;本工作室都能承包
部分開發分包:
歡迎各公司或工作室,有難度性的或是須要分包出來的案件;本工作室也能承包
開發語言:
ASP.NET / ASP Core
VB .NET / C# .NET / Framework
開發工具:
vs2022 community
2025年6月29日 星期日
2025年6月24日 星期二
TSC条码打印机C#例程(tsclib.dll调用) 【转】
TSC条码打印机C#例程(tsclib.dll调用) 【转】
//---- program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class TSCLIB_DLL
{
[DllImport("TSCLIB.dll", EntryPoint = "about")]
public static extern int about();
[DllImport("TSCLIB.dll", EntryPoint = "openport")]
public static extern int openport(string printername);
[DllImport("TSCLIB.dll", EntryPoint = "barcode")]
public static extern int barcode(string x, string y, string type,
string height, string readable, string rotation,
string narrow, string wide, string code);
[DllImport("TSCLIB.dll", EntryPoint = "clearbuffer")]
public static extern int clearbuffer();
[DllImport("TSCLIB.dll", EntryPoint = "closeport")]
public static extern int closeport();
[DllImport("TSCLIB.dll", EntryPoint = "downloadpcx")]
public static extern int downloadpcx(string filename, string image_name);
[DllImport("TSCLIB.dll", EntryPoint = "formfeed")]
public static extern int formfeed();
[DllImport("TSCLIB.dll", EntryPoint = "nobackfeed")]
public static extern int nobackfeed();
[DllImport("TSCLIB.dll", EntryPoint = "printerfont")]
public static extern int printerfont(string x, string y, string fonttype,
string rotation, string xmul, string ymul,
string text);
[DllImport("TSCLIB.dll", EntryPoint = "printlabel")]
public static extern int printlabel(string set, string copy);
[DllImport("TSCLIB.dll", EntryPoint = "sendcommand")]
public static extern int sendcommand(string printercommand);
[DllImport("TSCLIB.dll", EntryPoint = "setup")]
public static extern int setup(string width, string height,
string speed, string density,
string sensor, string vertical,
string offset);
[DllImport("TSCLIB.dll", EntryPoint = "windowsfont")]
public static extern int windowsfont(int x, int y, int fontheight,
int rotation, int fontstyle, int fontunderline,
string szFaceName, string content);
}
namespace TSCLIB_DLL_IN_C_Sharp
{
static class Program
{
/// <summary>
/// 應用程式的主要進入點。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
//----Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TSCLIB_DLL_IN_C_Sharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//TSCLIB_DLL.about(); //Show the DLL version
TSCLIB_DLL.openport("TSC TTP-344M Plus"); //Open specified printer driver
TSCLIB_DLL.setup("100", "63.5", "4", "8", "0", "0", "0"); //Setup the media size and sensor type info
TSCLIB_DLL.clearbuffer(); //Clear image buffer
TSCLIB_DLL.barcode("100", "100", "128", "100", "1", "0", "2", "2", "Barcode Test"); //Drawing barcode
TSCLIB_DLL.printerfont("100", "250", "3", "0", "1", "1", "Print Font Test"); //Drawing printer font
TSCLIB_DLL.windowsfont(100, 300, 24, 0, 0, 0, "ARIAL", "Windows Arial Font Test"); //Draw windows font
TSCLIB_DLL.downloadpcx("UL.PCX", "UL.PCX"); //Download PCX file into printer
TSCLIB_DLL.sendcommand("PUTPCX 100,400,"UL.PCX""); //Drawing PCX graphic
TSCLIB_DLL.printlabel("1", "1"); //Print labels
TSCLIB_DLL.closeport(); //Close specified printer driver
}
}
}
//------ 另例
[System.Runtime.InteropServices.DllImport("tsclib.dll")]
private static extern void windowsfont(int a, int b, int c,int d,int e ,int f, string g ,string h);
[System.Runtime.InteropServices.DllImport("tsclib.dll")]
private static extern void openport(string printername);
[System.Runtime.InteropServices.DllImport("tsclib.dll")]
private static extern void closeport();
[System.Runtime.InteropServices.DllImport("tsclib.dll")]
private static extern void sendcommand(string command);
[System.Runtime.InteropServices.DllImport("tsclib.dll")]
private static extern void setup(string width,string height,string speed,string density,string sensor,string vertical,string offset);
[System.Runtime.InteropServices.DllImport("tsclib.dll")]
private static extern void clearbuffer();
[System.Runtime.InteropServices.DllImport("tsclib.dll")]
private static extern void printlabel(string Set,string Copy);
private void button1_Click(object sender, System.EventArgs e)
{
openport("TSC TTP-343");
setup("100","65","3","10","0","3","0");
clearbuffer();
windowsfont(50,30,70,0,0,0,"黑体","索书号:");
printlabel("1", "1");
closeport();
}
#region 调用TSC打印机打印条码
/// <summary>
/// 调用TSC打印机打印条码
/// </summary>
/// <param name="title">打印的标题</param>
/// <param name="barCode">打印的条码编号</param>
public static void TSC(string title, string barCode)
{
// 打开 打印机 端口.
TSCLIB_DLL.openport(p_port);
// 设置标签 宽度、高度 等信息.
// 宽 94mm 高 25mm
// 速度为4
// 字体浓度为8
// 使用垂直間距感測器(gap sensor)
// 两个标签之间的 间距为 3.5mm
TSCLIB_DLL.setup("94", "25", "4", "8", "0", "3.5", "0");
// 清除缓冲信息
TSCLIB_DLL.clearbuffer();
// 发送 TSPL 指令.
// 设置 打印的方向.
TSCLIB_DLL.sendcommand("DIRECTION 1");
// 打印文本信息.
// 在 (176, 16) 的坐标上
// 字体高度为34
// 旋转的角度为 0 度
// 2 表示 粗体.
// 文字没有下划线.
// 字体为 黑体.
// 打印的内容为:title
TSCLIB_DLL.windowsfont(176, 16, 34, 0, 2, 0, "宋体", title);
// 打印条码.
// 在 (176, 66) 的坐标上
// 以 Code39 的条码方式
// 条码高度 130
// 打印条码的同时,还打印条码的文本信息.
// 旋转的角度为 0 度
// 条码 宽 窄 比例因子为 7:12
// 条码内容为:barCode
TSCLIB_DLL.barcode("176", "66", "39", "130", "1", "0", "7", "12", barCode);
#region 请求sendcommand指令,打印二维码
//功能:繪製QRCODE二維條碼
//語法:
//QRCODE X, Y, ECC Level, cell width, mode, rotation, [model, mask,]"Data string”
//參數說明
//X QRCODE條碼左上角X座標
//Y QRCODE條碼左上角Y座標
//ECC level 錯誤糾正能力等級
//L 7%
//M 15%
//Q 25%
//H 30%
//cell width 1~10
//mode 自動生成編碼/手動生成編碼
//A Auto
//M Manual
//rotation 順時針旋轉角度
//0 不旋轉
//90 順時針旋轉90度
//180 順時針旋轉180度
//270 順時針旋轉270度
//model 條碼生成樣式
//1 (預設), 原始版本
//2 擴大版本
//mask 範圍:0~8,預設7
//Data string 條碼資料內容
#endregion
string command = "QRCODE 176,8,Q,8,A,0,M2,S7,\"" + barCode + "\"";
TSCLIB_DLL.sendcommand(command);
// 打印.
TSCLIB_DLL.printlabel("1", "1");
// 关闭 打印机 端口
TSCLIB_DLL.closeport();
}
#endregion
2025年6月12日 星期四
2025年5月14日 星期三
TRY CATCH
在較早的 SQL 版本,要檢測 TSQL 是否有發生執行錯誤,都只能透過判斷 @@ERROR 全域變數,直到 SQL2005 才新增了 TRY...CATCH 這個結構化的例外處理功能。 它採用和程式語言中的 TRY...CATCH 類似的語法,在 TRY 區塊內放的是一般陳述式,CATCH 區塊內放的是錯誤處理的陳述式。
使用 TRY...CATCH 結構,若執行的 TSQL 發生了錯誤,錯誤訊息將不會傳到呼叫端,除非透過 RAISERROR 再送出錯誤訊息。
取得錯誤訊息的函式:
當使用 TRY...CATCH 時,你可以在 CATCH 區塊中使用以下函式以取得與錯誤訊息相關的資訊:
ERROR_NUMBER :發生錯誤的錯誤代碼
ERROR_MESSAGE :發生錯誤的錯誤訊息
ERROR_SEVERITY :發生錯誤的錯誤層級
ERROR_STATE :發生錯誤的錯誤狀態
ERROR_PROCEDURE :發生錯誤的程序名稱
ERROR_LINE :發生錯誤的行數
BEGIN TRY
INSERT Emp(EmpName, DepNo) Values (@EmpName, 1)
INSERT Emp(EmpName, DepNo) Values (@EmpName, 1)
END TRY
BEGIN CATCH
PRINT '錯誤代碼:' + cast(ERROR_NUMBER() as varchar(5)) + char(13) +
'錯誤訊息:' + ERROR_MESSAGE()
RAISERROR('資料寫入錯誤',16,10)
END CATCH;
以上函式,若不是在 CATCH 區塊中使用,都將回傳 NULL 。
2025年5月7日 星期三
2025年5月6日 星期二
DriveInfo.GetDrives 取所有磁碟
參考引用:DriveInfo.GetDrives Method
---
Imports System.IO
Imports System
Class Test
Public Shared Sub Main()
Dim allDrives As DriveInfo() = DriveInfo.GetDrives()
For Each d As DriveInfo In allDrives
Console.WriteLine("Drive {0}", d.Name)
Console.WriteLine(" Drive type: {0}", d.DriveType)
If d.IsReady Then
Console.WriteLine(" Volume label: {0}", d.VolumeLabel)
Console.WriteLine(" File system: {0}", d.DriveFormat)
Console.WriteLine(" Available space to current user:{0, 15} bytes", d.AvailableFreeSpace)
Console.WriteLine(" Total available space: {0, 15} bytes", d.TotalFreeSpace)
Console.WriteLine(" Total size of drive: {0, 15} bytes ", d.TotalSize)
End If
Next
End Sub
End Class
2025年4月23日 星期三
2025年3月3日 星期一
2025年2月19日 星期三
2025年2月18日 星期二
2025年2月17日 星期一
WebClient Download json
參考引用:How To Display JSON Data Into GridView
----
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace _5M_Solution
{
public partial class Harqat_Maqbozat_Grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetJsonData();
}
}
public void GetJsonData()
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string json = (new WebClient()).DownloadString("https://receipt-voucher-default-rtdb.firebaseio.com/receipts.json");
Dictionary<string, object> values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
List<Receipt> receipts = new List<Receipt>();
foreach (var entry in values)
{
receipts.Add(JsonConvert.DeserializeObject<Receipt>(entry.Value.ToString()));
}
gvDetails.DataSource = receipts;
gvDetails.DataBind();
}
public class Receipt
{
public string amount { get; set; }
public string branch_num { get; set; }
public string machineID { get; set; }
public string shift { get; set; }
public string userID { get; set; }
public string voucher_date { get; set; }
public string voucher_number { get; set; }
}
public void ExportExcel()
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "5M_MaqbozatDetails.xls"));
Response.ContentType = "application/ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter html = new System.Web.UI.HtmlTextWriter(writer);
GetJsonData();
//dl_JsonDetails.DataBind();
gvDetails.RenderControl(html);
Response.Write(writer.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex)
{
}
}
protected void btn_ExportExcel_Click(object sender, EventArgs e)
{
ExportExcel();
}
protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDetails.PageIndex = e.NewPageIndex;
this.GetJsonData();
}
protected void dd_SearchByBranchNo_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
How To Display JSON Data Into GridView
參考引用:How To Display JSON Data Into GridView
---
"-MuPh0RFdkXA6Jw5wYxp": {
"amount": "10000.0",
"branch_num": "001",
"machineID": "VB12213C20156",
"shift": 2,
"userID": "7",
"voucher_date": "2022-01-27T11:42:56",
"voucher_number": "156202200017"
}
public DataTable jsonDataDiplay()
{
StreamReader sr = new StreamReader(Server.MapPath("TrainServiceAlerts.json"));
string json = sr.ReadToEnd();
dynamic table = JsonConvert.DeserializeObject(json);
DataTable newTable = new DataTable();
newTable.Columns.Add("amount", typeof(string));
newTable.Columns.Add("branch_num", typeof(string));
newTable.Columns.Add("machineID", typeof(string));
newTable.Columns.Add("shift", typeof(string));
newTable.Columns.Add("userID", typeof(string));
newTable.Columns.Add("voucher_date", typeof(string));
newTable.Columns.Add("voucher_number", typeof(string));
foreach (var row in table.value.data)
{
newTable.Rows.Add(row.amount, row.branch_num, row.machineID, row.shift,row.userID,row.voucher_date,row.voucher_number);
}
return newTable;
}
GridView.DataSource = newTable ;
GridView.DataBind();
2025年2月16日 星期日
2025年2月15日 星期六
使用 HttpClient 類別提出 HTTP 要求
請參考來源:使用 HttpClient 類別提出 HTTP 要求
---
HttpClient
提出 HTTP 要求
若要提出 HTTP 要求,您可以呼叫下列任何 API:
HTTP 方法 API
GET HttpClient.GetAsync
GET HttpClient.GetByteArrayAsync
GET HttpClient.GetStreamAsync
GET HttpClient.GetStringAsync
POST HttpClient.PostAsync
PUT HttpClient.PutAsync
PATCH HttpClient.PatchAsync
DELETE HttpClient.DeleteAsync
HttpClient.SendAsync USER SPECIFIED 要求表示 SendAsync 方法接受任何有效的 HttpMethod
2025年2月14日 星期五
2025年2月10日 星期一
清除 mstsc 记录
---
方法2. 通过命令提示符删除记录
在方法1中我们可以手动将远程桌面连接历史删除,如果觉得太麻烦或太费时间,我们也可以通过命令提示符删除远程桌面连接记录。
步骤1. 按“Win + R”键,然后输入“CMD”打开命令提示符。
步骤2. 然后依次输入以下命令,并在每个命令输入完成按下回车键。
reg delete “HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default” /va /f
reg delete “HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers” /f
reg add “HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers”
del /ah %homepath%\documents\default.rdp
TcpClient port
Imports System.Diagnostics
Imports System.Net.Sockets
Imports System.Threading
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ip = "192.168.1.10" 'SQL Server主機的IP位址。
Dim port = 1433 'SQL Server的port預設是1433。
Dim sw As Stopwatch = New Stopwatch()
sw.Start()
Dim isConnection = TestConn(ip, port)
sw.[Stop]()
Dim message = String.Empty
If isConnection Then
message = "連線成功。 經過{0}秒。"
Else
message = "連線失敗了! 經過{0}秒!"
End If
Dim t = sw.ElapsedMilliseconds / 1000.0
MessageBox.Show(String.Format(message, t))
End Sub
Public Function TestConn(ip As String, port As Integer) As Boolean
Try
Using tc As TcpClient = New TcpClient()
Dim result As IAsyncResult = tc.BeginConnect(ip, port, Nothing, Nothing)
Dim start = Date.Now
Do
SpinWait.SpinUntil(Function() False, 100)
If result.IsCompleted Then Exit Do
Loop While Date.Now.Subtract(start).TotalSeconds < 0.3
If result.IsCompleted Then
tc.EndConnect(result)
Return True
End If
tc.Close()
If Not result.IsCompleted Then
Return False
End If
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
Throw
End Try
Return False
End Function
End Class
2025年2月7日 星期五
安裝WordPress到Windows
6步輕鬆安裝WordPress到Windows和Mac電腦上
https://loyseo.com/zh-hant/tutorial/wordpress/install-wordpress/pc-local/
zh-tw:安裝WordPress
https://codex.wordpress.org/zh-tw:%E5%AE%89%E8%A3%9DWordPress
********
如何下載安裝 WordPress 站台,設定資料庫連線,建立全新部落格 (適用 IIS 架站)
https://ithelp.ithome.com.tw/m/articles/10260063
Windows Server IIS 如何安裝 PHP 網頁伺服器
https://blog.hungwin.com.tw/windows-server-iis-php-install/
********
wordpress自己架設網站,快速架站wordpress教學
https://www.koc.com.tw/archives/165785
WordPress教學-20分鐘新手網站架設流程
https://jclassroom.net/20-minutes-create-wordpress-website/
WordPress 後台教學:給新手的操作教學(全指南)
https://frankknow.com/wordpress-build-teach/
2025年2月4日 星期二
MSSQL stored procedure TRY...CATCH
參考來源:TRY...CATCH (Transact-SQL)
BEGIN TRY
SELECT aa/0 FROM DEMO
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_MESSAGE() AS ErrorMessage;
END CATCH