Designer.vb of RESX file does not update when adding resource via code - vb.net

I am trying to add content to my resx files, via the AddResource(myval.Key, myval.Value) method. It works perfectly, but the only thing that bothers me is that stupid Designer file. Can I force it to update according to its resx file?
This is how I have added my strings to the resx file:
For Each entry In list
Dim resxList As List(Of KeyValuePair(Of String, String)) = New List(Of KeyValuePair(Of String, String))
Dim reader = New System.Resources.ResXResourceReader(entry.Key)
Dim node = reader.GetEnumerator()
While node.MoveNext()
resxList.Add(New KeyValuePair(Of String, String)(node.Key.ToString(), node.Value.ToString()))
End While
reader.Close()
Using fs As System.IO.FileStream = New System.IO.FileStream(entry.Key, System.IO.FileMode.Open)
Dim resx As System.Resources.ResXResourceWriter = New System.Resources.ResXResourceWriter(fs)
Using resx
If resxList.Count <> 0 Then
For Each r In resxList
resx.AddResource(r.Key, r.Value)
Next
End If
For Each myval In entry.Value
resx.AddResource(myval.Key, myval.Value)
Next
resx.Generate()
resx.Close()
End Using
fs.Close()
End Using
Next

I have found a solution on: https://github.com/thomaslevesque/AutoRunCustomTool
This is the code I extracted for my pruposes:
Private Function RunCustomToolSuccess(path As String) As Boolean
Dim targetItem As ProjectItem = _applicationObject.Solution.FindProjectItem(path)
If targetItem Is Nothing Then Return False
Dim targetCustomTool As String = CStr(GetPropertyValue(targetItem, "CustomTool"))
If String.IsNullOrEmpty(targetCustomTool) Then Return False
Dim vsTargetItem = targetItem.Object
vsTargetItem.RunCustomTool()
Return True
End Function
Private Shared Function GetPropertyValue(ByVal item As ProjectItem, ByVal index As Object) As Object
Try
Dim prop = item.Properties.Item(index)
If prop IsNot Nothing Then Return prop.Value
Catch __unusedArgumentException1__ As ArgumentException
End Try
Return Nothing
End Function

Related

Getfile with multiple extension filter and order by file name

i am working on vb.net desktop application.now i need that files coming from directory is in with extension .txt and .sql and also need that files coming in order by folder name. in need both together how to do it?
Try
Dim s As String = Txtfolder.Text
Dim files As List(Of String) = New List(Of String)()
Try
For Each f As String In Directory.GetFiles(s, "*.*").Where(Function(f1) f1.EndsWith(".sql") OrElse f1.EndsWith(".txt")).OrderBy(Function(f) f.LastWriteTime).First()
files.Add(f)
Next
For Each d As String In Directory.GetDirectories(s)
files.AddRange(DirSearch(d))
Next
Catch excpt As System.Exception
MessageBox.Show(excpt.Message)
End Try
Private Function DirSearch(ByVal sDir As String) As List(Of String)
Dim files As List(Of String) = New List(Of String)()
Try
For Each f As String In Directory.GetFiles(sDir, "*.*").Where(Function(f1) f1.EndsWith(".sql") OrElse f1.EndsWith(".txt"))
files.Add(f)
Next
For Each d As String In Directory.GetDirectories(sDir)
files.AddRange(DirSearch(d))
Next
Catch excpt As System.Exception
MessageBox.Show(excpt.Message)
End Try
Return files
End Function
Here is an example of option 1 from my comment, i.e. get all file paths and filter yourself:
Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles(folderPath).
Where(Function(s) {".txt", ".sql"}.Contains(Path.GetExtension(s))).
OrderBy(Function(s) Path.GetFileName(s)).
ToArray()
Here's an example of option 2, i.e. get paths by extension and combine:
Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles(folderPath, "*.txt").
Concat(Directory.GetFiles(folderPath, "*.sql")).
OrderBy(Function(s) Path.GetFileName(s)).
ToArray()
An alternative method, which allows searching for multiple directories and filtering the results using multiple search patterns.
It returns an ordered List(Of String):
Private Function DirSearch(ByVal sDirList As String(), SearchPatter As String()) As List(Of String)
Return sDirList.SelectMany(
Function(dir) SearchPatter.SelectMany(
Function(filter)
Return Directory.GetFiles(dir, filter, SearchOption.AllDirectories)
End Function).OrderBy(Function(xDir) xDir)).ToList()
End Function
You can pass the method a list of paths and a list of extensions:
Dim SearchPaths As String() = New String() {"[Directory1]", "[Directory2]"}
Dim ItemSearchPattern As String() = New String() {"*.txt", "*.sql", "*.jpg"}
Dim DirListing As List(Of String) = DirSearch(SearchPaths, ItemSearchPattern)
Extract the content of a sigle directory with:
Dim FilesInDir As List(Of String) = DirListing.
Where(Function(entry) entry.ToUpper().
Contains("[DirectoryName]".ToUpper())).ToList()
This is a case insensitive filter. Remove (ToUpper()) for a case sensitive one.

