Create a module of Extensions methods for all the new projects - vb.net

I'd like to know if there is a way to create a module of Extensions methods for all the new projects in Visual Studio 2013.
For example, this is my Module :
Imports System.Runtime.CompilerServices
Imports System.IO
Module Extensions
<Extension> Public Function ReplaceFirst(value As String, oldValue As String, newValue As String) As String
Dim position As Integer = value.IndexOf(oldValue)
If position = -1 Then
Return value
Else
Return value.Substring(0, position) + newValue + value.Substring(position + oldValue.Length)
End If
End Function
<Extension> Public Function ReadAllLines(value As String) As List(Of String)
If value Is Nothing Then
Return Nothing
End If
Dim lines As New List(Of String)
Using StringRdr As New StringReader(value)
While StringRdr.Peek() <> -1
Dim line As String = StringRdr.ReadLine
If Not String.IsNullOrWhiteSpace(line) Then
lines.Add(line)
End If
End While
End Using
Return lines
End Function
<Extension> Public Function UppercaseFirstLetter(value As String) As String
If String.IsNullOrEmpty(value) Then
Return value
End If
Dim Chars() As Char = value.ToCharArray
Chars(0) = Char.ToUpper(Chars(0))
Return New String(Chars)
End Function
<Extension> Public Function ZeroBased(value) As Integer
Return value - 1
End Function
End Module
How can I use this Extensions methods in all my projects without adding the module in all of them ?
Regards, Drarig29.

Make it a library (DLL) and add a reference to the library in each project.

Related

Sort directory path alphabetically

Below code is used for sorting Directories in vb.net.
Dim a As New List(Of String)
a.Add("a\b\c")
a.Add("a\b\c\d")
a.Add("a\b\c d")
a.Add("a\b\c d\e")
a.Add("a\b\c\d\f")
a.Sort(Function(x, Y) (x).CompareTo((Y)))
result:
a\b\c
a\b\c d
a\b\c d\e
a\b\c\d
a\b\c\d\f
In the result list directories with space is placed before "\".
There are more than 1500000 sub-directories and files
it takes around 50 seconds to sort(default method)
all other methods we tried is taking at least 400 seconds.
how to sort directory path alphabetically?
Is there any built in method to consider Backslash before space ?
You need to break the path up into individual folder names and compare each of them in turn until you find a difference. If there is no difference then you use the length to differentiate, i.e. higher-level folder comes first.
a.Sort(Function(x, y)
Dim xFolderNames As New List(Of String)
Dim yFolderNames As New List(Of String)
'Split first path into folder names.
Do Until String.IsNullOrEmpty(x)
xFolderNames.Insert(0, Path.GetFileName(x))
x = Path.GetDirectoryName(x)
Loop
'Split second path into folder names.
Do Until String.IsNullOrEmpty(y)
yFolderNames.Insert(0, Path.GetFileName(y))
y = Path.GetDirectoryName(y)
Loop
Dim result = 0
'Compare up to as many folders as are in the shortest path.
For i = 0 To Math.Min(xFolderNames.Count, yFolderNames.Count) - 1
result = xFolderNames(i).CompareTo(yFolderNames(i))
If result <> 0 Then
'A difference has been found.
Exit For
End If
Next
If result = 0 Then
'No difference was found so put the shortest path first.
result = xFolderNames.Count.CompareTo(yFolderNames.Count)
End If
Return result
End Function)
For good measure, here's a class that encapsulates that functionality:
Imports System.Collections.ObjectModel
Imports System.IO
Public Class FileSystemPath
Implements IComparable, IComparable(Of FileSystemPath)
Public ReadOnly Property FullPath As String
Public ReadOnly Property PartialPaths As ReadOnlyCollection(Of String)
Public Sub New(fileOrFolderPath As String)
FullPath = fileOrFolderPath
Dim partialPaths As New List(Of String)
Do Until String.IsNullOrEmpty(fileOrFolderPath)
partialPaths.Insert(0, Path.GetFileName(fileOrFolderPath))
fileOrFolderPath = Path.GetDirectoryName(fileOrFolderPath)
Loop
Me.PartialPaths = New ReadOnlyCollection(Of String)(partialPaths)
End Sub
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Return CompareTo(DirectCast(obj, FileSystemPath))
End Function
Public Function CompareTo(other As FileSystemPath) As Integer Implements IComparable(Of FileSystemPath).CompareTo
Dim result = 0
'Compare up to as many folders as are in the shortest path.
For i = 0 To Math.Min(PartialPaths.Count, other.PartialPaths.Count) - 1
result = PartialPaths(i).CompareTo(other.PartialPaths(i))
If result <> 0 Then
'A difference has been found.
Exit For
End If
Next
If result = 0 Then
'No difference was found so put the shortest path first.
result = PartialPaths.Count.CompareTo(other.PartialPaths.Count)
End If
Return result
End Function
Public Overrides Function ToString() As String
Return FullPath
End Function
End Class
It can be used with barely a change to your code:
Dim a As New List(Of FileSystemPath)
a.Add(New FileSystemPath("a\b\c"))
a.Add(New FileSystemPath("a\b\c\d"))
a.Add(New FileSystemPath("a\b\c d"))
a.Add(New FileSystemPath("a\b\c d\e"))
a.Add(New FileSystemPath("a\b\c\d\f"))
a.Sort()
Console.WriteLine(String.Join(Environment.NewLine, a))
Console.ReadLine()

