OpenFileDialog component in Visual Studio 2017 - visual-studio-2017

I'm working on a VB project in Visual Studio 2017. It's a Blank App (Universal Windows) project. When trying to work with this type of app, it doesn't seem to have an OpenFileDialog like the Windows Forms App (.NET Framework) has. Is there a way to do one of two things:
Create a Windows Forms App that has the same look and feel as the Blank App (Universal Windows)
Add the OpenFileDialog option to the Blank App (Universal Windows)

The following code is a VB version of the MS example at https://learn.microsoft.com/en-us/uwp/api/Windows.Storage.Pickers.FileOpenPicker.
Imports Windows.Storage
Imports Windows.Storage.Pickers
Public NotInheritable Class MainPage
Inherits Page
Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim openPicker As New FileOpenPicker()
openPicker.ViewMode = PickerViewMode.Thumbnail
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary
openPicker.FileTypeFilter.Add(".jpg")
openPicker.FileTypeFilter.Add(".jpeg")
openPicker.FileTypeFilter.Add(".png")
Dim file As StorageFile = Await openPicker.PickSingleFileAsync()
If (file IsNot Nothing) Then
Debug.WriteLine($"Picked File: {file.Name}")
Else
Debug.WriteLine("Operation Cancelled.")
End If
End Sub
End Class

What I ended up doing to get the same(ish) look was to just play around with some of the properties of the form and the buttons. This gave me the look that I was after. It wasn't exact, but I'll take it.
As for OpenFileDialog, I ended up using the following:
Dim myStream As IO.Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
' Open file dialog parameters
openFileDialog1.InitialDirectory = "c:\" ' Default open location
openFileDialog1.Filter = "Executable Files (*.exe)|*.exe|All Files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
Textbox1.Text = openFileDialog1.FileName
' Even though we're reading the entire path to the file, the file is going to be ignored and only the path will be saved.
' Mostly due to me lacking the ability to figure out how to open just the directory instead of a file. Resolution threadbelow.
' http://www.vbforums.com/showthread.php?570294-RESOLVED-textbox-openfiledialog-folder
' Setting the public variable so it can be used later
Dim exepath As String
exepath = IO.Path.GetDirectoryName(Me.txtExeLocation.Text)
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If

Related

Excel VBA script or macro for linking to new Excel document using a template in it