Split() doesn't work properly

well I'm doing a computing assessment and well I've ran into an issue with splitting a string. For some reason when the string splits the array stores the whole thing in Variable(0). The error that occurs is when it tries to assign TicketID(Index) a value, it says that the array is out of bound.
Here's the code:
Private Sub ReadInformation(ByRef TicketID() As String, CustomerID() As String, PurchaseMethod() As Char, NumberOfTickets() As Integer, FileName As String)
Dim Line, TextArray(3) As String
Dim Index As Integer
FileOpen(1, FileName, OpenMode.Input)
For Index = 0 To 499
Input(1, Line)
TextArray = Line.Split(",")
CustomerID(Index) = TextArray(0)
TicketID(Index) = TextArray(1)
NumberOfTickets(Index) = TextArray(2)
PurchaseMethod(Index) = TextArray(3)
MessageBox.Show(CustomerID(Index))
Next
FileClose()
End Sub
Here's the first 10 lines of the TextFile I'm trying to read:
C001,F3,10,S
C002,F3,2,O
C003,F3,3,S
C004,W2,9,S
C005,T3,10,S
C006,F3,2,S
C007,W1,3,O
C008,W3,1,O
C009,T2,2,S
C010,F2,9,O
Here's the Error Message I receive:
Error Message
I would use some Lists instead of arrays. In this way you don't have to worry about length of the arrays or if there are fewer lines than 500. Of course, using the more advanced NET Framework methods of the File.IO namespace is a must
Private Sub ReadInformation(TicketID As List(Of String), _
CustomerID As List(Of String), _
PurchaseMethod As List(Of Char), _
NumberOfTickets As List(Of Integer), _
FileName As String)
for each line in File.ReadLines(FileName)
Dim TextArray = Line.Split(","c)
if TextArray.Length > 3 Then
CustomerID.Add(TextArray(0))
TicketID.Add(TextArray(1))
' This line works just because you have Option Strict Off
' It should be changed as soon as possible
NumberOfTickets.Add(TextArray(2))
PurchaseMethod.Add(TextArray(3))
End If
Next
End Sub
You can call this version of your code declaring the 4 lists
Dim TicketID = New List(Of String)()
Dim CustomerID = New List(Of String)()
Dim PurchaseMethod = New List(Of Char)()
Dim NumberOfTickets = New List(Of Integer)()
ReadInformation(TicketID, CustomerID, PurchaseMethod, NumberOfTickets, FileName)
Another approach more Object Oriented is to create a class that represent a line of your data. Inside the loop you create instances of that class and add the instance to a single List
Public Class CustomerData
Public Property TicketID As String
Public Property CustomerID As String
Public Property NumberOfTickets As Integer
Public Property PurchaseMethod As Char
End Class
Now the loop becomes
Private Function ReadInformation(FileName As String) as List(Of CustomerData)
Dim custData = New List(Of CustomerData)()
For Each line in File.ReadLines(FileName)
Dim TextArray = Line.Split(","c)
if TextArray.Length > 3 Then
Dim data = new CustomerData()
data.CustomerID = TextArray(0)
data.TicketID = TextArray(1)
data.NumberOfTickets = TextArray(2)
data.PurchaseMethod = TextArray(3)
custData.Add(data)
End If
Next
return custData
End Function
This version requires the declaration of just one list
You can call this version of your code passing just the filename and receiving the result fo the function
Dim customers = ReadInformation(FileName)
For Each cust in customers
Console.WriteLine(cust.CustomerID)
...
Next
Or use it as an array
Dim theFirstCustomer = customers[0]
Console.WriteLine(theFirstCustomer.CustomerID)

