---
還有各種轉換,有需要的可看看 探索更多
引用來源: [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. 程式前後文,也有可能造成此問題,前半寫好,後段尚未完成,但只想驗證前面時,也會 發生,會發生在有參數互相傳遞的程式間
做為紀錄方便自己查詢
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
使用 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
--
真是好用的工具
在 Visual Studio 中,您可以從 JSON 或 XML 檔案複製文字,然後將文本作為類粘貼到 C# 或 Visual Basic 代碼中。 為此,請選擇Edit>Paste Special 並選擇 Paste JSON As Classes 或 Paste XML As Classes。
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
參考引用: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
---
"-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();
請參考來源:使用 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
參考引用 用户权限与 Visual Studio
---
修改快捷方式
此外,還可以透過快捷應用程式以利於始終利用。
Windows 10
開啟「開始」功能表,捲動到您正在使用的 Visual Studio 版本,然後按一下「更多」 >「開啟檔案位置」。
在檔案總管中,找到你使用的版本的 Visual Studio 捷徑。
在 Windows 10 桌面上,您可以使用 Visual Studio 捷徑,然後進入「屬性」。
選擇「進階」按鈕,來到「以管理員身分執行」的地方。
選擇“確定”,然後再選擇“確定”。
Windows 11
選擇“開始”按鈕,然後在“搜尋”框中輸入“Visual Studio”。
在搜尋結果中,您可在「開啟檔案位置」中找到「Visual Studio 2019」或「Visual Studio 2022」。
在檔案總管中,找到你使用的版本的 Visual Studio 捷徑。
在 Windows 11 桌面上,您可以快速使用 Visual Studio,然後進行「屬性」。
接下來,選擇「進階」按鈕,前往「以管理員身分執行」所在地。
選擇“確定”並關閉該對話框。
參考引用來源 C#-DataGridView控件中增加合计和平均值
統計採用: ds.Tables[tablename].Compute("SUM(當月金額)", "").ToString();
---
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SumAndAverage
{
public partial class Frm_Main : Form
{
public Frm_Main()
{
InitializeComponent();
}
private List<Fruit> G_Fruit;
private void Frm_Main_Load(object sender, EventArgs e)
{
G_Fruit = new List<Fruit>() {//创建集合并添加元素
new Fruit(){Name="苹果",Price=30},
new Fruit(){Name="橘子",Price=40},
new Fruit(){Name="鸭梨",Price=33},
new Fruit(){Name="水蜜桃",Price=31}};
dgv_Message.Columns.Add("Fruit", "水果");//添加列
dgv_Message.Columns.Add("Pric", "价格");//添加列
foreach (Fruit f in G_Fruit)//添加元素
{
dgv_Message.Rows.Add(new string[]
{
f.Name,
f.Price.ToString()
});
}
dgv_Message.Columns[0].Width = 200;//设置列宽度
dgv_Message.Columns[1].Width = 170;//设置列宽度
float sum = 0;//定义float类型变量
G_Fruit.ForEach(
(pp) =>
{
sum += pp.Price;//求和
});
dgv_Message.Rows.Add(new string[] //在新列中显示平均值及合计信息
{
"合计: "+sum.ToString()+" 元",
"平均价格: "+(sum/G_Fruit.Count).ToString()+" 元"
});
}
}
}
--
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
win7 x64 C# 讀取 delphi Paradox db
Paradox 4 database connect and edit inside c#
##
C# Application to import paradox data to SQL Server
----------------
C# code:
var strPath = @"D:\Test\4#新程序全兼容\4#新程序全兼容\Data";
string myConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=Paradox 5.x;";
string mySelectQuery = "select * from TD2002002;";
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
myConnection.Open();
OleDbDataAdapter da = new OleDbDataAdapter(mySelectQuery, myConnection);
DataSet ds = new DataSet();
da.Fill(ds);
----------
VB code:
Dim strPath As Object = "D:\Test\4#新程序全兼容\4#新程序全兼容\Data"
Dim myConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=Paradox 5.x;"
Dim mySelectQuery As String = "select * from TD2002002;"
Dim myConnection As New OleDbConnection(myConnectionString)
myConnection.Open()
Dim da As New OleDbDataAdapter(mySelectQuery, myConnection)
Dim ds As New DataSet()
da.Fill(ds)
Using TLS1.2 in .Net 2.0, .Net 3.0, .Net 3.5 and .Net 4.0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType)
Dim json As String = (New WebClient).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json")
Response.Write(json)
End If
End Sub