WPF Vb.net Copyto not working? - wpf

I am simply tyring to fire an event that copies a program to the Startup folder. I do not understand where I am going wrong? I keep on getting exception message. The file that is being copies is NOT in use.
Try
Dim DesktopLink As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim StartupFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim info As New FileInfo(StartupFolder)
info.CopyTo(DesktopLink + "\doessomething.bat")
Catch ex As Exception
MessageBox.Show("Error: Can not copy to startup folder")
End Try

Right now, you're creating a FileInfo from a folder, not a file.
This should likely be:
Dim info As New FileInfo(Path.Combine(StartupFolder, "doessomething.bat"))
info.CopyTo(Path.Combine(DesktopLink, "doessomething.bat"))
Or, even easier:
Dim source = Path.Combine(StartupFolder, "doessomething.bat")
Dim target = Path.Combine(DesktopLink, "doessomething.bat")
File.Copy(source, target)

Related

Getting MetaData from an image file

We have images stored on a DB and they are being used to replace an image within a Word document - that bit works perfectly, except where the replacement image is portrait and it's replacing a landscape one, so I'm trying to get the metadata to determine how the image is orientated using this function
Public Function GetImageTags(ImageFile() As Byte) As String()
Try
Dim vReturnArray() As String = Nothing
Using MS As New System.IO.MemoryStream(ImageFile)
Dim vDecoder As BitmapDecoder = BitmapDecoder.Create(MS, BitmapCreateOptions.None, BitmapCacheOption.Default)
Dim vFrame As BitmapFrame = vDecoder.Frames(0)
Dim vMetadata As BitmapMetadata = TryCast(vFrame.Metadata, BitmapMetadata)
If vMetadata IsNot Nothing And vMetadata.Keywords IsNot Nothing Then
vReturnArray = vMetadata.Keywords.ToArray()
End If
End Using
Return vReturnArray
Catch ex As Exception
EmailError(ex)
Return Nothing
End Try
End Function
...but it throws the toys out with...
This codec does not support the specified property.
at System.Windows.Media.Imaging.BitmapMetadata.GetQuery(String query)
at System.Windows.Media.Imaging.BitmapMetadata.get_Keywords()
...at BitMapMetadata.Keywords. Any idea how I can overcome this and get the keywords?
Thank you
================ UPDATE ================
It appears that the error, and I also tried...
vReturnArray = TryCast(vMetadata.GetQuery("System.Keywords"), String())
... is only returned for some images, but all that I tried returned Nothing for the String()
There is a really good EXIF class on Code Project that is easy to implement, either with a string link to the file
Dim vEXIF As New ImageEXIF(ImagePath)
Dim vOrientation As Integer = vEXIF.Orientation
or as BitMap
Dim vOrientation As Integer = 0
Using vBitmap As System.Drawing.Image = System.Drawing.Image.FromStream(New IO.MemoryStream(ImageFile))
Dim vEXIF As New ImageEXIF(vBitmap)
vOrientation = vEXIF.Orientation
End Using
It would not be difficult to add another Sub to the class for Byte(), but the above conversion is quite straightforward and the class should work with all image types.
You could use MetadataExtractor to access the image metadata.
Check for the presence of ExifDirectoryBase.TagOrientation on any of the contained Exif directories.
Something like this (sorry it's C# as I don't know VB.NET):
var orientation = ImageMetadataReader.ReadMetadata(imagePath)
.OfType<ExifSubIfdDirectory>()
.Select(d => d.GetObject(ExifDirectoryBase.TagOrientation))
.First(o => o != null);

Load/split a .txt into multiple listboxes.?

I am trying to figure out a way to load a very large .txt file and thought if I break it into sections (Listboxes) it would load faster and be easier to manipulate with less lag. Or is there a way to OFD with a background worker?
Here is how I am loading the .txt
TextBox1.Text = ""
OpenFileDialog1.Title = "Load File"
OpenFileDialog1.InitialDirectory = "C:temp"
OpenFileDialog1.ShowDialog()
Dim path As String = OpenFileDialog1.FileName
TextBox1.Text = path
Dim lines() As String = IO.File.ReadAllLines(TextBox1.Text)
I can go in and mark every 1/4 of the .txt with a delimiter if that would help?
I was thinking if I iterate through XX amount of lines then Next listbox etc. Maybe some form of items.count in a if not statement? My mind is going in circles please aim me in the best direction. My file is 25.MB and growing slowly. Notepad++ is the only thing handling it well ATM.
ListBox1.Items.Add(lines(1 - 10000))
throws an error ("Outside array index or similar")
ListBox1.Items.Add(lines(10000))
Loads the single line
Probably something along the lines of this. This is not 100% accurate code. But to give you an idea.
Dim dt As New DataTable()
Dim lines As New List(Of [String])()
lines = New List(Of [String])(File.ReadLines(ofDialog.FileName))
Task.Run(Function()
Dim options As New ParallelOptions()
options.MaxDegreeOfParallelism = CInt(1)//Number of threads to spawn
Parallel.ForEach(lines, options, Function(line)
dt.Rows.Add()
End Function)
Me.Invoke(DirectCast(Sub() listview.DataSource = dt, MethodInvoker))
End Function)