Use generic type to create new instance of that objects

I am very new to Generics and it looks promising towards my problem although I have some questions around it.
I am in the process to build a generic function that will deserialize xml into an object and then create an ArrayList of that object and return it.
My question is how will I go to implement generics to do so? To be more clear I need to create new instance of object and assign values to its properties.
This is my function:
Private Function DeSerializeArrayList(serializedData As String, ByVal ObjectName As Object, ByVal ObjType As System.Type, ByVal ReturnObjectType As System.Type) As ArrayList
Dim list As New ArrayList()
Dim extraTypes As Type() = New Type(0) {}
extraTypes(0) = ObjectName.GetType()
'Code fails here and says can't include anonymous class
Dim serializer As New System.Xml.Serialization.XmlSerializer(ObjectName.GetType(), extraTypes)
Dim xReader As XmlReader = XmlReader.Create(New StringReader(serializedData))
Try
Dim obj = serializer.Deserialize(xReader)
For i As Integer = 0 To obj.Items.Length - 1
'Need to create NEW object
Dim labPrice As Type() = New Type(0) {}
labPrice(0) = ReturnObjectType
'Need some method to get the properties of that object
'Dim s = labPrice(0).GetEnumNames
'Need to asign values to that object's properties
'With labPrice
' .fLabPricelistID = obj.Items(i).fLabPricelistID
' .ftariffCode = obj.Items(i).fTariffCode
' .fSurfaced = obj.Items(i).fSurfaced
' .fLabCostPrice = obj.Items(i).fLabCostPrice
' .fLabDiscountedPrice = obj.Items(i).fLabDiscountedPrice
' .fEffectiveDate = obj.Items(i).fEffectiveDate
' .fLaboratoryCodeID = obj.Items(i).fLaboratoryCodeID
' .fDescription = obj.Items(i).fDescription
' .flabProduct = obj.Items(i).fLabProduct
' .fActive = obj.Items(i).fActive
'End With
'list.Add(labPrice)
Next
Catch
Throw
Finally
xReader.Close()
End Try
Return list
End Function
I found a solution that works perfectly for my problem that I had:
Dim obj = DeserializeObject(Of TestObject)(xmlString)
'Function will map xml to object/list of objects
Public Function DeserializeObject(Of T)(xml As String) As T
Dim xs As New XmlSerializer(GetType(T))
Dim memoryStream As New MemoryStream(StringToUTF8ByteArray(xml))
Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)
Dim obj = DirectCast(xs.Deserialize(memoryStream), T)
Return obj
End Function
Public Shared Function StringToUTF8ByteArray(stringVal As String) As [Byte]()
Dim encoding As New UTF8Encoding()
Dim byteArray As Byte() = encoding.GetBytes(stringVal)
Return byteArray
End Function

VB.net Object Array throwing an exception

