.NET 类目

VB.net 都忘光了,好在还有C#。

程序结构

评分 0.00, 满分 5星 0 票 No comments

偶尔看看程序总是会有些收益~
C# 中的组织结构的关键概念是程序 (program)、命名空间 (namespace)、类型 (type)、成员 (member) 和程序集 (assembly)。C# 程序由一个或多个源文件组成。程序中声明类型,类型包含成员,并且可按命名空间进行组织。类和接口就是类型的示例。字段 (field)、方法、属性和事件是成员的示例。在编译 C# 程序时,它们被物理地打包为程序集。程序集通常具有文件扩展名 .exe 或 .dll,具体取决于它们是实现应用程序 (application) 还是实现库 (library)。
下面的示例

using System;
namespace Acme.Collections
{
	public class Stack
	{
		Entry top;
		public void Push(object data) {
			top = new Entry(top, data);
		}
		public object Pop() {
			if (top == null) throw new InvalidOperationException();
			object result = top.data;
			top = top.next;
			return result;
		}
		class Entry
		{
			public Entry next;
			public object data;
			public Entry(Entry next, object data) {
				this.next = next;
				this.data = data;
			}
		}
	}
}

在名为 Acme.Collections 的命名空间中声明了一个名为 Stack 的类。Acme.Collections.Stack 是此类的完全限定名。该类包含几个成员:一个名为 top 的字段,两个分别名为 Push 和 Pop 的方法和一个名为 Entry 的嵌套类。Entry 类还包含三个成员:一个名为 next 的字段、一个名为 data 的字段和一个构造函数。假定将此示例的源代码存储在文件 acme.cs 中,执行以下命令行:
csc /t:library acme.cs
将此示例编译为一个库(没有 Main 入口点的代码),并产生一个名为 acme.dll 的程序集。
程序集包含中间语言 (Intermediate Language, IL) 指令形式的可执行代码和元数据 (metadata) 形式的符号信息。在执行程序集之前,.NET 公共语言运行时的实时 (JIT) 编译器将程序集中的 IL 代码自动转换为特定于处理器的代码。
由于程序集是一个自描述的功能单元,它既包含代码又包含元数据,因此,C# 中不需要 #include 指令和头文件。若要在 C# 程序中使用某特定程序集中包含的公共类型和成员,只需在编译程序时引用该程序集即可。例如,下面的程序将使用来自 acme.dll 程序集的 Acme.Collections.Stack 类:

using System;
using Acme.Collections;
class Test
{
	static void Main() {
		Stack s = new Stack();
		s.Push(1);
		s.Push(10);
		s.Push(100);
		Console.WriteLine(s.Pop());
		Console.WriteLine(s.Pop());
		Console.WriteLine(s.Pop());
	}
}

如果此程序存储在文件 test.cs 中,那么在编译 test.cs 时,可以使用编译器的 /r 选项引用 acme.dll 程序集:
csc /r:acme.dll test.cs
这样将创建名为 test.exe 的可执行程序集,运行结果如下:
100
10
1
C# 允许将一个程序的源文本存储在多个源文件中。在编译多个文件组成的 C# 程序时,所有源文件将一起处理,并且源文件可以自由地相互引用 — 从概念上讲,就像是在处理之前将所有源文件合并为一个大文件。C# 中从不需要前向声明,因为除了极少数的例外情况,声明顺序无关紧要。C# 不限制一个源文件只能声明一个公共类型,也不要求源文件的名称与该源文件中声明的类型匹配。

[转]C#连接Oracle数据库

评分 0.00, 满分 5星 0 票 No comments

C#连接Oracle数据库的字符串如下:

Data Source=GDBZH;User Id=zhangf;Password=guangy;

需要特别指出的是Data Source这个值是什么,从哪里获取到(后面两个,能在这里看到的,估计都知道意思了吧,后面两个不解析了)。