I have a small family-operated shop and, in the process of speeding things up and/or automating them, I need help on the following matter (will try to explain as well as possible, since I am at a novice level on this kind of stuff.)
So, in my shop we offer a certain service (taking specific measurements of body dimensions along with weight/sugar levels etc etc). I have created an .xlsx document that contains all required fields and saved it as a template for future use. What I need to do is this:
I want to have a "master" Excel file with the names of our customers. From there, each name when clicked should open a new Excel file, using the aforementioned template, which would eventually be saved as each customer's record. I've tried a script for linking to the template but opening it as a new file (with the template in it) but, the problem is that each time I click on the name on the master file it opens a new document altogether, while I need it to open a new document named after the name in the original cell, with the template in it. As far as I can think, this is the best "automation" I can accomplish. Is it plausible? If so, how can I do it?
edit: this is the code, as i found it elsewhere:
'File:
' OfficeTemplate.vbs
'
'Problem:
' A hyperlink from an Office application to an Office template opens the template,
' instead of creating a new file.
' The proposed solution
' support.microsoft.com/kb/278627
' did not work.
'
'Solution:
' Create a hyperlink to a VBS file that starts the process.
'
'Instructions:
' Copy this VBScript into the same directory of your template.
' Rename it so that the VBS file name has the name of the template file in front.
' Example:
' Template name: test.dotx
' VBScript name: test.dotx.vbs
' Create the hyperlink to the VBS file.
Set fso = CreateObject("Scripting.FileSystemObject")
'Get the name of the template
OurName = fso.GetBaseName(WScript.ScriptName)
'Find all files in our directory
For Each File In fso.GetFolder(fso.GetParentFolderName(WScript.ScriptFullName)).Files
'Did we found the template?
If StrComp(OurName, File.Name, vbTextCompare) = 0 Then
'Invoke the default verb
CreateObject("Shell.Application").Namespace(0).ParseName(File.Path).InvokeVerb
'Wait a second to let the application start
WScript.Sleep 1000
'Done
Exit For
End If
Next
this is my template:
http://i215.photobucket.com/albums/cc55/psyclone_tread/templ.jpg
this is the master file, just a column with names and one with phone numbers, i want the names to link to each customer's individual file.
http://i215.photobucket.com/albums/cc55/psyclone_tread/master.jpg
Let me give you a very simple answer for this. Use VBA instead of VBS, and write code inside your master excel as per following illustration.
When you click on the cell with the name,
If File.Exists ("YourFolder\" & ActiveCell.Value & ".xlsx") Then
Workbooks.Open("YourFolder\" & ActiveCell.Value & ".xlsx")
Else
WorkBooks.Add(YourTemplate)
Fill in the details already present in the master sheet to new workbook if needed
NewWorkbook.Save("YourFolder\" & ActiveCell.Value & ".xlsx")
End If

VBS script attempting to write to .rc file returns error

I am trying to find a process by which to edit and write to a resource .rc file; I attempted to use the sample code listed at
How to increment values in resourse file by using vbscript but the last line in both samples returned the same error ( fso.OpenTextFile(rcfile, 2).Write rctext ) :
Error: Invalid procedure call or argument
Code: 800A0005
Source: Microsoft VBScript runtime error
I modified the script to write out to a .txt file and that worked fine, but I'm baffled as to what may be causing the problem writing out to a .rc file.
From the linked sample (simplified)
rctext = fso.OpenTextFile(rcfile).ReadAll
rctext = ....
fso.OpenTextFile(rcfile, 2).Write rctext
The idea is read all the file, and as far as there is no variable holding a reference to the opened file, it is closed, then change what needs to be changed and open again the file, now for writing, and write the changed content to file
And, usually, it works. But sometimes the file opened for reading is not closed fast enough to later open it for writing.
To ensure the file is closed and then can be opened for writing, change the reading code to
set f = fso.OpenTextFile(rcfile)
rctext = f.ReadAll
f.Close
As your line
fso.OpenTextFile(rcfile, 2).Write rctext
does three things (access fso, open file, write to it), there are many things that could go wrong. Please see this answer for ideas wrt to problems concerning the first two actions. Another answer concerns the write.
In your case, the evidence - works with a.txt, but not with b.rc - makes it highly improbable that the file's opening is to blame (so .Close won't save you). I suspect that the .rc contains Unicode (UTF-8/UTF-16) data that the textstream can't encode.
So either use the unicode parameter to read/write open the file with UTF-16 encoding or an ADODB.Stream for UTF-8.
It seems that the answer to my question required both of your answers(#MC ND and #Ekkehard.Horner); also, once I changed the vbs script to open and write to the .rc file in Unicode, which I'm not sure why I have to, the script was able to execute without error.
Here is the vbs script in it's final form:
Const ForReading = 1, ForWriting = 2
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Const DoNotCreate = false
rcFile = "C:\Path\To\RC\File.rc"
major = 4
minor = 3
maint = 2
build = 1
version = major & "," & minor & "," & maint & "," & build
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileObj = fso.OpenTextFile(rcFile, ForReading, DoNotCreate, TristateTrue)
rcText = fileObj.ReadAll
fileObj.Close
Set regex = New RegExp
regex.Global = True
regex.Pattern = "(PRODUCTVERSION|FILEVERSION) \d+,\d+,\d+,\d+"
rcText = regex.Replace(rcText, "$1 " & version)
regex.Pattern = "(""(ProductVersion|FileVersion)"",) ""\d+, \d+, \d+, \d+"""
rcText = regex.Replace(rcText, "$1 """ & Replace(version, ",", ", ") & """")
Set fileObj = fso.GetFile(rcFile)
Set textStream = fileObj.OpenAsTextStream(ForWriting, TristateTrue)
textStream.Write rcText
textStream.Close
The only thing that does not seem to work is the regex for replacing the ProduceVersion|FileVersion values, but hopefully I can hammer that out within a reasonable time.

How to match and return part of an HTML file in ASP

I'm looking to match a part of several HTML files that get passed into a loop in an ASP file and then return that part of the HTML files to include in my output. Here's my code so far:
<%for i=0 to uBound(fileIDs) ' fileIDs is an array of URLs
dim srcText, outText, url
Set ex = New RegExp
ex.Global = true
ex.IgnoreCase = true
ex.Pattern = "<section>[\S\s]+</section>" ' This finds the HTML I want
url = fileIDs(i)
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET", url, false
xmlhttp.send ""
srcText = xmlhttp.responseText
outputText = ex.Execute(mediaSrcText) ' I expect this to be the HTML I want
Response.Write(outputText.Item(0).Value) ' This would then return the first instance
set xmlhttp = nothing
next %>
I've tested the regular expression on my files and it's matching the parts that I want it to.
when I run the page containing this code, I get an error:
Microsoft VBScript runtime error '800a01b6'
Object doesn't support this property or method
on the line with ex.Execute. I've also tried ex.Match, but got the same error. So I'm clearly missing the proper method for returning the match so I can write it out into the file. What is that method? Or am I approaching the problem from the wrong direction?
Thanks!
You need a Set when you're assigning outputText:
Set outputText = ex.Execute(mediaSrcText)
I should probably also say that you really shouldn't be using regular expressions to attempt to parse HTML, although I don't know enough about the context to offer more specific advice.

VB6 List and Delete All Files in Directory

I need to grab the names of all files in a directory, I am currently using this code:
Dim File As String
File = Dir$(Environ("AppData") & "\*.exe")
Do While Len(File)
MsgBox "Deleting: " & Environ("AppData") & "\" & File
Kill Environ("AppData") & "\" & File
File = Dir$
Loop
This works fine, however it does not display hidden/system files, or files with any attributes other than 'normal', how can I list files no matter their attributes?
I have tried this as well, which has the same outcome:
Kill Environ("AppData") & "\*.*"
The Dir function can take a second parameter for attributes:
File = Dir$(Environ("AppData") & "\*.exe", vbHidden & vbSystem)
You can fin more about the Dir function here.
I pretty much always use the Microsoft Scripting Runtime for file I/O from VB6. It just does more, and it does it better and more easily. One tiny downside is that your VB program is now dependent on the Scripting Runtime DLL (scrrun.dll), which you should add as a reference from within the VB6 IDE.
Here's an example that deletes all files from a folder.
' Note: This code is untested.
Sub Main()
DeleteAllFilesInFolder Environ("App_Data")
End Sub
Sub DeleteAllFilesInFolder(strFolder As String)
Dim fso As Scripting.FileSystemObject
Dim objFolder As Scripting.Folder
Dim objFile As Scripting.File
Set fso = New Scripting.FileSystemObject
Set objFolder = fso.GetFolder(strFolder)
For Each objFile in objFolder.Files
objFile.Delete force:=True
Next
End Sub

Quickly enter command-line parameters for Visual Studio debugging?

I want to change my command-line arguments and then debug my executable.
With the default Visual Studio UI, this takes me several tortuous mouse and keyboard actions:
Project ... right click ... Configuration Properties ... Debugging ... Command Arguments ... type args ... ENTER ... F5
Is there a way to make this common action as easy as other common operations, for example, searching all files for a pattern which goes:
CNTL+SHIFT+F ... type search pattern ... ENTER
For example, is there an way to create a custom edit box to allow quick access to the debug command-line arguments? Or a way to have a key-binding pop up a simple "debug dialog" where the args can be entered and debugging started directly? e.g.
ALT+F5 ... type args ... ENTER
I am using C++ and Visual Studio 2010 Express. Thanks!
The extension CLIArgsMadeEasy 2010/2012 is a great little thing that puts the project's debug session's command line arguments right in a little text box on the visual studio toolbar, IMO, its alot easier and less tedious than using macros.
The Link
http://visualstudiogallery.msdn.microsoft.com/8159cd7d-2c81-47f3-9794-a347ec1fba09?SRC=VSIDE
You can just type CLIArgsMadeEasy in your search box in the extensions manager which will find it fairly quickly in the gallery, thats how I installed it, if you need to know. Hope this helps!
Macro below should help. Open "Tools->Macros->Macro Explorer", then create new module, edit it, and copy-paste code below. Required command is SetCommandArgsProperty. UI is not nice, but it works (VS 2005, I hope this will also work in VS 2010). Then add any shortcut you like to run this macro.
Here are some details:
Find startup project
Select it active configuration and find property with name "CommandArguments"
Create edit box with the current value in it
Update property if OK is selected
Sub SetCommandArgsProperty()
Dim newVal As Object
newVal = InputValue(GetCommandArgsPropertyValue())
If TypeOf newVal Is String Then
SetCommandArgsProperty(newVal)
End If
End Sub
Function InputValue(ByVal defaultText As String)
Dim frm As New System.Windows.Forms.Form
Dim btn As New System.Windows.Forms.Button
Dim edit As New System.Windows.Forms.TextBox
edit.Text = defaultText
edit.Width = 100
btn.Text = "OK"
btn.DialogResult = System.Windows.Forms.DialogResult.OK
frm.Text = "Input command line properties"
frm.Controls.Add(btn)
btn.Dock = System.Windows.Forms.DockStyle.Bottom
frm.Controls.Add(edit)
edit.Dock = System.Windows.Forms.DockStyle.Top
frm.Height = 80
frm.Width = 300
If frm.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Return edit.Text
End If
Return System.DBNull.Value
End Function
Function GetCommandArgsProperty() As EnvDTE.Property
Dim solution As Solution
Dim project As Project
Dim sb As SolutionBuild
Dim str As String
Dim cm As ConfigurationManager
Dim config As Configuration
Dim properties As Properties
Dim prop As EnvDTE.Property
solution = DTE.Solution
sb = solution.SolutionBuild
For Each str 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
Function GetCommandArgsPropertyValue()
Return GetCommandArgsProperty().Value
End Function
Sub SetCommandArgsProperty(ByVal value As String)
GetCommandArgsProperty().Value = value
End Sub
At least in Visual Studio 2012, you can use Alt+F7 shortcut to directly access project properties.
Furthermore, the opened Property Pages normally remembers the last opened item, i.e. Configuration Properties -> Debugging.