I am getting an exception when running the following code.
Public Function getSongs() As Song()
' Dim dir As New DirectoryInfo(Application.ExecutablePath)
Dim dir As New DirectoryInfo(directory)
Dim songsInDir() As Song = Nothing
Dim i As Integer = 0
For Each file As FileInfo In dir.GetFiles()
'only read ".mp3" files
If file.Extension = ".mp3" Then
songsInDir(i) = New Song(file.Name)
i = +i
End If
Next
Return songsInDir
End Function
I get an error on line:
songsInDir(i) = New Song(file.Name)
I get an uncaught exception that says:
"Object reference not set to an instance of an object."
The song object has a:
Public Sub new(By Val filename as String)
... sub that sets a variable and retrieves file info (this code works)
Any help would be appreciated!
Try using a list:
Public Function getSongs() As Song()
Dim dir As New DirectoryInfo(directory)
Dim songsInDir() As New List(of Song)
For Each file As FileInfo In dir.GetFiles()
'only read ".mp3" files
If file.Extension = ".mp3" Then
songsInDir.Add(New Song(file.Name)
End If
Next
Return songsInDir.ToArray()
End Function
Your problem is that arrays need a size when they're initialized and setting it to Nothing gives you exactly that. Give the array a size and don't set it to Nothing. Also, there's a much cleaner way to do this.
Public Function getSongs() As Song()
Dim songFiles As String() = Directory.GetFiles(directory, "*.mp3")
Dim songsInDir(songFiles.Length) As Song
Dim i As Integer = 0
For Each file As String In songFiles
songsInDir(i) = New Song(Path.GetFileName(file))
i = +i
Next
Return songsInDir
End Function
You should specify the array size
Dim i as Integer = dir.GetFiles().count or dir.FilesCount()
Dim songsInDir(i) As Song = Nothing
or you can use dynamic array
put this line inside your for loop
ReDim Preserve songsInDir(i)

copy one object to another

.net 3.5, VS 2010... this is for an asp.net website.
I have an class called Agency. there is a second class called Agency_Queries. Agency_Queries inhertis the Agency class. I'm trying to create a function that will copy the like properties in Agency to Agency_Queries. I figured out how to do that.. but when i try to make it more generic so that i can pass in my class name and lists i'm doing something wrong.
So if there is an list(of Agency) that needs to be copied to list(of Agency_Queries) i've got something like the following.
Dim AgencyS As List(Of Agency) = Nothing
Dim Oc As New Agency_Controller
AgencyS = Oc.GetAgencyData(0)
Dim AgencyQueriesS As New List(Of Agency_Queries)
Dim _itemProperties() As Reflection.PropertyInfo = AgencyS.Item(0).GetType.GetProperties()
For Each item In AgencyS
Dim X As NewAgency_Queries
_itemProperties = item.GetType().GetProperties()
For Each p As Reflection.PropertyInfo In _itemProperties
For Each s As Reflection.PropertyInfo In X.GetType().GetProperties()
If p.Name = s.Name Then
s.SetValue(X, p.GetValue(item, Nothing), Nothing)
End If
Next
Next
AgencyQueriesS.Add(X)
Next
the problem is when i go to make this generic by the Dim X as new Agency_Queries. How do i go about creating a new instance of the class in a generic sense. I need to have it be a new instance or each time it gets added to teh AgencyQueriesS list all the objects have the same data values.
Here is the generic version... not working
Shared Function CopyObject(ByVal inputList As Object, ByVal OutputClass As Object, ByVal outputList As Object) As Object
Dim _itemProperties() As Reflection.PropertyInfo = inputList.Item(0).GetType.GetProperties()
For Each item In inputList
Dim oClean As Object = OutputClass
For Each p As Reflection.PropertyInfo In _itemProperties
For Each s As Reflection.PropertyInfo In oClean.GetType().GetProperties()
If p.Name = s.Name Then
s.SetValue(oClean, p.GetValue(item, Nothing), Nothing)
End If
Next
Next
outputList.Add(oClean)
Next
Return outputList
End Function
thanks
shannon
I took a little of this and that and came up with this:
Imports System.Reflection
Public Class ObjectHelper
' Creates a copy of an object
Public Shared Function GetCopy(Of SourceType As {Class, New})(ByVal Source As SourceType) As SourceType
Dim ReturnValue As New SourceType
Dim sourceProperties() As PropertyInfo = Source.GetType().GetProperties()
For Each sourceProp As PropertyInfo In sourceProperties
sourceProp.SetValue(ReturnValue, sourceProp.GetValue(Source, Nothing), Nothing)
Next
Return ReturnValue
End Function
End Class
I use the following:
<Extension>
Public Sub CopyPropertiesByName(Of T1, T2)(dest As T1, src As T2)
Dim srcProps = src.GetType().GetProperties()
Dim destProps = dest.GetType().GetProperties()
For Each loSrcProp In srcProps
If loSrcProp.CanRead Then
Dim loDestProp = destProps.FirstOrDefault(Function(x) x.Name = loSrcProp.Name)
If loDestProp IsNot Nothing AndAlso loDestProp.CanWrite Then
Dim loVal = loSrcProp.GetValue(src, Nothing)
loDestProp.SetValue(dest, loVal, Nothing)
End If
End If
Next
End Sub