Data Source:从字面上解释就是数据源,这个数据源是从Oracle的tnsnames.ora文件中去找的。而并非是在系统的“管理工具”下的“数据源(ODBC)”中找。这个tnsnames.ora文件是在Oracle的安装目录下的“network\admin\”下。如我这个例子的GDBZH是这样的:

 
GDBZH =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = GDBZH)
    )
  )
 

这里说明一下:SERVICE_NAME = GDBZH 这个应该是Oracle是数据库的名称。在安装时如果没改的话,一般默认是ORCL。
Read more…

[原创]VB.net 通过Google Map API计算路程距离

评分 0.00, 满分 5星 0 票 No comments

利用Google Directions API (Google Map) http://code.google.com/intl/zh-CN/apis/maps/documentation/directions/
和VB.net 输入目的地(支持中文地址、经纬度等)计算出距离。
如:输入 北京|上海|天津
运行程序 会计算从A地出发依次到北京、上海、天津 三地的总距离,可选择是否包含返回的距离(天津到A地的距离)。
如果需要线路优化 可以参照API 介绍中的 optimize:true。开启后会自动安排路线。

已经在VB.net 2003 通过测试。

做的着急有些地方直接复制的,代码没有优化,有些重复,但不影响最终使用。

'需要以下命名空间
Imports System.web
Imports System.Xml
Imports System.IO

'需要声明的变量
Dim gstrPatch As String = "C:\XXX\map.xml"

    Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
     '判断输入的目的地是否为空。
        If txtROAD_ROUTE.Text = "" Then Exit Sub

        Try

          If MsgBox("路程距离数据会受到网络、关键字的影响,可能与实际距离相差很大,仅供参考。", MsgBoxStyle.YesNo, "系统提示") = MsgBoxResult.No Then Exit Sub
  
          Dim arrROAD As String()
          Dim strWaypoints As String  
          Dim i As Integer = 0
  
          arrROAD = txtROAD_ROUTE.Text.Split("|")
          Dim arrCalc(arrROAD.Length - 1) As String
      '对搜索的目的地编码
          For t As Integer = 0 To arrROAD.Length - 1
              arrROAD(t) = HttpUtility.UrlEncode(arrROAD(t), System.Text.Encoding.UTF8)  
          Next
         
      '编码重组
          For t As Integer = 0 To arrROAD.Length - 2
              If strWaypoints = "" Then
                  strWaypoints = arrROAD(t)
              Else
                  strWaypoints = strWaypoints & "|" & arrROAD(t)
              End If
          Next
         
      '39.049435,121.782503 为出发地 经纬度,可以替换成路名、地名等,注意中文请注意转码。
          Dim strURL As String
          strURL = "<a href="http://maps.google.com/maps/api/directions/xml?origin=39.049435,121.782503&destination">http://maps.google.com/maps/api/directions/xml?origin=39.049435,121.782503&destination</a>=" & arrROAD(arrROAD.Length - 1) & _
                  "&waypoints=" & strWaypoints & _
                  "&sensor=false"
  
          Dim myWebClient As New System.Net.WebClient
          'myWebClient.DownloadFile("<a href="http://maps.google.com/maps/api/directions/xml?origin=39.049435,121.782503&destination">http://maps.google.com/maps/api/directions/xml?origin=39.049435,121.782503&destination</a>=" & strdifang & "&waypoints=&sensor=false", "C:\msdn.xml")
          myWebClient.DownloadFile(strURL, gstrPatch)
  
          Dim xmlDoc As New XmlDocument
          Dim XmlFileName As String = gstrPatch
  
          If File.Exists(XmlFileName) Then
              xmlDoc.Load(XmlFileName)
              Dim nodeList As XmlNodeList = xmlDoc.SelectSingleNode("DirectionsResponse").ChildNodes
              Dim xn1 As XmlNode
              Dim xn2 As XmlNode
              Dim xn3 As XmlNode
                  For Each xn1 In nodeList
                      For Each xn2 In xn1
                          For Each xn3 In xn2
                              If xn3.Name = "distance" Then
                                  arrCalc(i) = xn3.ChildNodes.Item(1).InnerText
                                  i = i + 1
                              End If
                          Next
                      Next
                  Next
          End If
  
          Dim douKM As Double
          Dim strLast As String
  
          If MsgBox("是否计算往返路程?", MsgBoxStyle.YesNo, "系统提示") = MsgBoxResult.Yes Then
              strURL = "<a href="http://maps.google.com/maps/api/directions/xml?origin">http://maps.google.com/maps/api/directions/xml?origin</a>=" & arrROAD(arrROAD.Length - 1) & "&destination=39.049435,121.782503" & _
                       "&sensor=false"
              myWebClient.DownloadFile(strURL, gstrPatch)
              '*计算
  
              Dim xmlDoc2 As New XmlDocument
              Dim XmlFileName2 As String = gstrPatch
  
              If File.Exists(XmlFileName2) Then
                  xmlDoc2.Load(XmlFileName2)
                  Dim nodeList As XmlNodeList = xmlDoc2.SelectSingleNode("DirectionsResponse").ChildNodes
                  Dim xn12 As XmlNode
                  Dim xn22 As XmlNode
                  Dim xn32 As XmlNode
                      For Each xn12 In nodeList
                          For Each xn22 In xn12
                              For Each xn32 In xn22
                                  If xn32.Name = "distance" Then
                                      strLast = xn32.ChildNodes.Item(1).InnerText
                                  End If
                              Next
                          Next
                      Next
              End If
  
              For r As Integer = 0 To arrCalc.Length - 1
                  douKM = douKM + CType(Replace(arrCalc(r), " km", ""), Double)
              Next
  
              douKM = douKM + CType(Replace(strLast, " km", ""), Double)
          Else
              For r As Integer = 0 To arrCalc.Length - 1
                  douKM = douKM + CType(Replace(arrCalc(r), " km", ""), Double)
              Next
          End If
      '显示距离 KM 单位
          txtDISTANCE.Text = douKM

        Catch ex As Exception
            MsgBox("获取距离数据失败。")
        End Try

    End Sub

