I'm taking a VB.Net DLL and turning it into a Portable Class Library. Once I got all of the classes moved into the new project for the PCL, Visual Studio started throwing errors for a lot of common VB syntax that I thought would still work just fine. Some examples:
LCase
InStr
Left
Mid
On Error GoTo 0
Err
Is it possible there is just some option or include I need to have to get these to work?
You must use methods of assemblies that are supported by Portable Class Libraries (see Assemblies section). You'll be able to find equivelants to the methods that aren't working for you (ex = SubString, ToUpper, ToLower, IndexOf, etc).
When using portable to target the down-level platforms (.NET 4.0, Silverlight, Windows Phone, Xbox), we do not support the majority of the features that are exposed within Microsoft.VisualBasic.dll.
Instead, we make use of the embedded runtime feature. This embeds certain functionality that would traditionally be found in Microsoft.VisualBasic.dll, into the resulting binary itself. The features that are supported are called out on this page, under the /vbruntime* section: http://msdn.microsoft.com/en-us/library/bb531259.aspx.
When targeting .NET 4.5 & Windows Store apps only, then you do get access to the traditional Microsoft.VisualBasic.dll.
As a workaround, to help you move to portable, you can define your own module that bridges the old VB functions to their .NET equivalents:
Public Module VisualBasicBridge
Public Function LCase(value As String) As String
Return value.ToLower()
End Function
End Module
As far as On Error, I'm not aware of a good way to bridging that without providing your own implementation of Microsoft.VisualBasic, and passing that via the /vbruntime switch/msbuild property.
You can create those methods so that you don't have to update tons of your legacy code. Most of it is very straightforward, the biggest difference comes with the string functions where the legacy VB functions use a 1 based index and .Net uses a 0 index. To give you an example, here is the Mid function recreated to behave like VB (created like an extension method here):
''' <summary>
''' Simulates the same functionality provide by the traditional 1 based index Mid function.
''' </summary>
''' <param name="str"></param>
''' <param name="startPos"></param>
''' <param name="length"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function Mid(ByVal str As String, ByVal startPos As Integer, ByVal length As Integer) As String
Return str.Substring(startPos - 1, length)
End Function
Here's a few more from your list and/or commonly used ones:
''' <summary>
''' Extension to the Visual Basic Left function
''' </summary>
''' <param name="str"></param>
''' <param name="length"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function [Left](ByVal str As String, ByVal length As Integer) As String
Return str.Substring(0, length)
End Function
''' <summary>
''' Extension to the Visual Basic Right function
''' </summary>
''' <param name="str"></param>
''' <param name="length"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function [Right](ByVal str As String, ByVal length As Integer) As String
Return str.Substring(str.Length - length, length)
End Function
''' <summary>
''' Determines whether a string is a numeric value. This implementation uses Decimal.TryParse to produce it's value.
''' </summary>
''' <param name="str"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function [IsNumeric](str As String) As Boolean
Dim result As Decimal = 0
Return Decimal.TryParse(str, result)
End Function
<Extension()> _
Public Function LCase(str As String) As String
Return str.ToLower
End Function
All think those methods are in Microsoft.VisualBasic namespace. You can replace them with standard ones:
LCase => string.ToLower()
InStr => string.IndexOf()
....
Replace "on error" with regular try/catch
Best regards
Related
I've seen lots of posts on here (and elsewhere) with a solution to the problem of finding the available free space on a UNC path, but these all involve using GetDiskFreeSpaceEx which only appears to be available in C.
I've included it in some test code and get:
Error BC30451 'GetDiskFreeSpaceEx' is not declared. It may be inaccessible due to its protection level.
The IDE offers the solutions of creating a method or a property.
Trying this in a console program...
What is the VB equivalent of this?
When working with P/Invoke, I usually write a class with the name of the method and not only the method declaration itself and try to expose the functionality in a .NET fashion instead of low-level C++ style.
e.g. in the method description of the native GetDiskFreeSpaceEx function it is mentioned that in case the provided path is an UNC-path the trailing backslash is mandatory!
C++ style: Write it in the description, if the caller does not provide it in that fashion, they are to blame themselves, RTFM.
.NET style: We adjust it for the caller, they do not have to worry about such implementation details.
I would also provide 3 different methods for each available information (I included a 4th one for the space used), and a common one to get more than one value at once.
Here how it could look:
Imports System
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.InteropServices
Namespace PInvoke.Kernel32
Public Class GetDiskFreeSpaceEx
''' <summary>
''' Retrieves the number of bytes currently available to the caller. This takes into account any quotas etc. that may
''' exist on the folder resp. file share.
''' </summary>
''' <param name="folderName">The name of the path to retrieve the for me available bytes from.</param>
''' <returns>The maximum number of bytes that are currently available for me to use.</returns>
Public Shared Function GetAvailableBytesToCaller(folderName As String) As UInt64
Dim result As SizeInfo = Invoke(folderName)
Return result.BytesAvailableToCaller
End Function
''' <summary>
''' Retrieves the number of bytes currently available on the according volume. This may be more than I can use,
''' see <see cref="GetAvailableBytesToCaller(String)" /> for a method that respects quotas etc.
''' </summary>
''' <param name="folderName">The name of the path to retrieve the (in general) available bytes from.</param>
''' <returns>The maximum number of bytes that are available for all users together.</returns>
Public Shared Function GetAvailableBytesInTotal(folderName As String) As UInt64
Dim result As SizeInfo = Invoke(folderName)
Return result.BytesAvailableInTotal
End Function
''' <summary>
''' Retrieves the number of bytes currently used on the according volume. This value corresponds to
''' <see cref="GetBytesInTotal(String)"/> - <see cref="GetAvailableBytesInTotal(String)"/>.
''' </summary>
''' <param name="folderName">The name of the path to retrieve the used bytes from.</param>
''' <returns>The number of bytes that are already used by all users together.</returns>
Public Shared Function GetUsedBytesInTotal(folderName As String) As UInt64
Dim result As SizeInfo = Invoke(folderName)
Return result.BytesUsedInTotal
End Function
''' <summary>
''' Retrieves the size in bytes of the according volume (the total of already used and available space).
''' </summary>
''' <param name="folderName">The name of the path to retrieve the (in general) available bytes from.</param>
''' <returns>The maximum number of bytes that are available for all users together.</returns>
Public Shared Function GetBytesInTotal(folderName As String) As UInt64
Dim result As SizeInfo = Invoke(folderName)
Return result.TotalNumberOfBytes
End Function
''' <summary>
''' Retrieves a <see cref="SizeInfo"/> object containing the information about how many bytes are available at
''' the given path in general or for the current user account, how much is the total and how much is already
''' used.
''' </summary>
''' <param name="folderName">The name of the path from which to retrieve the size info.</param>
''' <returns>The according size info object.</returns>
Public Shared Function Invoke(folderName As String) As SizeInfo
'Check argument
If (String.IsNullOrWhiteSpace(folderName)) Then
Throw New ArgumentNullException(NameOf(folderName), "The folder's name must not be null, empty or white-space!")
End If
'Expand environment variables
Try
folderName = Environment.ExpandEnvironmentVariables(folderName)
Catch ex As Exception
Throw New ArgumentException($"Unable to expand possible environment variables of folder '{folderName}'! See inner exception for details...", ex)
End Try
'Get full path
Try
folderName = Path.GetFullPath(folderName)
Catch ex As Exception
Throw New ArgumentException($"Unable to retrieve absolute path of folder '{folderName}'! See inner exception for details...", ex)
End Try
'Append final back-slash (which is mandatory for UNC paths)
folderName = folderName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
If (Not folderName.EndsWith(Path.DirectorySeparatorChar)) Then
folderName &= Path.DirectorySeparatorChar
End If
'Invoke method
Dim bytesAvailableToCaller As UInt64
Dim bytesInTotal As UInt64
Dim bytesAvailableInGeneral As UInt64
Dim success As Boolean = Invoke(folderName, bytesAvailableToCaller, bytesInTotal, bytesAvailableInGeneral)
If (Not success) Then Throw New Win32Exception()
'Return result
Return New SizeInfo(bytesAvailableToCaller, bytesInTotal, bytesAvailableInGeneral)
End Function
'Private Methods
<DllImport("kernel32.dll", EntryPoint:="GetDiskFreeSpaceExW", ExactSpelling:=True, SetLastError:=True, CharSet:=CharSet.Unicode)>
Private Shared Function Invoke(folderName As String, ByRef bytesAvailableToCaller As UInt64, ByRef bytesInTotal As UInt64, ByRef bytesAvailableInGeneral As UInt64) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
'************************************************************************************************************************
' Inner Class "SizeInfo"
'************************************************************************************************************************
Public Class SizeInfo
Public Sub New(freeBytesAvailableToCaller As UInt64, totalNumberOfBytes As UInt64, freeBytesAvailableInTotal As UInt64)
Me.BytesAvailableToCaller = freeBytesAvailableToCaller
Me.BytesAvailableInTotal = freeBytesAvailableInTotal
Me.TotalNumberOfBytes = totalNumberOfBytes
End Sub
Public ReadOnly Property BytesAvailableToCaller As UInt64
Public ReadOnly Property BytesAvailableInTotal As UInt64
Public ReadOnly Property BytesUsedInTotal As UInt64
Get
Dim total As UInt64 = TotalNumberOfBytes
Dim available As UInt64 = BytesAvailableInTotal
If (total <= available) Then Return 0
Return total - available
End Get
End Property
Public ReadOnly Property TotalNumberOfBytes As UInt64
End Class
End Class
End Namespace
I am trying my best not to use late binding with the getObject function. How ever i know i wont be looked down upon turning strict off in only One class.
My question is i can't find what to declare my member type of.
Dim restPoint = GetObject("winmgmts:\\.\root\default:Systemrestore")
If restPoint IsNot Nothing Then
If restPoint.CreateRestorePoint("test restore point system", 12, 100) = 0 Then
MsgBox("Restore Point created successfully")
Else
MsgBox("Could not create restore point!")
End If
End If
I have spent hours trying to research msdn createrestorepoint come from. I don't want to use WMI directly or keep strict off.
Thanks
I guess i will go with WMI for now. That snippet cleaned up.
Imports System.Management
Public Class CreateRestorePoint
''' <summary>
''' Defines the search query for the ManagementScope path.
''' </summary>
Private Const MANAGEMENT_SCOPE As String = "\\localhost\root\default:SystemRestore"
''' <summary>
''' Attempts to create a new restore point using WMI.
''' </summary>
''' <returns>True if the restore point was created, other wise false.</returns>
''' <remarks>
''' Gets the object containing the input parameters to a method, and then fills in the values and passes the object to the InvokeMethod call.
''' </remarks>
Friend Function CreateRestorePoint() As Boolean
Dim created As Boolean = True
Using wmiQuery As New ManagementClass(New ManagementPath(MANAGEMENT_SCOPE))
Dim query = GetParams(wmiQuery)
Try
wmiQuery.InvokeMethod("CreateRestorePoint", query, Nothing)
Catch ex As ManagementException
created = False
End Try
End Using
Return created
End Function
''' <summary>
''' Sets the ManagementBaseObject parameters.
''' </summary>
''' <param name="wmiQuery"></param>
''' <returns>Returns a ManagementBaseObject representing the list of input parameters for a method.</returns>
''' <remarks>The members of this class enable you to access WMI data using a specific WMI class path.></remarks>
Private Function GetParams(wmiQuery As ManagementClass) As ManagementBaseObject
Dim query = wmiQuery.GetMethodParameters("CreateRestorePoint")
query("Description") = "-CautionSparta"
query("RestorePointType") = 12
query("EventType") = 100
Return query
End Function
End Class
I am having some issues writing a large set of data to an XML file. I am using the following class to serialize objects to xml and then write them to disk:
''' <summary>
''' Borrowed from http://icanmakethiswork.blogspot.ca/2012/11/xsdxml-schema-generator-xsdexe-taking.html
''' </summary>
''' <typeparam name="T"></typeparam>
''' <remarks></remarks>
Public Class XMLConverter(Of T)
Private Shared serializer As XmlSerializer = Nothing
''' <summary>
''' Static constructor that initialises the serializer for this type
''' </summary>
Shared Sub New()
serializer = New XmlSerializer(GetType(T))
End Sub
''' <summary>
''' Write a node to an xmlwriter
''' </summary>
''' <param name="writer"></param>
''' <param name="itemToAppend">the object to be converted and written</param>
''' <remarks></remarks>
Public Shared Sub AppendToXml(writer As XmlWriter, itemToAppend As T)
Dim strObj As String = ToXML(itemToAppend)
strObj = XMLCleaner.CleanResult(strObj)
writer.WriteRaw(strObj)
writer.Flush()
strObj = Nothing
End Sub
''' <summary>
''' Serialize the supplied object into a string of XML
''' </summary>
''' <param name="obj"></param>
''' <returns></returns>
Public Shared Function ToXML(obj As T) As String
Dim strXml As String = ""
Using memoryStream As New MemoryStream()
serializer.Serialize(memoryStream, obj)
memoryStream.Position = 0
Using sr As New StreamReader(memoryStream)
strXml = sr.ReadToEnd()
End Using
End Using
Return strXml
End Function
End Class
Public Class XMLCleaner
'This is just for removing junk and slightly modifying the output
Public Shared Function CleanResult(result As String) As String
Dim retVal As String = Regex.Replace(result, "\sxmlns.+?"".*?""", "")
retVal = Regex.Replace(retVal, "SavedSearchRecord", "Record")
retVal = retVal.Replace("<?xml version=""1.0""?>", "")
retVal = Regex.Replace(retVal, vbCrLf, vbCrLf & " ")
Return retVal
End Function
End Class
And am calling this like so:
XMLConverter(Of SavedSearchRecord).AppendToXml(writer, record)
The issue is that memory is quickly being accumulated as I append new records to the file and ultimately results in an out of memory exception.
I've seen that not caching the serializer can result in this behaviour, but I think I've sidestepped that issue in my implementation. (Please correct me if I am wrong).
After examining a memory dump:
716821b4 28535 10497120 System.String
71682b74 140213 145562968 System.Char[]
71685670 140258 758802112 System.Byte[]
I can see that I have an enormous number of byte arrays getting stuck in memory. The data in the arrays leads me to believe that these are being stranded in memory by the ToXML function (as they contain the unmodified serialized object strings).
Given that the memory stream is in a Using block, I can't figure out why these byte arrays are not being collected by the GC.
In addition to this there also seems to be a large number of Char arrays in memory as well (about 1/5 of the memory used by the byte arrays) that are not being collected.
Can anyone tell me how to prevent this code from culminating in out of memory exceptions?
FYI code is written using .NET 4.0
I posted my question in a Microsoft forum and it was correctly answered there. I invited the answerer to post their response here, but they have not done so.
The original answer in full can be found here
Paraphrasing:
The serializer creates an assembly to serialize a loaded assembly in an AppDomain which cannot be unloaded.
The workaround was to Cache the serializer by specifying the RootAttribute (only one assembly will leak, once, which is a minimum amount of memory)
This workaround is the best if all the serialized objects are the same type and the object being serialized is not too large.
In my code, I didn't have the RootAttribute specified in the XMLSerializer constructor which was causing a new assembly to be created each time I called the serializer.
Changing from this
''' <summary>
''' Static constructor that initialises the serializer for this type
''' </summary>
Shared Sub New()
serializer = New XmlSerializer(GetType(T))
End Sub
To this:
''' <summary>
''' Static constructor that initialises the serializer for this type
''' </summary>
Shared Sub New()
serializer = New XmlSerializer(GetType(T), XmlRootAttribute(GetType(T).ToString))
End Sub
Completely resolved the leaking.
For a more in depth explanation for why this worked, please see the original answer in the link I posted above.
Please note that I later had to modify the constructor a bit for the results to make sense, but the above was the minimum required to fix the leak.
Shared Sub New()
Dim root As String = GetType(T).ToString
root = root.Substring(root.LastIndexOf(".") + 1, root.Length - root.LastIndexOf(".") - 1)
Dim rootNode As New XmlRootAttribute(root)
rootNode.Namespace = "<appropriate.xsd>"
serializer = New XmlSerializer(GetType(T), rootNode)
End Sub
From MSDN https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx
To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors:
XmlSerializer.XmlSerializer(Type)
XmlSerializer.XmlSerializer(Type, String)
If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.
Is it possible to make efficient queries that use regular expression feature set.I got data in my table which is not in correct format,EX:-In Title colum: Cable 180┬░ To 90┬░ Serial ATA Cable and in Id column 123234+ data in exponential format,it is possible to make queries using regular expression in Sqlserver2008.
You need to make use of the following. Usually requires combinations of the three:
patindex
charindex
substring
In response to your comment above, patindex should not 0 where the case is found. patindex finds the start location of the pattern specified, so if patindex finds the case, it should return an integer > 0.
EDIT:
Also, len(string) and reverse(string) come in handy on specific occasions.
With the CLR and .NET project published to SQL Server it is EXTREMELY efficient. After starting to use a CLR Project in VB.Net with our 2005 SQL Server over the past 2 years I have found that every occurance of a Scalar Function in TSQL for which I have replaced with the .NET version it have dramatically improved performance times. I have used it for advanced date manipulation, formatting and parsing, String formatting and parsing, MD5 Hash generation, Vector lengths, String JOIN Aggragate function, Split Table Valued function, and even bulk loading from serialized datatables via a share folder (which is amazingly fast).
For RegEx since it is not already present I can only assume it is as efficient as a compiled EXE would be doing the same REGEX, which is to say extremely fast.
I will share a code file from my VB.Net CLR project that allows some RegEx functionality.
This code would be part of a .NET CLR DLL that is published to your server.
Function Summary
Regex_IsMatch(Data,Parttern,Options) AS tinyint (0/1 result)
Eg. SELECT dbo.Regex_IsMatch('Darren','[trwq]en$',NULL) -- returns 1 / true
Regex_Group(data,pattern,groupname,options) as nvarchar(max) (capture group value returned)
Eg. SELECT dbo.Regex_Group('Cable 180+e10 to 120+e3',' (?[0-9]+)+e[0-9]+','n',NULL) -- returns '180'
Regex_Replace(data,pattern,replacement,options) as nvarchar(max) (returns modified string)
Eg. SELECT dbo.Regex_Replace('Cable 180+e10 to 120+e3',' (?[0-9]+)+e(?[0-9]+)',' ${e}:${n]',NULL) -- returns 'Cable 10:180 to 3:120'
Partial Public Class UserDefinedFunctions
''' <summary>
''' Returns 1 (true) or 0 (false) if a pattern passed is matched in the data passed.
''' Returns NULL if Data is NULL.
''' options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline"
''' </summary>
''' <param name="data"></param>
''' <param name="pattern"></param>
''' <param name="options">options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline"</param>
''' <returns></returns>
''' <remarks></remarks>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function Regex_IsMatch(data As SqlChars, pattern As SqlChars, options As SqlString) As SqlByte
If pattern.IsNull Then
Throw New Exception("Pattern Parameter in ""RegEx_IsMatch"" cannot be NULL")
End If
If data.IsNull Then
Return SqlByte.Null
Else
Return CByte(If(Regex.IsMatch(data.Value, pattern.Value, Regex_Options(options)), 1, 0))
End If
End Function
''' <summary>
''' Returns the Value of a RegularExpression Pattern Group by Name or Number.
''' Group needs to be captured explicitly. Example Pattern "[a-z](?<m>[0-9][0-9][0-9][0-9])" to capture the numeric portion of an engeneering number by the group called "m".
''' Returns NULL if The Capture was not successful.
''' Returns NULL if Data is NULL.
''' options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline"
''' </summary>
''' <param name="data"></param>
''' <param name="pattern"></param>
''' <param name="groupName">Name used in the explicit capture group</param>
''' <param name="options">options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline"</param>
<Microsoft.SqlServer.Server.SqlFunction()> _
Public Shared Function Regex_Group(data As SqlChars, pattern As SqlChars, groupName As SqlString, options As SqlString) As SqlChars
If pattern.IsNull Then
Throw New Exception("Pattern Parameter in ""RegEx_IsMatch"" cannot be NULL")
End If
If groupName.IsNull Then
Throw New Exception("GroupName Parameter in ""RegEx_IsMatch"" cannot be NULL")
End If
If data.IsNull Then
Return SqlChars.Null
Else
Dim m As Match = Regex.Match(data.Value, pattern.Value, Regex_Options(options))
If m.Success Then
Dim g As Group
If IsNumeric(groupName.Value) Then
g = m.Groups(CInt(groupName.Value))
Else
g = m.Groups(groupName.Value)
End If
If g.Success Then
Return New SqlChars(g.Value)
Else ' group did not return or was not found.
Return SqlChars.Null
End If
Else 'match failed.
Return SqlChars.Null
End If
End If
End Function
''' <summary>
''' Does the Equivalent toi Regex.Replace in .NET.
''' Replacement String Replacement Markers are done in this format "${test}" = Replaces the capturing group (?<test>...)
''' If the replacement pattern is $1 or $2 then it replaces the first or second captured group by position.
''' Returns NULL if Data is NULL.
''' options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline"
''' </summary>
''' <param name="data"></param>
''' <param name="pattern"></param>
''' <param name="replacement">Replacement String Replacement Markers are done in this format "${test}" = Replaces the capturing group (?<test>...). If the replacement pattern is $1 or $2 then it replaces the first or second captured group by position.</param>
''' <param name="options">options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline"</param>
''' <returns></returns>
''' <remarks></remarks>
<SqlFunction()> _
Public Shared Function Regex_Replace(data As SqlChars, pattern As SqlChars, replacement As SqlChars, options As SqlString) As SqlChars
If pattern.IsNull Then
Throw New Exception("Pattern Parameter in ""Regex_Replace"" cannot be NULL")
End If
If replacement.IsNull Then
Throw New Exception("Replacement Parameter in ""Regex_Replace"" cannot be NULL")
End If
If data.IsNull Then
Return SqlChars.Null
Else
Return New SqlChars(Regex.Replace(data.Value, pattern.Value, replacement.Value, Regex_Options(options)))
End If
End Function
''' <summary>
''' Buffered list of options by name for speed.
''' </summary>
Private Shared m_Regex_Buffered_Options As New Generic.Dictionary(Of String, RegexOptions)(StrComp)
''' <summary>
''' Default regex options used when options value is NULL or an Empty String
''' </summary>
Private Shared ReadOnly m_Regex_DefaultOptions As RegexOptions = RegexOptions.IgnoreCase Or RegexOptions.ExplicitCapture Or RegexOptions.Multiline
''' <summary>
''' Get the regular expressions options to use by a passed string of data.
''' Formatted like command line arguments.
''' </summary>
''' <param name="options">options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline "</param>
Private Shared Function Regex_Options(options As SqlString) As RegexOptions
Return Regex_Options(If(options.IsNull, "", options.Value))
End Function
''' <summary>
''' Get the regular expressions options to use by a passed string of data.
''' Formatted like command line arguments.
''' </summary>
''' <param name="options">options example, full or partial names can be used after slashes or hypens with or without spaces, some are exclusive of each other "/ic /ex -s" = "\ignorecase -explicitcapture/singleline"</param>
Private Shared Function Regex_Options(options As String) As RegexOptions
'empty options string is considered default options.
If options Is Nothing OrElse options = "" Then
Return m_Regex_DefaultOptions
Else
Dim out As RegexOptions
If m_Regex_Buffered_Options.TryGetValue(options, out) Then
Return out
Else
'must build options and store them
If options Like "*[/\-]n*" Then
out = RegexOptions.None
End If
If options Like "*[/\-]s*" Then
out = out Or RegexOptions.Singleline
End If
If options Like "*[/\-]m*" Then
out = out Or RegexOptions.Multiline
End If
If options Like "*[/\-]co*" Then
out = out Or RegexOptions.Compiled
End If
If options Like "*[/\-]c[ui]*" Then
out = out Or RegexOptions.CultureInvariant
End If
If options Like "*[/\-]ecma*" Then
out = out Or RegexOptions.ECMAScript
End If
If options Like "*[/\-]e[xc]*" Then
out = out Or RegexOptions.ExplicitCapture
End If
If options Like "*[/\-]i[c]*" OrElse options Like "*[/\-]ignorec*" Then
out = out Or RegexOptions.IgnoreCase
End If
If options Like "*[/\-]i[pw]*" OrElse options Like "*[/\-]ignore[pw]*" Then
out = out Or RegexOptions.IgnorePatternWhitespace
End If
If options Like "*[/\-]r[tl]*" Then
out = out Or RegexOptions.RightToLeft
End If
'store the options for next call (for speed)
m_Regex_Buffered_Options(options) = out
Return out
End If
End If
End Function
End Class
i want to make the listview control collapsible to the groups alone. Like in Vista's My Computer, where only the group names are shown and then we click on the group to expand it.
I am using VB.NET 3.5
Check this out:
Collapsible ListViewGroup
and maybe:
Add Group Collapse Behavior on a Listview Control
Both are written in C# but of course you can still use them in VB.NET projects.
You can only use these on Vista and later.
There is definitely no way to do this with the bog-standard VB.NET ListView control. In fact, it doesn't seem possible even with an ObjectListView, which is my usual port of call when I encounter a ListView limitation.
You could either:
Roll your own control
Switch to a TreeView
Give up
I think that number 2 is the best option in your case, as it's not that difficult. Number one is overkill and takes a lot of time. If you have a GUI layer that is tightly coupled to your logic and database layers, it may be a lot harder to convert to a TreeView. Or, you could just be using the other ListView views. (In the latter case, an TreeListView from the same FOSS project could be the way to go - it is GPL though.)
It may be easier just to kill this feature - I don't think it would be critical.
Here's an old article that extends the list view:
http://www.codeproject.com/KB/list/GroupListView.aspx?msg=1135144
Here's a sample that does what I think you want with a GridView, panel and the Collapsible Panel Extender
You could also switch to the AJAX control toolkit Accordian control.
I have managed to achieve this by looking at what you guys have posted around here and this is how my code looks like.
Imports System.Collections.Generic
Imports System.Text
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Imports System.Reflection
Public Class ListViewCollapsible
Inherits ListView
Private Const LVM_FIRST As Integer = &H1000
' ListView messages
Private Const LVM_SETGROUPINFO As Integer = (LVM_FIRST + 147)
' ListView messages Setinfo on Group
Private Const WM_LBUTTONUP As Integer = &H202
' Windows message left button
Private Delegate Sub CallBackSetGroupState(lstvwgrp As ListViewGroup, state As ListViewGroupState)
Private Delegate Sub CallbackSetGroupString(lstvwgrp As ListViewGroup, value As String)
''' <summary>
''' Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.
''' To send a message and return immediately, use the SendMessageCallback or SendNotifyMessage function. To post a message to a thread's message queue and return immediately, use the PostMessage or PostThreadMessage function.
''' </summary>
''' <param name="hWnd">
''' [in] Handle to the window whose window procedure will receive the message.
''' If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows.
''' Microsoft Windows Vista and later. Message sending is subject to User Interface Privilege Isolation (UIPI). The thread of a process can send messages only to message queues of threads in processes of lesser or equal integrity level.
''' </param>
''' <param name="Msg">[in] Specifies the message to be sent.</param>
''' <param name="wParam">[in] Specifies additional message-specific information.</param>
''' <param name="lParam">[in] Type of LVGROUP, Specifies additional message-specific information.</param>
''' <returns>
''' Microsoft Windows Vista and later. When a message is blocked by UIPI the last error, retrieved with GetLastError, is set to 5 (access denied).
''' Applications that need to communicate using HWND_BROADCAST should use the RegisterWindowMessage function to obtain a unique message for inter-application communication.
''' The system only does marshalling for system messages (those in the range 0 to (WM_USER-1)). To send other messages (those >= WM_USER) to another process, you must do custom marshalling.
''' If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code. The sending thread is blocked until the receiving thread processes the message. However, the sending thread will process incoming nonqueued messages while waiting for its message to be processed. To prevent this, use SendMessageTimeout with SMTO_BLOCK set. For more information on nonqueued messages, see Nonqueued Messages.
''' Windows 95/98/Me: SendMessageW is supported by the Microsoft Layer for Unicode (MSLU). To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.
''' </returns>
<DllImport("User32.dll"), Description("Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message. To send a message and return immediately, use the SendMessageCallback or SendNotifyMessage function. To post a message to a thread's message queue and return immediately, use the PostMessage or PostThreadMessage function.")> _
Private Shared Function SendMessage(hWnd As IntPtr, Msg As Integer, wParam As Integer, lParam As IntPtr) As Integer
End Function
Private Shared Function GetGroupID(lstvwgrp As ListViewGroup) As System.Nullable(Of Integer)
Dim rtnval As System.Nullable(Of Integer) = Nothing
Dim GrpTp As Type = lstvwgrp.[GetType]()
If GrpTp IsNot Nothing Then
Dim pi As PropertyInfo = GrpTp.GetProperty("ID", BindingFlags.NonPublic Or BindingFlags.Instance)
If pi IsNot Nothing Then
Dim tmprtnval As Object = pi.GetValue(lstvwgrp, Nothing)
If tmprtnval IsNot Nothing Then
rtnval = CInt(tmprtnval)
End If
End If
End If
Return rtnval
End Function
Private Shared Sub setGrpState(lstvwgrp As ListViewGroup, state As ListViewGroupState)
If Environment.OSVersion.Version.Major < 6 Then
'Only Vista and forward allows collaps of ListViewGroups
Return
End If
If lstvwgrp Is Nothing OrElse lstvwgrp.ListView Is Nothing Then
Return
End If
If lstvwgrp.ListView.InvokeRequired Then
lstvwgrp.ListView.Invoke(New CallBackSetGroupState(AddressOf setGrpState), lstvwgrp, state)
Else
Dim GrpId As System.Nullable(Of Integer) = GetGroupID(lstvwgrp)
Dim gIndex As Integer = lstvwgrp.ListView.Groups.IndexOf(lstvwgrp)
Dim group As New LVGROUP
group.CbSize = Marshal.SizeOf(group)
group.State = state
group.Mask = ListViewGroupMask.State
Dim ip As IntPtr = IntPtr.Zero
Try
If GrpId IsNot Nothing Then
group.IGroupId = GrpId.Value
ip = Marshal.AllocHGlobal(group.CbSize)
Marshal.StructureToPtr(group, ip, False)
SendMessage(lstvwgrp.ListView.Handle, LVM_SETGROUPINFO, GrpId.Value, ip)
SendMessage(lstvwgrp.ListView.Handle, LVM_SETGROUPINFO, GrpId.Value, ip)
Else
group.IGroupId = gIndex
ip = Marshal.AllocHGlobal(group.CbSize)
Marshal.StructureToPtr(group, ip, False)
SendMessage(lstvwgrp.ListView.Handle, LVM_SETGROUPINFO, gIndex, ip)
SendMessage(lstvwgrp.ListView.Handle, LVM_SETGROUPINFO, gIndex, ip)
End If
lstvwgrp.ListView.Refresh()
Finally
If (ip <> IntPtr.Zero) Then Marshal.FreeHGlobal(ip)
End Try
End If
End Sub
Private Shared Sub setGrpFooter(lstvwgrp As ListViewGroup, footer As String)
If Environment.OSVersion.Version.Major < 6 Then
'Only Vista and forward allows footer on ListViewGroups
Return
End If
If lstvwgrp Is Nothing OrElse lstvwgrp.ListView Is Nothing Then
Return
End If
If lstvwgrp.ListView.InvokeRequired Then
lstvwgrp.ListView.Invoke(New CallbackSetGroupString(AddressOf setGrpFooter), lstvwgrp, footer)
Else
Dim GrpId As System.Nullable(Of Integer) = GetGroupID(lstvwgrp)
Dim gIndex As Integer = lstvwgrp.ListView.Groups.IndexOf(lstvwgrp)
Dim group As New LVGROUP
group.CbSize = Marshal.SizeOf(group)
group.PszFooter = footer
group.Mask = ListViewGroupMask.Footer
Dim ip As IntPtr = IntPtr.Zero
Try
If GrpId IsNot Nothing Then
group.IGroupId = GrpId.Value
ip = Marshal.AllocHGlobal(group.CbSize)
Marshal.StructureToPtr(group, ip, False)
SendMessage(lstvwgrp.ListView.Handle, LVM_SETGROUPINFO, GrpId.Value, ip)
Else
group.IGroupId = gIndex
ip = Marshal.AllocHGlobal(group.CbSize)
Marshal.StructureToPtr(group, ip, False)
SendMessage(lstvwgrp.ListView.Handle, LVM_SETGROUPINFO, gIndex, ip)
End If
Finally
If (ip <> IntPtr.Zero) Then Marshal.FreeHGlobal(ip)
End Try
End If
End Sub
Public Sub SetGroupState(state As ListViewGroupState)
For Each lvg As ListViewGroup In Me.Groups
setGrpState(lvg, state)
Next
End Sub
Public Sub SetGroupState(state As ListViewGroupState, lvg As ListViewGroup)
setGrpState(lvg, state)
End Sub
Public Sub SetGroupFooter(lvg As ListViewGroup, footerText As String)
setGrpFooter(lvg, footerText)
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = WM_LBUTTONUP Then
MyBase.DefWndProc(m)
End If
MyBase.WndProc(m)
End Sub
End Class
''' <summary>
''' LVGROUP StructureUsed to set and retrieve groups.
''' </summary>
''' <example>
''' LVGROUP myLVGROUP = new LVGROUP();
''' myLVGROUP.CbSize // is of managed type uint
''' myLVGROUP.Mask // is of managed type uint
''' myLVGROUP.PszHeader // is of managed type string
''' myLVGROUP.CchHeader // is of managed type int
''' myLVGROUP.PszFooter // is of managed type string
''' myLVGROUP.CchFooter // is of managed type int
''' myLVGROUP.IGroupId // is of managed type int
''' myLVGROUP.StateMask // is of managed type uint
''' myLVGROUP.State // is of managed type uint
''' myLVGROUP.UAlign // is of managed type uint
''' myLVGROUP.PszSubtitle // is of managed type IntPtr
''' myLVGROUP.CchSubtitle // is of managed type uint
''' myLVGROUP.PszTask // is of managed type string
''' myLVGROUP.CchTask // is of managed type uint
''' myLVGROUP.PszDescriptionTop // is of managed type string
''' myLVGROUP.CchDescriptionTop // is of managed type uint
''' myLVGROUP.PszDescriptionBottom // is of managed type string
''' myLVGROUP.CchDescriptionBottom // is of managed type uint
''' myLVGROUP.ITitleImage // is of managed type int
''' myLVGROUP.IExtendedImage // is of managed type int
''' myLVGROUP.IFirstItem // is of managed type int
''' myLVGROUP.CItems // is of managed type IntPtr
''' myLVGROUP.PszSubsetTitle // is of managed type IntPtr
''' myLVGROUP.CchSubsetTitle // is of managed type IntPtr
''' </example>
''' <remarks>
''' The LVGROUP structure was created by Paw Jershauge
''' Created: Jan. 2008.
''' The LVGROUP structure code is based on information from Microsoft's MSDN2 website.
''' The structure is generated via an automated converter and is as is.
''' The structure may or may not hold errors inside the code, so use at own risk.
''' Reference url: http://msdn.microsoft.com/en-us/library/bb774769(VS.85).aspx
''' </remarks>
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode), Description("LVGROUP StructureUsed to set and retrieve groups.")> _
Public Structure LVGROUP
''' <summary>
''' Size of this structure, in bytes.
''' </summary>
<Description("Size of this structure, in bytes.")> _
Public CbSize As Integer
''' <summary>
''' Mask that specifies which members of the structure are valid input. One or more of the following values:LVGF_NONENo other items are valid.
''' </summary>
<Description("Mask that specifies which members of the structure are valid input. One or more of the following values:LVGF_NONE No other items are valid.")> _
Public Mask As ListViewGroupMask
''' <summary>
''' Pointer to a null-terminated string that contains the header text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the header text.
''' </summary>
<Description("Pointer to a null-terminated string that contains the header text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the header text.")> _
<MarshalAs(UnmanagedType.LPWStr)> _
Public PszHeader As String
''' <summary>
''' Size in TCHARs of the buffer pointed to by the pszHeader member. If the structure is not receiving information about a group, this member is ignored.
''' </summary>
<Description("Size in TCHARs of the buffer pointed to by the pszHeader member. If the structure is not receiving information about a group, this member is ignored.")> _
Public CchHeader As Integer
''' <summary>
''' Pointer to a null-terminated string that contains the footer text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the footer text.
''' </summary>
<Description("Pointer to a null-terminated string that contains the footer text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the footer text.")> _
<MarshalAs(UnmanagedType.LPWStr)> _
Public PszFooter As String
''' <summary>
''' Size in TCHARs of the buffer pointed to by the pszFooter member. If the structure is not receiving information about a group, this member is ignored.
''' </summary>
<Description("Size in TCHARs of the buffer pointed to by the pszFooter member. If the structure is not receiving information about a group, this member is ignored.")> _
Public CchFooter As Integer
''' <summary>
''' ID of the group.
''' </summary>
<Description("ID of the group.")> _
Public IGroupId As Integer
''' <summary>
''' Mask used with LVM_GETGROUPINFO (Microsoft Windows XP and Windows Vista) and LVM_SETGROUPINFO (Windows Vista only) to specify which flags in the state value are being retrieved or set.
''' </summary>
<Description("Mask used with LVM_GETGROUPINFO (Microsoft Windows XP and Windows Vista) and LVM_SETGROUPINFO (Windows Vista only) to specify which flags in the state value are being retrieved or set.")> _
Public StateMask As Integer
''' <summary>
''' Flag that can have one of the following values:LVGS_NORMALGroups are expanded, the group name is displayed, and all items in the group are displayed.
''' </summary>
<Description("Flag that can have one of the following values:LVGS_NORMAL Groups are expanded, the group name is displayed, and all items in the group are displayed.")> _
Public State As ListViewGroupState
''' <summary>
''' Indicates the alignment of the header or footer text for the group. It can have one or more of the following values. Use one of the header flags. Footer flags are optional. Windows XP: Footer flags are reserved.LVGA_FOOTER_CENTERReserved.
''' </summary>
<Description("Indicates the alignment of the header or footer text for the group. It can have one or more of the following values. Use one of the header flags. Footer flags are optional. Windows XP: Footer flags are reserved.LVGA_FOOTER_CENTERReserved.")> _
Public UAlign As UInteger
''' <summary>
''' Windows Vista. Pointer to a null-terminated string that contains the subtitle text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the subtitle text. This element is drawn under the header text.
''' </summary>
<Description("Windows Vista. Pointer to a null-terminated string that contains the subtitle text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the subtitle text. This element is drawn under the header text.")> _
Public PszSubtitle As IntPtr
''' <summary>
''' Windows Vista. Size, in TCHARs, of the buffer pointed to by the pszSubtitle member. If the structure is not receiving information about a group, this member is ignored.
''' </summary>
<Description("Windows Vista. Size, in TCHARs, of the buffer pointed to by the pszSubtitle member. If the structure is not receiving information about a group, this member is ignored.")> _
Public CchSubtitle As UInteger
''' <summary>
''' Windows Vista. Pointer to a null-terminated string that contains the text for a task link when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the task text. This item is drawn right-aligned opposite the header text. When clicked by the user, the task link generates an LVN_LINKCLICK notification.
''' </summary>
<Description("Windows Vista. Pointer to a null-terminated string that contains the text for a task link when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the task text. This item is drawn right-aligned opposite the header text. When clicked by the user, the task link generates an LVN_LINKCLICK notification.")> _
<MarshalAs(UnmanagedType.LPWStr)> _
Public PszTask As String
''' <summary>
''' Windows Vista. Size in TCHARs of the buffer pointed to by the pszTask member. If the structure is not receiving information about a group, this member is ignored.
''' </summary>
<Description("Windows Vista. Size in TCHARs of the buffer pointed to by the pszTask member. If the structure is not receiving information about a group, this member is ignored.")> _
Public CchTask As UInteger
''' <summary>
''' Windows Vista. Pointer to a null-terminated string that contains the top description text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the top description text. This item is drawn opposite the title image when there is a title image, no extended image, and uAlign==LVGA_HEADER_CENTER.
''' </summary>
<Description("Windows Vista. Pointer to a null-terminated string that contains the top description text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the top description text. This item is drawn opposite the title image when there is a title image, no extended image, and uAlign==LVGA_HEADER_CENTER.")> _
<MarshalAs(UnmanagedType.LPWStr)> _
Public PszDescriptionTop As String
''' <summary>
''' Windows Vista. Size in TCHARs of the buffer pointed to by the pszDescriptionTop member. If the structure is not receiving information about a group, this member is ignored.
''' </summary>
<Description("Windows Vista. Size in TCHARs of the buffer pointed to by the pszDescriptionTop member. If the structure is not receiving information about a group, this member is ignored.")> _
Public CchDescriptionTop As UInteger
''' <summary>
''' Windows Vista. Pointer to a null-terminated string that contains the bottom description text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the bottom description text. This item is drawn under the top description text when there is a title image, no extended image, and uAlign==LVGA_HEADER_CENTER.
''' </summary>
<Description("Windows Vista. Pointer to a null-terminated string that contains the bottom description text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the bottom description text. This item is drawn under the top description text when there is a title image, no extended image, and uAlign==LVGA_HEADER_CENTER.")> _
<MarshalAs(UnmanagedType.LPWStr)> _
Public PszDescriptionBottom As String
''' <summary>
''' Windows Vista. Size in TCHARs of the buffer pointed to by the pszDescriptionBottom member. If the structure is not receiving information about a group, this member is ignored.
''' </summary>
<Description("Windows Vista. Size in TCHARs of the buffer pointed to by the pszDescriptionBottom member. If the structure is not receiving information about a group, this member is ignored.")> _
Public CchDescriptionBottom As UInteger
''' <summary>
''' Windows Vista. Index of the title image in the control imagelist.
''' </summary>
<Description("Windows Vista. Index of the title image in the control imagelist.")> _
Public ITitleImage As Integer
''' <summary>
''' Windows Vista. Index of the extended image in the control imagelist.
''' </summary>
<Description("Windows Vista. Index of the extended image in the control imagelist.")> _
Public IExtendedImage As Integer
''' <summary>
''' Windows Vista. Read-only.
''' </summary>
<Description("Windows Vista. Read-only.")> _
Public IFirstItem As Integer
''' <summary>
''' Windows Vista. Read-only in non-owner data mode.
''' </summary>
<Description("Windows Vista. Read-only in non-owner data mode.")> _
Public CItems As IntPtr
''' <summary>
''' Windows Vista. NULL if group is not a subset. Pointer to a null-terminated string that contains the subset title text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the subset title text.
''' </summary>
<Description("Windows Vista. NULL if group is not a subset. Pointer to a null-terminated string that contains the subset title text when item information is being set. If group information is being retrieved, this member specifies the address of the buffer that receives the subset title text.")> _
Public PszSubsetTitle As IntPtr
''' <summary>
''' Windows Vista. Size in TCHARs of the buffer pointed to by the pszSubsetTitle member. If the structure is not receiving information about a group, this member is ignored.
''' </summary>
<Description("Windows Vista. Size in TCHARs of the buffer pointed to by the pszSubsetTitle member. If the structure is not receiving information about a group, this member is ignored.")> _
Public CchSubsetTitle As IntPtr
End Structure
Public Enum ListViewGroupMask
None = &H0
Header = &H1
Footer = &H2
State = &H4
Align = &H8
GroupId = &H10
SubTitle = &H100
Task = &H200
DescriptionTop = &H400
DescriptionBottom = &H800
TitleImage = &H1000
ExtendedImage = &H2000
Items = &H4000
Subset = &H8000
SubsetItems = &H10000
End Enum
Public Enum ListViewGroupState
''' <summary>
''' Groups are expanded, the group name is displayed, and all items in the group are displayed.
''' </summary>
Normal = 0
''' <summary>
''' The group is collapsed.
''' </summary>
Collapsed = 1
''' <summary>
''' The group is hidden.
''' </summary>
Hidden = 2
''' <summary>
''' Version 6.00 and Windows Vista. The group does not display a header.
''' </summary>
NoHeader = 4
''' <summary>
''' Version 6.00 and Windows Vista. The group can be collapsed.
''' </summary>
Collapsible = 8
''' <summary>
''' Version 6.00 and Windows Vista. The group has keyboard focus.
''' </summary>
Focused = 16
''' <summary>
''' Version 6.00 and Windows Vista. The group is selected.
''' </summary>
Selected = 32
''' <summary>
''' Version 6.00 and Windows Vista. The group displays only a portion of its items.
''' </summary>
SubSeted = 64
''' <summary>
''' Version 6.00 and Windows Vista. The subset link of the group has keyboard focus.
''' </summary>
SubSetLinkFocused = 128
End Enum
I have tested this and it works just fine for me.
Hope it will help some of you as well.