顯示具有 VBNET 標籤的文章。 顯示所有文章
顯示具有 VBNET 標籤的文章。 顯示所有文章

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月26日 星期二

webclient 無法建立 SSL/TLS 的安全通道

 在 framework 4.0 無法建立 tls12

只能自己新增:

in .net Framework 4.0 add

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2

2025年8月12日 星期二

Setup POST REST Webservice with ASP.net and VB.net

 Setup POST REST Webservice with ASP.net and VB.net

Add new REST Service into existing ASP.net web application

---


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


VB.NET || How To Send, Post & Process A REST API Web Request Using VB.NET

 VB.NET || How To Send, Post & Process A REST API Web Request Using VB.NET

---

很棒的code


ShareFileV3Sample

 ShareFileV3Sample

----

請參考來源:程式碼



2025年8月5日 星期二

VBNET dataGridView當掉問題

 [C#] 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月3日 星期日

Windows Form 設計工具錯誤頁面

 官方:Windows Form 設計工具錯誤頁面

---

引用:

首先嘗試什麼

您通常可以透過清理並重建專案或解決方案來排除錯誤。

尋找 方案總管視窗。

在解決方案或專案上按右鍵,然後選取 [清除]。

在解決方案或專案上按右鍵,然後選取 [重建]。

----


*** 在 VS 2022 只要關掉[方案]再重新開啟方案 就可以正常了



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年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();