[原创]VB.net 根据日期取本周第一天 可自定义

评分 0.00, 满分 5星 0 票 No comments

.net 里面的每周第一天默认是星期日,实在是不符合中国人的行为习惯。
以下函数 可以返回 传入日期所在星期的第一天,可自定义星期的第一天 是星期一、二、三 …  … 日

  Private Function FirstDayOfWeek(ByVal day As DateTime, ByVal weekStarts As DayOfWeek) As DateTime
        Dim d As DateTime = day
        Do While d.DayOfWeek <> weekStarts
            d = d.AddDays(-1)
        Loop
        Return d
    End Function

[原创]VB.net Group Box 窗口内 自由 拖拽

评分 0.00, 满分 5星 0 票 No comments
#Region "Group Box 拖拽"

    Dim CurrX As Integer
    Dim CurrY As Integer
    Dim MousX As Integer
    Dim MousY As Integer
    Dim MovBoll As Boolean

    '*--将 gpbMATERIAL_INFO 更换为 自己Group Box的名字
    Private Sub gpbATT_FILE_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gpbMATERIAL_INFO.MouseDown
        MousX = e.X
        MousY = e.Y
        MovBoll = True
    End Sub

    Private Sub gpbATT_FILE_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gpbMATERIAL_INFO.MouseMove
         If MovBoll = True Then
            CurrX = sender.Left - MousX + e.X
            CurrY = sender.Top - MousY + e.Y
            sender.Location = New System.Drawing.Point(CurrX, CurrY)
        End If
    End Sub

    Private Sub gpbATT_FILE_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gpbMATERIAL_INFO.MouseUp
        MovBoll = False
    End Sub


#End Region

[原创]VB.net 使用XML 对 FpSpread 列宽记忆

评分 0.00, 满分 5星 0 票 1 comment
'需要引入的 命名空间
Imports System.Xml
Imports System.IO