VB.NET - .accdb database not saving changes

I can't figure out why my code won't save to my .accdb database.
I am fetching data from a .accdb database file and displaying it in a DataGridView, and then allowing changes to be made to it there. (This is a stock control system.) After making changes, the user is meant to be able to send the data back so it is saved in the .accdb file.
I have looked online everywhere and tried multiple different ways of doing this. This is the way I am currently using to solve the problem, but when running the code it does not save to the .accdb file. (However, it throws up no errors.)
Public Class Database
Dim datatable As DataTable
Dim adapter As OleDb.OleDbDataAdapter
Dim dbCon As New OleDb.OleDbConnection
Dim dbProvider As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
Dim dbRsrc As String = "Data Source =" & System.IO.Directory.GetCurrentDirectory & "/Resources/List.accdb"
Dim binding As BindingSource
Dim cmdBuilder As OleDb.OleDbCommandBuilder
Private Sub Database_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
adapter = New OleDb.OleDbDataAdapter("Select * FROM List", dbCon)
datatable = New DataTable
adapter.FillSchema(datatable, SchemaType.Source)
adapter.Fill(datatable)
binding = New BindingSource
binding.DataSource = datatable
dbCon.Close()
StockTable.DataSource = binding
End Sub
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
'insert validation here
Try
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
cmdBuilder = New OleDb.OleDbCommandBuilder(adapter)
adapter.AcceptChangesDuringUpdate = True
adapter.Update(datatable)
dbCon.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString() & " Save Unsuccessful.")
End Try
End Sub
End Class
Not sure where I'm going wrong - when I hit the 'save' button, it should connect to the database, build a SQL query to update it and then update my datatable + .accdb database, right?
To test it, I've tried editing multiple columns and saving it, but when opening the file it still says the same values as it had before.
Any suggestions/pointers? I'm pretty newbie to VB.NET, learnt it about 3 months ago and only just starting to get fully into it.
Many thanks to the user "jmcilhinney" who helped me to reach this answer. I feel highly stupid at not realising that my code was working.
I used
Debug.WriteLine("Update value: " & adapter.Update(datatable))
Debug.WriteLine("Connection str: " & dbProvider & dbRsrc)
to find that my update command worked, and that in fact the output of my database file was in the /bin/ folder. I didn't realise that it used the /bin/ folder, and was looking in the root folder with the .VB files, etc.

Start debugging from add-in

I'm making VS add-in which changes debugging commandline.
This part works, but i need to start debugging after it's changed.
How do I start debugging from add-in?
mybe something from this function might help
Function GetCommandArgsProperty() As EnvDTE.Property
Dim solution As Solution
Dim project As Project
Dim sb As SolutionBuild
Dim cm As ConfigurationManager
Dim config As Configuration
Dim properties As Properties
Dim prop As EnvDTE.Property
solution = _applicationObject.Solution
sb = solution.SolutionBuild
For Each str As String In sb.StartupProjects
project = solution.Item(str)
cm = project.ConfigurationManager
config = cm.ActiveConfiguration
properties = config.Properties
For Each prop In properties
If prop.Name = "CommandArguments" Then
Return prop
End If
Next
Next
End Function
got it working
Dim dte As EnvDTE.DTE = GetService(GetType(EnvDTE.DTE))
dte.Solution.SolutionBuild.Run()

winform's Application Settings : cannot save application settings which has been added during the run time

I having some issues with saving Application settings during the run time...
If i change the setting scope to user, it works fine, but in application scope, nothing being happened...
I've used :
Properties.Settings.Default.Save();
any ideas ?
thanks
That's because setting the scope to Application makes it read-only.
See Using Settings in C#
Application-scope settings are read only, and can only be changed at design time or by altering the .exe.config file in between application sessions. User-scope settings, however, can be written at run time, just as you would change any property value. The new value persists for the duration of the application session. You can persist changes to user settings between application sessions by calling the Settings.Save method.
You can save and read setting like all advanced programs in Registry, and that is how to do it:
Public Function GetRegistryValue(ByVal KeyName As String, Optional ByVal DefaultValue As Object = Nothing) As Object
Dim res As Object = Nothing
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
res = k.GetValue(KeyName, DefaultValue)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
Return res
End Function
Public Sub SetRegistryValue(ByVal KeyName As String, ByVal _Value As Object)
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
k.SetValue(KeyName, _Value)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
k.SetValue(KeyName, _Value)
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
End Sub
Or even more you can make a serializable class ([Serializable()] attrib) that contains all of your settings as properties, then save it in your app directory, with the BinaryFormatter class.
Public Sub saveBinary(ByVal c As Object, ByVal filepath As String)
Try
Using sr As Stream = File.Open(filepath, FileMode.Create)
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(sr, c)
sr.Close()
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
Public Function loadBinary(ByVal path As String) As Object
Try
If File.Exists(path) Then
Using sr As Stream = File.Open(path, FileMode.Open)
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim c = bf.Deserialize(sr)
sr.Close()
Return c
End Using
Else
Throw New Exception("File not found")
End If
Catch ex As Exception
Throw ex
End Try
Return Nothing
End Function
Check this post out. You just refer to the application scoped settings like this:
Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file
Worked for me.

Resources