|
Hi I'm using Visual studio 2010 i'm creating a invoice billing software. i can access the data from database to datagridview and calculate the sum of all products. now i want a print function so i need to make a report please help me out this
Thanks in advance.
Public Class Form1
Dim ID As String = Nothing
Dim pname As String = Nothing
Dim qty As UInteger = Nothing
Dim rate As Decimal = Nothing
Dim amt As Decimal = Nothing
Dim i As UInteger
Dim count As UInteger = Nothing
Dim totalAmt
Dim salesTax
Dim salesTaxRate
Private Sub AddProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddProduct.Click
Dim MaxRows As UInteger = Nothing
Dim pid As String
Dim found As Boolean = False
Dim Sql As String
Dim count As UInteger = Nothing
Dim con As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\IMPossible\Music\Project\BillingInvoice\BillingInvoice\InvoiceDatabase.accdb"
count = count + 1
con.Open()
Dim productAdapter As OleDb.OleDbDataAdapter = Nothing
Dim productDataSet As New DataSet
Dim validID As Boolean = True
Dim validQty As Boolean = True
Sql = "SELECT Product_ID,Product_Name,Product_Rate FROM Product_Data"
productAdapter = New OleDb.OleDbDataAdapter(Sql, con)
productAdapter.Fill(productDataSet, "Prod_Data")
If txtID.Text = "" Then
MsgBox("Enter a valid ProductID")
validID = False
End If
If txtqty.Text = "" Then
MsgBox("Enter a valid quantity")
validQty = False
End If
If validID And validQty Then
Try
qty = CInt(txtqty.Text)
ID = txtID.Text.ToUpper
Catch ex As Exception
MsgBox("qty can't be empty")
End Try
End If
MaxRows = productDataSet.Tables("Prod_Data").Rows.Count
' Get the data for the new line item.
If MaxRows = 0 Then
MsgBox("No Product Found")
Else
i = 0
Do Until i >= MaxRows
pid = productDataSet.Tables("Prod_Data").Rows(i).Item(0)
If ID = pid Then
found = True
pname = productDataSet.Tables("Prod_Data").Rows(i).Item(1)
rate = productDataSet.Tables("Prod_Data").Rows(i).Item(2)
txtpname.Text = pname
txtrate.Text = rate
amt = qty * rate
txtamt.Text = amt
DataGridView.Rows.Add(New String() {ID, pname, qty, rate, amt})
End If
i = i + 1
Loop
If found <> True Then
MsgBox("NO product found")
End If
End If
con.Close()
' Clear the total text boxes.
txtTotalAmt.Text = ""
txtTax.Text = ""
txtGrandTotal.Text = ""
txtTotalProd.Text = ""
Dim totalAmt As Integer
For Each r As DataGridViewRow In DataGridView.Rows
Dim prodAmount As Integer = CInt(r.Cells(4).Value)
totalAmt += prodAmount
Next
txtTotalProd.Text = totalAmt
' Calculate the sales tax.
salesTax = 12.5
txtTax.Text = salesTax
' Calculate the total prod
Dim totalQuantity As Integer
For Each r As DataGridViewRow In DataGridView.Rows
Dim prodQty As Integer = CInt(r.Cells(2).Value)
totalQuantity += prodQty
Next
txtTotalProd.Text = totalQuantity
' Calculate the invoice total.
Dim invoiceTotal = totalAmt + salesTax
' Display the invoice totals.
txtTotalAmt.Text = FormatCurrency(totalAmt)
txtTax.Text = FormatCurrency(salesTax)
txtGrandTotal.Text = FormatCurrency(invoiceTotal)
End Sub
End Class
|
|
|
|
|
Since you're using Access as a database, it'd seem logical to create a report in Access itself. If this application is used by more than one person, I'd suggest you upgrade to Sql Server.
For more information on building reports, go here[^].
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi.
For the life of me, I cannot get a TreeView Find to work. I have a list of drives, folders and subfolders in my TreeView. I have googled like crazy and either find repeated references to a very simple method, or convoluted methods that seem to apply to something else. Here is a very basic procedure that fails:
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
Me.TreeView1.SelectedNode = Me.TreeView1.Nodes.Find("Client Supplied Files", True)(0)
End Sub
I put the Find method in the _AfterSelect event only because I was using that event as a test area to do the find. In other words...If I clicked on any node in the tree, the event would cause the selected node to change to the one specified in the search. But alas, no go.
I have to be missing something really simple here.
Thank you for any hints!
|
|
|
|
|
treddie wrote: I have a list of drives, folders and subfolders in my TreeView. How did you load them? Something similar to this[^]? In that case not all nodes will be loaded when the control shows, only the nodes that are expanded.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hm...I like that solution MUCH better. But in the interests of trying to understand why "my" version won't work (it was an online TreeView demo that I modified slightly), no, it was a fully recursive method. Please see code below:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Go_cmd.Click
Dim drives As System.Collections.ObjectModel.ReadOnlyCollection(Of IO.DriveInfo) = My.Computer.FileSystem.Drives
Dim rootDir As String = String.Empty
For i As Integer = 0 To drives.Count - 1
System.Windows.Forms.Application.DoEvents()
rootDir = drives(i).Name
TreeView1.Nodes.Add(rootDir)
PopulateTreeView(rootDir, TreeView1.Nodes(i))
NextDrive:
Next i
End Sub
Private Sub PopulateTreeView(ByVal dir As String, ByVal parentNode As TreeNode)
Dim folder As String = String.Empty
Try
Dim folders() As String = IO.Directory.GetDirectories(dir)
If folders.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each folder In folders
System.Windows.Forms.Application.DoEvents()
childNode = New TreeNode(folder)
parentNode.Nodes.Add(childNode)
PopulateTreeView(folder, childNode)
Next folder
End If
Catch ex As System.IO.IOException
parentNode.Nodes.Add(folder & ": Drive not Ready")
Catch ex As UnauthorizedAccessException
parentNode.Nodes.Add(folder & ": Access Denied")
End Try
End Sub
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
If Text <> String.Empty Then
Dim arr As TreeNode() = TreeView1.Nodes.Find("Client Supplied Files", True)
For i = 0 To arr.Length - 1
TreeView1.SelectedNode = arr(i)
Next
End If
End Sub
End Class
|
|
|
|
|
Unless some other members beats me to it, I'll write a search-implementation tomorrow.
Now,
|
|
|
|
|
Thank you very much, and no rush.
|
|
|
|
|
Here is a code that I made by several examples that I found:
Public Class cTreeviewFind
Inherits TreeView
#Region "Functions"
Function SearchTree(ByVal root As TreeNode, ByVal text As String) As System.Collections.Generic.List(Of TreeNode)
Dim nodes As New System.Collections.Generic.List(Of TreeNode)()
If root.Text.ToUpper().Contains(text.ToUpper()) Then
nodes.Add(root)
End If
For Each node As TreeNode In root.Nodes
Dim subNodes As System.Collections.Generic.List(Of TreeNode) = SearchTree(node, text)
If (subNodes.Count > 0) Then
nodes.AddRange(subNodes)
End If
Next
Return nodes
End Function
Public Function FindNode(ByVal _nodeCollection As TreeNode, ByVal SearchVal As String, Optional ByVal CaseSensitief As Boolean = False, Optional ByVal CompleteValue As Boolean = False, Optional ByVal refind As Boolean = False) As TreeNode
Dim tmpNode As TreeNode = Nothing
Static bFoundSelectedNode As Boolean
If refind Then bFoundSelectedNode = False
If Me.SelectedNode.Equals(Me.Nodes(0)) Then
bFoundSelectedNode = True
End If
For Each _c As TreeNode In _nodeCollection.Nodes
If _c.Equals(Me.SelectedNode) Then
bFoundSelectedNode = True
End If
If bFoundSelectedNode = False Then
If _c.Nodes.Count > 0 Then
tmpNode = FindNode(_c, SearchVal, CaseSensitief, CompleteValue)
If bFoundSelectedNode = True AndAlso Not tmpNode Is Nothing Then
Return tmpNode
End If
End If
Else
If CaseSensitief Then
If CompleteValue Then
If _c.Text = SearchVal AndAlso _c.Equals(Me.SelectedNode) = False Then Return _c
If _c.Nodes.Count > 0 Then tmpNode = FindNode(_c, SearchVal, CaseSensitief, CompleteValue)
If Not tmpNode Is Nothing Then
Return tmpNode
End If
Else
If _c.Text.IndexOf(SearchVal) >= 0 AndAlso _c.Equals(Me.SelectedNode) = False Then Return _c
If _c.Nodes.Count > 0 Then tmpNode = FindNode(_c, SearchVal, CaseSensitief, CompleteValue)
If Not tmpNode Is Nothing Then
Return tmpNode
End If
End If
Else
If CompleteValue Then
If _c.Text.ToLower = SearchVal.ToLower AndAlso _c.Equals(Me.SelectedNode) = False Then Return _c
If _c.Nodes.Count > 0 Then tmpNode = FindNode(_c, SearchVal, CaseSensitief, CompleteValue)
If Not tmpNode Is Nothing Then
Return tmpNode
End If
Else
If _c.Text.ToLower.IndexOf(SearchVal.ToLower) >= 0 AndAlso _c.Equals(Me.SelectedNode) = False Then Return _c
If _c.Nodes.Count > 0 Then tmpNode = FindNode(_c, SearchVal, CaseSensitief, CompleteValue)
If Not tmpNode Is Nothing Then
Return tmpNode
End If
End If
End If
End If
Next
Return Nothing
End Function
#End Region 'functions
End Class
Jan
|
|
|
|
|
FINALLY! One that actually works! . Now the big $30,000 question is, why doesn't the method that MS and so many others suggest NOT work?
Me.TreeView1.SelectedNode = Me.TreeView1.Nodes.Find("Client Supplied Files", True)
|
|
|
|
|
treddie wrote: Now the big $30,000 question is, why doesn't the method that MS and so many others suggest NOT work? Here's a free answer to an expensive question; due to the difference between the nodes' key and it's label. The "find" method works on keys[^] (the name of the node), not on the text being displayed. If you only pass a single string when creating a node, it will not have a name. Try the example below and play a bith with it.
Imports System.Windows.Forms
Module Module1
Private TreeView1 As New TreeView()
Sub Main()
Using f As New Form
Dim btn As New Button
btn.Dock = DockStyle.Top
AddHandler btn.Click, Sub(s As Object, e As EventArgs)
Dim foundNodes As TreeNode() = TreeView1.Nodes.Find("Node 39", True)
If foundNodes.Length > 0 Then
TreeView1.SelectedNode = foundNodes(0)
TreeView1.Focus()
End If
End Sub
TreeView1.Dock = DockStyle.Fill
For i As Integer = 0 To 40
Dim key As String = String.Format("Node {0}", i)
Dim label As String = String.Format("Label {0}", i)
TreeView1.Nodes.Add(key, label)
Next
f.Controls.Add(TreeView1)
f.Controls.Add(btn)
f.ShowDialog()
End Using
End Sub
End Module
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Heheh...Your code threw me for a second. It looks like you did a C#-to-vb conversion. But I figured it out and made the mods to get it to work in vb.Net. (I'm not a "C" guy). Here is my change to your translation, with a caption added to the button:
Imports System.Windows.Forms
Module Module1
Dim TreeView1 As New TreeView
Sub Main()
Using f As New Form
Dim btn As New Button
btn.Dock = DockStyle.Top
btn.Text = "Find ""Label 39"""
AddHandler btn.Click, AddressOf BClick
TreeView1.Dock = DockStyle.Fill
For i As Integer = 0 To 40
Dim key As String
key = String.Format("Node {0}", i)
Dim label As String = String.Format("Label {0}", i)
TreeView1.Nodes.Add(key, label)
Next i
f.Controls.Add(TreeView1)
f.Controls.Add(btn)
f.ShowDialog()
End Using
End Sub
Private Sub BClick(ByVal s As Object, ByVal e As EventArgs)
Dim foundNodes As TreeNode() = TreeView1.Nodes.Find("Node 39", True)
If foundNodes.Length > 0 Then
TreeView1.SelectedNode = foundNodes(0)
TreeView1.Focus()
End If
End Sub
End Module
This makes complete sense now...The name/key is NOT the text label. Although it is best to make sure the key = text, so that you don't get confused by the results.
|
|
|
|
|
treddie wrote: It looks like you did a C#-to-vb conversion. Thanks; no conversion, it was a new console-application in the VS-IDE
|
|
|
|
|
I'm curious what that app is?
|
|
|
|
|
VS-IDE?
Visual Studio 2010.
|
|
|
|
|
Hm, I'll check out the console part.
Thanks for all your help, Eddy!
|
|
|
|
|
treddie wrote: Thanks for all your help, Eddy! My pleasure, glad I could help a bit
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
HAI
DATABASE : SQLSERVER 2005
VB : 2008
TYPE PROJECT : NETWORK
Use a separate DATASET in the draft and when I update the data or start I update the data also DATASET so you do not need to reopen Aldtasi of the new data because the size of a very large and cause slow in the project How can I find records that have been updated or deleted, or added?
Because the project network
|
|
|
|
|
Vb Rnd wrote: Use a separate DATASET in the draft and when I update the data or start I update the data also DATASET so you do not need to reopen Aldtasi of the new data because the size of a very large and cause slow in the project How can I find records that have been updated or deleted, or added?
Sounds like you're abusing the dataset as a local cache. If you want to cache your data locally, consider using a local database and a synchronization framework; it'd save you a lot of redundant calls.
Alternatively, you can find all that has been added using plain SQL; perform a SELECT WHERE NOT IN and pass the values for the primary keys of the records in your dataset. Deleting would be something similar. For updates, one could use a timestamp (think "lastmodified"-field).
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Hi.
I was reading the article:
.NET 2.0 Workaround for PathTooLongException
for a solution to the too long path name problem. In that article it states that there is a long, "W" version of the CreateFile() function. Now, the class he developed seems to support opening, reading and writing of files but not looking at the contents of a directory. I have two questions:
1. Is there an "easy" way to expand his class to include other functions such as listing directory contents? If so, what other functions would be required to pull this off? I have found such functions such as FindFirstFile(), but the documentation and Googling do not suggest that there are any "W" versions of these.
UPDATE: According to MSDN, FindFirstFileEx() does not carry the MAX_PATH limitation, so in theory, it should work.
2. In his code, he does not include declarations for his API functions, although he does import namespaces. Is this because he is working in C# (which I am only partly familiar with)? I have converted his code from C# to vb.Net, but the online converter cannot necessarily know that declarations need to be added to the converted code, if in fact they DO need to be. My experience says, "Yes", it definitely does, but then again, why wouldn't those same Import lines work just as well in vb.Net? If that is where these functions are located, then why does vb.Net require explicit declarations? Is this so an entire library does not need to be loaded into memory all at once?
Many thanks for any help!
Below is his original code and usage, followed by my online conversion from C# to vb.Net:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.IO;
namespace System.IO
{
class Win32File
{
const int ERROR_ALREADY_EXISTS = 183;
const uint FILE_BEGIN = 0x0;
const uint FILE_CURRENT = 0x1;
const uint FILE_END = 0x2;
const uint GENERIC_READ = 0x80000000;
const uint GENERIC_WRITE = 0x40000000;
const uint GENERIC_EXECUTE = 0x20000000;
const uint GENERIC_ALL = 0x10000000;
const uint FILE_APPEND_DATA = 0x00000004;
const uint FILE_ATTRIBUTE_NORMAL = 0x80;
const uint FILE_SHARE_DELETE = 0x00000004;
const uint FILE_SHARE_READ = 0x00000001;
const uint FILE_SHARE_WRITE = 0x00000002;
const uint CREATE_NEW = 1;
const uint CREATE_ALWAYS = 2;
const uint OPEN_EXISTING = 3;
const uint OPEN_ALWAYS = 4;
const uint TRUNCATE_EXISTING = 5;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern SafeFileHandle CreateFileW(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern uint SetFilePointer(SafeFileHandle hFile, long lDistanceToMove, IntPtr lpDistanceToMoveHigh, uint dwMoveMethod);
#region GetMode
private static uint GetMode(FileMode mode)
{
uint umode = 0;
switch (mode)
{
case FileMode.CreateNew:
umode = CREATE_NEW;
break;
case FileMode.Create:
umode = CREATE_ALWAYS;
break;
case FileMode.Append:
umode = OPEN_ALWAYS;
break;
case FileMode.Open:
umode = OPEN_EXISTING;
break;
case FileMode.OpenOrCreate:
umode = OPEN_ALWAYS;
break;
case FileMode.Truncate:
umode = TRUNCATE_EXISTING;
break;
}
return umode;
}
#endregion
#region GetAccess
private static uint GetAccess(FileAccess access)
{
uint uaccess = 0;
switch (access)
{
case FileAccess.Read:
uaccess = GENERIC_READ;
break;
case FileAccess.ReadWrite:
uaccess = GENERIC_READ | GENERIC_WRITE;
break;
case FileAccess.Write:
uaccess = GENERIC_WRITE;
break;
}
return uaccess;
}
#endregion
#region GetShare
private static uint GetShare(FileShare share)
{
uint ushare = 0;
switch (share)
{
case FileShare.Read:
ushare = FILE_SHARE_READ;
break;
case FileShare.ReadWrite:
ushare = FILE_SHARE_READ | FILE_SHARE_WRITE;
break;
case FileShare.Write:
ushare = FILE_SHARE_WRITE;
break;
case FileShare.Delete:
ushare = FILE_SHARE_DELETE;
break;
case FileShare.None:
ushare = 0;
break;
}
return ushare;
}
#endregion
public static FileStream Open(string filepath, FileMode mode)
{
FileStream fs = null;
uint umode = GetMode(mode);
uint uaccess = GENERIC_READ | GENERIC_WRITE;
uint ushare = 0;
if (mode == FileMode.Append)
uaccess = FILE_APPEND_DATA;
if (filepath.StartsWith(@"\\"))
{
filepath = @"\\?\UNC\" + filepath.Substring(2, filepath.Length - 2);
}
else
filepath = @"\\?\" + filepath;
SafeFileHandle sh = CreateFileW(filepath, uaccess, ushare, IntPtr.Zero, umode, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
int iError = Marshal.GetLastWin32Error();
if ((iError > 0 && !(mode == FileMode.Append && iError == ERROR_ALREADY_EXISTS)) || sh.IsInvalid)
{
throw new Exception("Error opening file Win32 Error:" + iError);
}
else
{
fs = new FileStream(sh, FileAccess.ReadWrite);
}
if (mode == FileMode.Append)
{
if (!sh.IsInvalid)
{
SetFilePointer(sh, 0, IntPtr.Zero, FILE_END);
}
}
return fs;
}
public static FileStream Open(string filepath, FileMode mode, FileAccess access)
{
FileStream fs = null;
uint umode = GetMode(mode);
uint uaccess = GetAccess(access);
uint ushare = 0;
if (mode == FileMode.Append)
uaccess = FILE_APPEND_DATA;
if (filepath.StartsWith(@"\\"))
{
filepath = @"\\?\UNC\" + filepath.Substring(2, filepath.Length - 2);
}
else
filepath = @"\\?\" + filepath;
SafeFileHandle sh = CreateFileW(filepath, uaccess, ushare, IntPtr.Zero, umode, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
int iError = Marshal.GetLastWin32Error();
if ((iError > 0 && !(mode == FileMode.Append && iError != ERROR_ALREADY_EXISTS)) || sh.IsInvalid)
{
throw new Exception("Error opening file Win32 Error:" + iError);
}
else
{
fs = new FileStream(sh, access);
}
if (mode == FileMode.Append)
{
if (!sh.IsInvalid)
{
SetFilePointer(sh, 0, IntPtr.Zero, FILE_END);
}
}
return fs;
}
public static FileStream Open(string filepath, FileMode mode, FileAccess access, FileShare share)
{
FileStream fs = null;
uint umode = GetMode(mode);
uint uaccess = GetAccess(access);
uint ushare = GetShare(share);
if (mode == FileMode.Append)
uaccess = FILE_APPEND_DATA;
if (filepath.StartsWith(@"\\"))
{
filepath = @"\\?\UNC\" + filepath.Substring(2, filepath.Length - 2);
}
else
filepath = @"\\?\" + filepath;
SafeFileHandle sh = CreateFileW(filepath, uaccess, ushare, IntPtr.Zero, umode, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
int iError = Marshal.GetLastWin32Error();
if ((iError > 0 && !(mode == FileMode.Append && iError != ERROR_ALREADY_EXISTS)) || sh.IsInvalid)
{
throw new Exception("Error opening file Win32 Error:" + iError);
}
else
{
fs = new FileStream(sh, access);
}
if (mode == FileMode.Append)
{
if (!sh.IsInvalid)
{
SetFilePointer(sh, 0, IntPtr.Zero, FILE_END);
}
}
return fs;
}
public static FileStream OpenRead(string filepath)
{
return Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
public static FileStream OpenWrite(string filepath)
{
return Open(filepath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
}
}
}
And an example of its usage:
FileStream fs1= Win32File.Open( "Long file name of greater " +
"than 260 char length", FileMode.Open);
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine("Hello world");
sw.Close();
sw.Dispose();
Finally, the conversion from C# to vb.Net:
:cool:Imports System.Text
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices
Imports System.IO
Namespace System.IO
Class Win32File
Const ERROR_ALREADY_EXISTS As Integer = 183
Const FILE_BEGIN As UInteger = &H0
Const FILE_CURRENT As UInteger = &H1
Const FILE_END As UInteger = &H2
Const GENERIC_READ As UInteger = &H80000000UI
Const GENERIC_WRITE As UInteger = &H40000000
Const GENERIC_EXECUTE As UInteger = &H20000000
Const GENERIC_ALL As UInteger = &H10000000
Const FILE_APPEND_DATA As UInteger = &H4
Const FILE_ATTRIBUTE_NORMAL As UInteger = &H80
Const FILE_SHARE_DELETE As UInteger = &H4
Const FILE_SHARE_READ As UInteger = &H1
Const FILE_SHARE_WRITE As UInteger = &H2
Const CREATE_NEW As UInteger = 1
Const CREATE_ALWAYS As UInteger = 2
Const OPEN_EXISTING As UInteger = 3
Const OPEN_ALWAYS As UInteger = 4
Const TRUNCATE_EXISTING As UInteger = 5
<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function CreateFileW(ByVal lpFileName As String, ByVal dwDesiredAccess As UInteger, ByVal dwShareMode As UInteger, ByVal lpSecurityAttributes As IntPtr, ByVal dwCreationDisposition As UInteger, ByVal dwFlagsAndAttributes As UInteger, _
ByVal hTemplateFile As IntPtr) As SafeFileHandle
End Function
<DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Private Shared Function SetFilePointer(ByVal hFile As SafeFileHandle, ByVal lDistanceToMove As Long, ByVal lpDistanceToMoveHigh As IntPtr, ByVal dwMoveMethod As UInteger) As UInteger
End Function
#Region "GetMode"
Private Shared Function GetMode(ByVal mode As FileMode) As UInteger
Dim umode As UInteger = 0
Select Case mode
Case FileMode.CreateNew
umode = CREATE_NEW
Exit Select
Case FileMode.Create
umode = CREATE_ALWAYS
Exit Select
Case FileMode.Append
umode = OPEN_ALWAYS
Exit Select
Case FileMode.Open
umode = OPEN_EXISTING
Exit Select
Case FileMode.OpenOrCreate
umode = OPEN_ALWAYS
Exit Select
Case FileMode.Truncate
umode = TRUNCATE_EXISTING
Exit Select
End Select
Return umode
End Function
#End Region
#Region "GetAccess"
Private Shared Function GetAccess(ByVal access As FileAccess) As UInteger
Dim uaccess As UInteger = 0
Select Case access
Case FileAccess.Read
uaccess = GENERIC_READ
Exit Select
Case FileAccess.ReadWrite
uaccess = GENERIC_READ Or GENERIC_WRITE
Exit Select
Case FileAccess.Write
uaccess = GENERIC_WRITE
Exit Select
End Select
Return uaccess
End Function
#End Region
#Region "GetShare"
Private Shared Function GetShare(ByVal share As FileShare) As UInteger
Dim ushare As UInteger = 0
Select Case share
Case FileShare.Read
ushare = FILE_SHARE_READ
Exit Select
Case FileShare.ReadWrite
ushare = FILE_SHARE_READ Or FILE_SHARE_WRITE
Exit Select
Case FileShare.Write
ushare = FILE_SHARE_WRITE
Exit Select
Case FileShare.Delete
ushare = FILE_SHARE_DELETE
Exit Select
Case FileShare.None
ushare = 0
Exit Select
End Select
Return ushare
End Function
#End Region
Public Shared Function Open(ByVal filepath As String, ByVal mode As FileMode) As FileStream
Dim fs As FileStream = Nothing
Dim umode As UInteger = GetMode(mode)
Dim uaccess As UInteger = GENERIC_READ Or GENERIC_WRITE
Dim ushare As UInteger = 0
If mode = FileMode.Append Then
uaccess = FILE_APPEND_DATA
End If
If filepath.StartsWith("\\") Then
filepath = "\\?\UNC\" & filepath.Substring(2, filepath.Length - 2)
Else
filepath = "\\?\" & filepath
End If
Dim sh As SafeFileHandle = CreateFileW(filepath, uaccess, ushare, IntPtr.Zero, umode, FILE_ATTRIBUTE_NORMAL, _
IntPtr.Zero)
Dim iError As Integer = Marshal.GetLastWin32Error()
If (iError > 0 AndAlso Not (mode = FileMode.Append AndAlso iError = ERROR_ALREADY_EXISTS)) OrElse sh.IsInvalid Then
Throw New Exception("Error opening file Win32 Error:" & iError)
Else
fs = New FileStream(sh, FileAccess.ReadWrite)
End If
If mode = FileMode.Append Then
If Not sh.IsInvalid Then
SetFilePointer(sh, 0, IntPtr.Zero, FILE_END)
End If
End If
Return fs
End Function
Public Shared Function Open(ByVal filepath As String, ByVal mode As FileMode, ByVal access As FileAccess) As FileStream
Dim fs As FileStream = Nothing
Dim umode As UInteger = GetMode(mode)
Dim uaccess As UInteger = GetAccess(access)
Dim ushare As UInteger = 0
If mode = FileMode.Append Then
uaccess = FILE_APPEND_DATA
End If
If filepath.StartsWith("\\") Then
filepath = "\\?\UNC\" & filepath.Substring(2, filepath.Length - 2)
Else
filepath = "\\?\" & filepath
End If
Dim sh As SafeFileHandle = CreateFileW(filepath, uaccess, ushare, IntPtr.Zero, umode, FILE_ATTRIBUTE_NORMAL, _
IntPtr.Zero)
Dim iError As Integer = Marshal.GetLastWin32Error()
If (iError > 0 AndAlso Not (mode = FileMode.Append AndAlso iError <> ERROR_ALREADY_EXISTS)) OrElse sh.IsInvalid Then
Throw New Exception("Error opening file Win32 Error:" & iError)
Else
fs = New FileStream(sh, access)
End If
If mode = FileMode.Append Then
If Not sh.IsInvalid Then
SetFilePointer(sh, 0, IntPtr.Zero, FILE_END)
End If
End If
Return fs
End Function
Public Shared Function Open(ByVal filepath As String, ByVal mode As FileMode, ByVal access As FileAccess, ByVal share As FileShare) As FileStream
Dim fs As FileStream = Nothing
Dim umode As UInteger = GetMode(mode)
Dim uaccess As UInteger = GetAccess(access)
Dim ushare As UInteger = GetShare(share)
If mode = FileMode.Append Then
uaccess = FILE_APPEND_DATA
End If
If filepath.StartsWith("\\") Then
filepath = "\\?\UNC\" & filepath.Substring(2, filepath.Length - 2)
Else
filepath = "\\?\" & filepath
End If
Dim sh As SafeFileHandle = CreateFileW(filepath, uaccess, ushare, IntPtr.Zero, umode, FILE_ATTRIBUTE_NORMAL, _
IntPtr.Zero)
Dim iError As Integer = Marshal.GetLastWin32Error()
If (iError > 0 AndAlso Not (mode = FileMode.Append AndAlso iError <> ERROR_ALREADY_EXISTS)) OrElse sh.IsInvalid Then
Throw New Exception("Error opening file Win32 Error:" & iError)
Else
fs = New FileStream(sh, access)
End If
If mode = FileMode.Append Then
If Not sh.IsInvalid Then
SetFilePointer(sh, 0, IntPtr.Zero, FILE_END)
End If
End If
Return fs
End Function
Public Shared Function OpenRead(ByVal filepath As String) As FileStream
Return Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)
End Function
Public Shared Function OpenWrite(ByVal filepath As String) As FileStream
Return Open(filepath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)
End Function
End Class
End Namespace
modified 3-May-13 15:52pm.
|
|
|
|
|
treddie wrote: In his code, he does not include declarations for his API functions, although he does import namespaces. Is this because he is working in C# He does. You can browse the source code using the links in the article. His P/Invokes start on line number 46.
treddie wrote: the online converter cannot necessarily know that declarations need to be added to the converted code, if in fact they DO need to be. Bad translator.
treddie wrote: why wouldn't those same Import lines work just as well in vb.Net? If that is where these functions are located, then why does vb.Net require explicit declarations? Is this so an entire library does not need to be loaded into memory all at once? There's multiple ways to link/load a dll. The "using" or "import" lines are defining which namespaces to look in when searching for a specific class-type. Sometimes one needs to "add (a) reference" to an external assembly to be able to access types in other libraries. That's the usual route for managed code - anything in .NET.
There's also a lot of unmanged code on the machine, as is the WinAPI. The code is also linking to a specific part in the WinAPI in "kernel32.dll". Both VB.NET and C# need special declarations for these, decorated with the DllImport attribute.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Cool. Tank you very much for your help, Eddy.
|
|
|
|
|
You're welcome
|
|
|
|
|
Hello,
I have an application where users opens more than one windows on an MDI form.
I want users to be able to save their work environment for future opening and used. When next the saved look is open, all previously opened windows should also open at exactly where they were before closing/saving the work area.
Any help please
Thanks
|
|
|
|
|
A very high level suggestion to your question:
Save the information to a database table linked to the user or save it to an xml file on the user's computer
Then when the forms are next opened consult these saved settings and restore the forms to how the user left them.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
|
|
|
|
|
hello,
I have MDI form that users open more than one windows at a time. I want user to be able to save these opened windows and be able to reopen them next time.
Please help
Thanks
Olu
|
|
|
|
|