#Region "XML 读取 写入 生成"
Private Sub createXML(ByVal xmlFileName As String)
	Try
	
		Dim writer As New Xml.XmlTextWriter(xmlFileName, System.Text.Encoding.GetEncoding("utf-8"))
		'使用自动缩进便于阅读
		writer.Formatting = Xml.Formatting.Indented
		writer.WriteRaw("<!--l version=""1.0"" encoding=""utf-8""-->")
		writer.WriteRaw("<!--   Xing   -->")
		'书写根元素()
		writer.WriteStartElement("xx")
		'关闭根元素
		writer.WriteFullEndElement()
		'将XML写入文件并关闭writer
		writer.Close()
	
	Catch ex As System.Exception
		MsgBox(ex.Message & vbCrLf & ex.StackTrace)
	End Try
End Sub

Private Sub FpSpread_Column_Size_load(ByVal FpSpread As FarPoint.Win.Spread.FpSpread)
	Dim xmlDoc As New XmlDocument
	Dim XmlFileName As String = "C:\XX\INI\FpSpread_Config.xml" '修改为实际XML路径
	Dim intCol As Integer
	
	Try
	
		If File.Exists(XmlFileName) Then
			xmlDoc.Load(XmlFileName)		
			Dim nodeList As XmlNodeList = xmlDoc.SelectSingleNode("xx").ChildNodes '获取xx节点的所有子节点
			Dim xn As XmlNode
			
			For Each xn In nodeList
				Dim xe As XmlElement = CType(xn, XmlElement)				
				If xe.GetAttribute("form") = Me.Name And xe.GetAttribute("Name") = FpSpread.Name Then				
					Dim nls As XmlNodeList = xe.ChildNodes '继续获取xe子节点的所有子节点
					Dim xn1 As XmlNode
					
					For Each xn1 In nls '遍历
						Dim xe2 As XmlElement = CType(xn1, XmlElement) '转换类型
						
						intCol = xe2.Name.Substring(1, xe2.Name.Length - 1)
						FpSpread.ActiveSheet.Columns(Val(intCol)).Width = Integer.Parse(xe2.InnerText)					
					Next xn1
				
				End If
			
			Next
		End If
		
	Catch ex As System.Exception
		File.Delete(XmlFileName)
	End Try
End Sub

Private Sub FpSpread_Column_Size_save(ByVal FpSpread As FarPoint.Win.Spread.FpSpread)
	Dim xmlDoc As New XmlDocument
	Dim XmlFileName As String = "C:\xx\INI\FpSpread_Config.xml" '修改为实际XML路径
	Dim intRecord As Integer
	
	Try
	If File.Exists(XmlFileName) = False Then
		createXML(XmlFileName)
	End If
	
	xmlDoc.Load(XmlFileName)	
	Dim nodeList As XmlNodeList = xmlDoc.SelectSingleNode("xx").ChildNodes '获取xx节点的所有子节点
	Dim xn As XmlNode
	
		For Each xn In nodeList '遍历所有子节点
			Dim xe As XmlElement = CType(xn, XmlElement) '将子节点类型转换为XmlElement类型
			If xe.GetAttribute("form") = Me.Name And xe.GetAttribute("Name") = FpSpread.Name Then '如果form属性值为“当前窗口”Name为 当前spread 那么就 清空下面的数据
			intRecord += 1
			xe.RemoveAll() '*清空数据
			
				If intRecord < 2 Then
				xe.SetAttribute("form", Me.Name)
				xe.SetAttribute("Name", FpSpread.Name)
				
				Dim child_node As XmlElement
					For i As Integer = 0 To FpSpread.ActiveSheet.Columns.Count - 1
						child_node = xmlDoc.CreateElement("C" & i)
						child_node.InnerText = FpSpread.ActiveSheet.Columns(i).Width
						xe.AppendChild(child_node)
					
					Next
				End If
			End If
		Next xn
	
	If intRecord < 1 Then
		Dim root As XmlNode = xmlDoc.SelectSingleNode("xx")
		Dim xe1 As XmlElement = xmlDoc.CreateElement("spread")
		xe1.SetAttribute("form", Me.Name)
		xe1.SetAttribute("Name", FpSpread.Name)
		
		Dim child_node As XmlElement
			For i As Integer = 0 To FpSpread.ActiveSheet.Columns.Count - 1
			child_node = xmlDoc.CreateElement("C" & i)
			child_node.InnerText = FpSpread.ActiveSheet.Columns(i).Width
			xe1.AppendChild(child_node)
	
		Next
	
		root.AppendChild(xe1) '添加到节点中
	
	End If
	
	xmlDoc.Save(XmlFileName) '保存。
	Catch ex As System.Exception
	
	End Try
	