BC36645 error in vb.net

I'm using Visual Studio 2015 to develop a website using web forms and Visual Basic. My problem is the error BC36645 has occured, preventing me from building the solution. It is described as "Data type(s) of the type parameter(s) in method 'Public Shared Overloads Function FromResult(Of TResult)(result As TResult) As Task(Of TResult)' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error."
Which I understand the basic meaning of. However, it's stated to be in a file that I have not touched, it's autogenerated. The file is IdentityModels.vb located in the Models folder.
I got the same error in another project in the same solution, which I solved by deleting, re-creating the project and rebuilding. But this is not really a convenient way to solve the problem.
Does someone have the same problem, can explain what it is about, or even have a proper solution?
//Eva-Lotta
EDIT:
This is the contents of the file the error points to (with the error in " Return Task.FromResult(GenerateUserIdentity(manager))":
Imports System
Imports System.Threading.Tasks
Imports System.Security.Claims
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Public Class ApplicationUser
Inherits IdentityUser
Public Function GenerateUserIdentity(manager As ApplicationUserManager) As
Dim userIdentity = manager.CreateIdentity(Me, DefaultAuthenticationTypes.ApplicationCookie)
Return userIdentity
End Function
Public Function GenerateUserIdentityAsync(manager As ApplicationUserManager)
As Task(Of ClaimsIdentity)
Return Task.FromResult(GenerateUserIdentity(manager))
End Function
End Class
Public Class ApplicationDbContext
Inherits IdentityDbContext(Of ApplicationUser)
Public Sub New()
MyBase.New("DefaultConnection", throwIfV1Schema:=False)
End Sub
Public Shared Function Create As ApplicationDbContext
Return New ApplicationDbContext()
End Function
End Class
#Region "Helpers"
Public Class
Public Const XsrfKey As String = "xsrfKey"
Public Const ProviderNameKey As String = "providerName"
Public Shared Function GetProviderNameFromRequest(request As HttpRequest) As String
Return request.QueryString(ProviderNameKey)
End Function
Public Const CodeKey As String = "code"
Public Shared Function GetCodeFromRequest(request As HttpRequest) As String
Return request.QueryString(CodeKey)
End Function
Public Const UserIdKey As String = "userId"
Public Shared Function GetUserIdFromRequest(request As HttpRequest) As String
Return HttpUtility.UrlDecode(request.QueryString(UserIdKey))
End Function
Public Shared Function GetResetPasswordRedirectUrl(code As String, request As HttpRequest) As String
Dim absoluteUri = "/Account/ResetPassword?" + CodeKey + "=" + HttpUtility.UrlEncode(code)
Return New Uri(request.Url, absoluteUri).AbsoluteUri.ToString()
End Function
Public Shared Function GetUserConfirmationRedirectUrl(code As String, userId As String, request As HttpRequest) As String
Dim absoluteUri = "/Account/Confirm?" + CodeKey + "=" + HttpUtility.UrlEncode(code) + "&" + UserIdKey + "=" + HttpUtility.UrlEncode(userId)
Return New Uri(request.Url, absoluteUri).AbsoluteUri.ToString()
End Function
Private Shared Function IsLocalUrl(url As String) As Boolean
Return Not String.IsNullOrEmpty(url) AndAlso ((url(0) = "/"c AndAlso (url.Length = 1 OrElse (url(1) <> "/"c AndAlso url(1) <> "\"c))) OrElse (url.Length > 1 AndAlso url(0) = "~"c AndAlso url(1) = "/"c))
End Function
Public Shared Sub RedirectToReturnUrl(returnUrl As String, response As HttpResponse)
If Not [String].IsNullOrEmpty(returnUrl) AndAlso IsLocalUrl(returnUrl) Then
response.Redirect(returnUrl)
Else
response.Redirect("~/")
End If
End Sub
End Class
#End Region
To resolve this error You may be able to specify a data type for the type parameter or parameters instead of relying on type inference.

Enum with string index or alternative

Is it possible to return a value from enum with a string index? For example I can use:
Enum test
firstval
secondval
thirdval
End Enum
Dim index As Integer = 1
CType(index, test).ToString()
to return firstval but is there a way to do something similar where index is a string value? For example:
Enum test
firstval = "one"
secondval = "two"
thirdval = "three"
End Enum
Dim index As string = "one"
CType(index, test).ToString()
It's not possible using an Enum, but you could easily create a type that can do what you want, using the Narrowing operator.
simple example:
Class Test
Private Shared _lookup As Dictionary(Of String, Test)
Private Key As String
Private Name As String
Public Shared ReadOnly firstval As Test = New Test("one", "firstval")
Public Shared ReadOnly secondval As Test = New Test("two", "secondval")
Public Shared ReadOnly thirdval As Test = New Test("three", "thirdval")
Private Sub New(key As String, name As String)
Me.Key = key
Me.Name = name
If _lookup Is Nothing Then _
_lookup = New Dictionary(Of String, Test)
_lookup.Add(key, Me)
End Sub
Public Overrides Function ToString() As String
Return Me.Name ' or whatever you want '
End Function
Public Shared Widening Operator CType(obj As Test) As String
Return obj.Key
End Operator
Public Shared Narrowing Operator CType(key As String) As Test
Return _lookup(key)
End Operator
End Class
usage:
Dim index As string = "one"
' returns firstval '
CType(index, Test).ToString()
There are several other alternatives.
One is to get the names used in the enum. For instance:
Friend Enum ImgFormat
Bitmap
GIF
JPeg
TIFF
PNG
End Enum
Dim ImgNames() As String
...
ImgNames = [Enum].GetNames(GetType(ImgFormat))
If your names are not friendly enough, decorate them with Descriptions:
Imports System.ComponentModel
Friend Enum ImgFormat
<Description("Bitmap (BMP)")> Bitmap
<Description("Graphic Interchange (GIF)")> GIF
<Description("Jpg/JPeg (JPG)")> JPeg
<Description("Tagged Image (TIFF)")> TIFF
<Description("Portable Graphics (PNG)")> PNG
End Enum
To get the descriptions, requires reflection which gets involved:
Imports System.Reflection
Imports System.ComponentModel
Public Class EnumConverter
' gets a single enum description
Public Shared Function GetEnumDescription(ByVal EnumConstant As [Enum]) As String
Dim fi As FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
Dim attr() As DescriptionAttribute = _
DirectCast( _
fi.GetCustomAttributes(GetType(DescriptionAttribute), False), _
DescriptionAttribute() )
If attr.Length > 0 Then
Return attr(0).Description
Else
Return EnumConstant.ToString()
End If
End Function
' get all the enum descriptions:
Public Shared Function GetEnumDescriptions(ByVal type As Type) As String()
Dim n As Integer = 0
Dim enumValues As Array = [Enum].GetValues(type)
Dim Descr(enumValues.Length - 1) As String
For Each value As [Enum] In enumValues
Descr(n) = GetEnumDescription(value)
n += 1
Next
Return Descr
End Function
End Class
To use:
Dim ImgNames() As String = EnumConverter.GetEnumDescriptions(ImgFormat)
ImgNames(ImgFormat.GIF) would be 'Graphic Interchange (GIF)'
This will break if the Enum values are not the default 0, 1, 2 ... IF that is an issue (and it really is), then build a class around it to store the Name or Description with the Enum Value. Rather than building a class to create a pseudo enum, make one to create a list of name-value pairs consisting of the Descriptions and Enum Value.

VB: Problems with using variable from another class + what to do with not used interface`s functions

I have a problem with getting variable from another class and cannot understand what to do with interface`s functions which have already existed in another class.
What I have:
Form where clicking on a button I should see reversed string:
(I want to call pooraja.StringReverse which is below)
Private Sub btnPoora1_Click(sender As System.Object, e As System.EventArgs) _
Handles btnPoora1.Click
'Dim text As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CtekstiPooraja
Dim text As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CtekstiPooraja
Dim pooraja As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CAlgrotimilinePooraja
text.strText = txtSisendTekst.Text
txtValjundTekst1.Text = pooraja.stringReverse
text.intStart = 1
text.intEnd = Len(txtSisendTekst.Text)
ascFSymbol.Text = text.ascFirstSymbol
ascLSymbol.Text = text.ascLastSymbol()
End Sub
CtekstiPooraja:
(Thiss class will be used to store data.Under data I mean strPooratavText. Data will be used in CAlgoritmilinePooraja)
Public Class CtekstiPooraja
Implements ITeisendused
Public intStartSymbol As Integer
Public intEndSymbol As Integer
Public strPooratavText As String
Private Property intEnd As Integer Implements ITeisendused.intEnd
Get
Return intEndSymbol
End Get
Set(ByVal value As Integer)
intEndSymbol = value
End Set
End Property
Private Property intStart As Integer Implements ITeisendused.intStart
Get
Return intStartSymbol
End Get
Set(ByVal value As Integer)
intStartSymbol = value
End Set
End Property
Public Function pooraText() As String Implements ITeisendused.pooraText
Return StrReverse(strPooratavText)
End Function
Public Property strText As String Implements ITeisendused.strText
Get
Return strPooratavText
End Get
Set(ByVal value As String)
strPooratavText = value
MsgBox(strPooratavText)
End Set
End Property
Public Sub teisendaText(ByRef strSisendText As String) Implements ITeisendused.teisendaText
strPooratavText = StrReverse(strSisendText)
End Sub
Public Function ascFirstSymbol() As String Implements ITeisendused.ascFirstSymbol
Return Asc(GetChar(strPooratavText, intStartSymbol))
End Function
Public Function ascLastSymbol() As String Implements ITeisendused.ascLastSymbol
Return Asc(GetChar(strPooratavText, intEndSymbol))
End Function
Public Function stringReverse() As String Implements ITeisendused.stringReverse
Return Nothing
End Function
End Class
CAlgrotimilinePooraja:
(This class will be called by form button. There I need to use stringReverse function with data from CtekstiPooraja. The problem is that everywhere is used the same interface and there is some functions and procedures from this interface which isnt necessary. I dont know what value should return these unused functions/procedures. Just using "return Nothing or return 0/ "" is bad idea, may be there is possible somehow referenceto to CTekstiPooraja functions/procedures variables")
Public Class CAlgrotimilinePooraja
Implements ITeisendused
Private x As New PrjTekstiPooraja.CtekstiPooraja
Public Function stringReverse() As String Implements ITeisendused.stringReverse
MsgBox(x.strPooratavText)
Dim i As Integer = 0
Dim j As Integer
Dim characters(j) As Char
Dim newString(j) As Char
characters = x.strPooratavText.ToCharArray()
newString = x.strPooratavText.ToCharArray()
Do While i <= j - 1
newString(i) = characters(j - 1)
newString(j - 1) = characters(i)
i += 1
j -= 1
Loop
Return newString
End Function
Public Function ascFirstSymbol() As String Implements ITeisendused.ascFirstSymbol
Return x.ascFirstSymbol()
End Function
Public Function ascLastSymbol() As String Implements ITeisendused.ascLastSymbol
Return Nothing
End Function
Public Property intEnd As Integer Implements ITeisendused.intEnd
Get
Return x.intEndSymbol
End Get
Set(ByVal value As Integer)
End Set
End Property
Public Property intStart As Integer Implements ITeisendused.intStart
Get
Return x.intStartSymbol
End Get
Set(ByVal value As Integer)
End Set
End Property
Public Function pooraText() As String Implements ITeisendused.pooraText
Return x.pooraText()
End Function
Public Property strText As String Implements ITeisendused.strText
Get
Return x.strPooratavText
End Get
Set(ByVal value As String)
End Set
End Property
Public Sub teisendaText(ByRef strSisendText As String) Implements ITeisendused.teisendaText
x.strPooratavText = StrReverse(strSisendText)
End Sub
End Class
MyInterface:
Public Interface ITeisendused
Property intStart As Integer
Property intEnd As Integer
Property strText As String
Function pooraText() As String
Function ascFirstSymbol() As String
Function ascLastSymbol() As String
Function stringReverse() As String
Sub teisendaText(ByRef strSisendText As String)
End Interface
I cannot understand how to get variable strPooratavText from CTekstiPooraja to CAlgrotimilinePooraja. Usually that instancewhich I create worked but not now. And I cannot understand what to do with already existed function and procedures in CAlgoritmilinePooraja when the same function and procedures has in another class. Maybe, it is possible to reference them somehow to existed functions/procedures in CTekstiPooraja? Could you explain me how to id, already tired to surf Internet to find a solution for it, have already try a lot.
Well, I think you have a fundamental problem with understanding interfaces. They describe data and behavior, it should be extremely rare to want to implement part of an interface.
That said, if you do want to implement part of an interface, instead of returning bogus data, throw an exception for behavior you don't implement.
Your specific problem is that CAlgoritmilinePooraja works on an instance of CtekstiPooraja, but it creates a new instance instead of using an existing one. Add
Sub New(incomingX as CtekstiPooraja)
x = incomingX
End Sub
to CAlgoritmilinePooraja. And then in your event, use....
Dim text As PrjTekstiPooraja.CtekstiPooraja = New PrjTekstiPooraja.CtekstiPooraja
text.strText = txtSisendTekst.Text
Dim pooraja As PrjTekstiPooraja.ITeisendused = New PrjTekstiPooraja.CAlgrotimilinePooraja(text)
That is the minimum change to your design that gets what you want to happen to happen but it's problably not what you should do. Other than implementing strReverse, CtekstiPooraja seems to be what you want, CAlgrotimilinePooraja looks to do just one thing, the actual string reversal.
I would move the implementation of strReverse into CtekstiPooraja, and then eliminate CAlgrotimilinePooraja.
PS I would try to stick to English for class names as well as functions and variables.

Order By file date in collection

I don't think the, System.Collections.ObjectModel has any sort or order by capability.
I have a list of files and I'd like to sort by the file date.
Dim list AS System.Collections.ObjectModel.ReadOnlyCollection(Of String)
list = My.Computer.FileSystem.GetFiles("C:\SearchFolder" _
, FileIO.SearchOption.SearchByTopLevelOnly _
, "TheFileName*.txt")
Dim sTheLastFile AS String
sTheLastFile = list.Max()
This returns the last file, but based on file name and not date. I think I need to add
.OrderBy(... just can't get that part.
using System.IO;
public static void Main()
{
DirectoryInfo di = new DirectoryInfo("c:\\temp\\");
FileSystemInfo[] files = di.GetFileSystemInfos("*.mp3");
printFiles(files);
Array.Sort(files, CompareFileByDate);
printFiles(files);
}
public static int CompareFileByDate(FileSystemInfo f1, FileSystemInfo f2)
{
return DateTime.Compare(f1.LastWriteTime, f2.LastWriteTime);
}
public static void printFiles(FileSystemInfo[] files)
{
foreach(FileSystemInfo file in files)
{
Console.WriteLine(file.Name);
}
Console.WriteLine("********************************");
}
See if this helps you at all.
I have used LastWriteTime property. You can choose whichever works for you (CreationTime or LastAccessTime).
EDIT: Sure, this can be converted to more compact syntax using c# 3.0 & support for lambda expressions.
EDIT2:
from file in new DirectoryInfo(#"c:\temp\").GetFileSystemInfos("*.mp3")
orderby file.LastWriteTime
select file
EDIT3: vb.net version of the above c# code
from file in new DirectoryInfo("c:\temp\").GetFileSystemInfos("*.mp3") _
order by file.LastWriteTime _
select file
EDIT4: Is this what you are looking for?
This will give you the max. date of the LastWriteTime of all *.mp3 files.
(from file in new DirectoryInfo("c:\temp\").GetFileSystemInfos("*.mp3") _
order by file.LastWriteTime descending _
select file.LastWriteTime).Take(1)
OR
(from file in new DirectoryInfo("c:\temp\").GetFileSystemInfos("*.mp3") _
select file.LastWriteTime).Max()
With this class you can order the files using the appropiate criteria (you must add private helper classes for every criteria you needed ;-) )
Imports System.IO
Class FilesTools
Private Class HelperSortByLastWriteTimeAsc
Implements IComparer(Of FileInfo)
Public Function Compare(ByVal x As System.IO.FileInfo, _
ByVal y As System.IO.FileInfo) As Integer Implements System.Collections.Generic.IComparer(Of System.IO.FileInfo).Compare
Return Date.Compare(x.LastWriteTime, y.LastWriteTime)
End Function
End Class
Private Class HelperSortByLastWriteTimeDesc
Implements IComparer(Of FileInfo)
Public Function Compare(ByVal x As System.IO.FileInfo, _
ByVal y As System.IO.FileInfo) As Integer Implements System.Collections.Generic.IComparer(Of System.IO.FileInfo).Compare
Return Date.Compare(y.LastWriteTime, x.LastWriteTime)
End Function
End Class
Public Shared Function sortByLastTime() As IComparer(Of FileInfo)
Return New HelperSortByLastWriteTimeAsc
End Function
Public Shared Function sortByLastTimeDesc() As IComparer(Of FileInfo)
Return New HelperSortByLastWriteTimeDesc
End Function
Public Shared Function GetFilesSorted(ByVal path As String, _
ByVal sort As IComparer(Of FileInfo)) As FileInfo()
Dim info As FileInfo()
info = New DirectoryInfo(path).GetFileSystemInfos()
Array.Sort(Of FileInfo)(info, sort)
Return info
End Function
End Class
To accomplish this please try the following...
Setup a new class implementing the IComparer interface. This will be used to perform the comparisons. IComparer provides a way to customize the sort order of a collection. Note that the example below uses the LastWriteTime as the basis for comparison however this can be changed to whatever property you see fit.
Public Class clsCompareFileInfo
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
Dim File1 As FileInfo
Dim File2 As FileInfo
File1 = DirectCast(x, FileInfo)
File2 = DirectCast(y, FileInfo)
Compare = DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime)
End Function
End Class
Then, grab the file collection and perform the following actions to sort the files accordingly.
Dim dirinfo As DirectoryInfo = New DirectoryInfo("C:\SearchFolder")
Dim allFiles() As FileInfo = dirinfo.GetFiles("TheFileName*.txt", SearchOption.TopDirectoryOnly)
Array.Sort(allFiles, New clsCompareFileInfo)
For Each fl As FileInfo In allFiles
MsgBox(fl.FullName.ToString())
Next