End Sub
#End Region

#Region "Form Load"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
	'spread load
	FpSpread_Column_Size_load(Me.spListMain)
End Sub
#End Region

#Region "form 关闭"
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
	FpSpread_Column_Size_save(Me.spListMain)
End Sub
#End Region

生成的XML文件内如如下

<?xml version="1.0" encoding="utf-8"?>
<!--   Xing   -->
<xx>
  <spread form="FORM1" Name="spListMain">
    <C0>60</C0>
    <C1>90</C1>
    <C2>106</C2>
    <C3>60</C3>
    <C4>80</C4>
    <C5>60</C5>
    <C6>178</C6>
    <C7>60</C7>
    <C8>119</C8>
    <C9>82</C9>
    <C10>145</C10>
    <C11>88</C11>
    <C12>123</C12>
    <C13>60</C13>
  </spread>
  <spread form="FORM1" Name="spListList">
    <C0>17</C0>
    <C1>65</C1>
    <C2>65</C2>
    <C3>31</C3>
    <C4>60</C4>
    <C5>65</C5>
    <C6>118</C6>
    <C7>69</C7>
    <C8>62</C8>
    <C9>71</C9>
    <C10>34</C10>
    <C11>52</C11>
    <C12>58</C12>
    <C13>58</C13>
    <C14>59</C14>
    <C15>106</C15>
    <C16>34</C16>
    <C17>34</C17>
  </spread>
  <spread form="FORM1" Name="spList1">
    <C0>60</C0>
    <C1>60</C1>
    <C2>60</C2>
    <C3>32</C3>
    <C4>60</C4>
    <C5>71</C5>
    <C6>60</C6>
    <C7>60</C7>
    <C8>60</C8>
    <C9>60</C9>
    <C10>60</C10>
    <C11>72</C11>
    <C12>68</C12>
    <C13>70</C13>
    <C14>60</C14>
    <C15>60</C15>
    <C16>60</C16>
    <C17>60</C17>
    <C18>60</C18>
    <C19>60</C19>
    <C20>60</C20>
    <C21>60</C21>
    <C22>65</C22>
  </spread>
</xx>

VB.net 删除文件夹内所有文件

评分 0.00, 满分 5星 0 票 No comments
Imports System.IO

Public Shared Sub DeleteDir(ByVal aimPath As String)
    Try

        '判断待删除的目录是否存在,不存在则退出.    
        If (Not Directory.Exists(aimPath)) Then Exit Sub
        ' 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组    
        ' 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法    
        ' string[] fileList = Directory.GetFiles(aimPath);    
        Dim fileList() As String = Directory.GetFileSystemEntries(aimPath)
        ' 遍历所有的文件和目录    
        For Each FileName As String In fileList
        If (Directory.Exists(FileName)) Then
        ' 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件    
        DeleteDir(aimPath + Path.GetFileName(FileName))
        Else
        ' 否则直接Delete文件    
        File.Delete(aimPath + Path.GetFileName(FileName))
        End If
        Next
        '删除文件夹、不删除    
        'System.IO.Directory.Delete(aimPath, True)
        Catch ex As Exception
        MessageBox.Show(ex.ToString())
    End Try
End Sub