|
tacbanon wrote: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
Parameter name: startIndex
You have an index to an array or list that is too large or too small. Check the code at the line mentioned in the error message. If necessary use your debugger to see exactly which variable is causing the problem.
|
|
|
|
|
Hi,
I need someone who uses/used Visual Basic to answer a few questions as an "interview" for a class. Respond if willing.
Thanks!
|
|
|
|
|
Willing.
Be carefull what you wish for though
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Hi
The script shown at the bottom creates a subfolder in "C:\Downloads" and moves files that are within it all into it after I named it .
What it is that I already have subfolders within the folder and when im running command its also merging the subfolders that I have alreay created too.
I may be wrong but believe that the line below is causing the issue but donno what to put in. I think that its tellling it for each object in the folder to merge but as mentioned I only need files merged and not the folders. They just need to be left there and do nothing with them.
Am I right and if so what do I need to prevent it from merging subfolders already created.
Any ideas?
<pre>On Error Goto 0
For Each objFile In objDLFolder.Files
objFSO.MoveFile objFile.Name, strNewFolder & "\"
The original script below
Option Explicit
Const strDLFolder = "C:\Downloads"
Dim objFSO, objWShell, objDLFolder, strNewFolder, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWShell = CreateObject("WScript.Shell")
If Not objFSO.FolderExists(strDLFolder) Then objFSO.CreateFolder(strDLFolder)
objWShell.CurrentDirectory = strDLFolder
Set objDLFolder = objFSO.GetFolder(strDLFolder)
If objDLFolder.Files.Count = 0 Then WScript.Quit
Do
Err.Clear
strNewFolder = InputBox("Folder Name", vbLf & "Enter the name of the folder to be created:")
If strNewFolder = False Then WScript.Quit
On Error Resume Next
objFSO.CreateFolder strNewFolder
Loop While Err.Number <> 0 Or Not objFSO.FolderExists(strNewFolder)
On Error Goto 0
For Each objFile In objDLFolder.Files
objFSO.MoveFile objFile.Name, strNewFolder & "\"
Next
objWShell.Popup "All files moved.", 0, "Done", vbInformation Or vbSystemModal Or &h00040000&
objWShell.Run "explorer.exe /select,""" & objFSO.BuildPath(strDLFolder, strNewFolder) & """"
Next
|
|
|
|
|
I have not used FSO, but it is quite possible that the For Each statement returns a full list of all objects, including files and subfolders. You may need to check the properties of each returned object before doing the copy.
|
|
|
|
|
In a vb.net 2010 desktop application, I added an app.config file to the application 2 years ago. I did not so I can point to different directly paths without needing to recompile the application. This change worked at that time.
I have not needed to change the application until recently.
Now I actually have to recompile the application so the app.config file changes will be picked up.
Thus can you tell me what I can do to the application so I can change the app.config file without needing to recompile the application?
|
|
|
|
|
Does you code actually look for a setting in the app.config file? What does that code look like?
|
|
|
|
|
The code in the application looks like the following:
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
frmMain.GlobalForm = Me
Dim strUserName As String = ConfigurationManager.AppSettings("NameofUser")
If strUserName = "ANN" Then
Dim strDirectoryPath As String = ConfigurationManager.AppSettings("File_directory_path")
If Not (Directory.Exists(strDirectoryPath)) Then
Application.Exit()
Exit Sub
End If
Else
Dim strDirectoryPath2 As String = ConfigurationManager.AppSettings("File_directory_path_KARON")
If Not (Directory.Exists(strDirectoryPath2)) Then
Application.Exit()
Exit Sub
End If
End If
The code in the app.config file looks like:
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information"/>
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<startup><supportedRuntime version="v2.0.50727"/>
</startup>
<appSettings>
<add key="NameofUser" value="ANN"/>
</appSettings>
</configuration>
|
|
|
|
|
It's not entirely clear what you're doing or what you expect.
Any setting you want can be placed into the app.config appSettings section and loaded with an appropriate call to ConfigurationManager.AppSettings("name") to get the setting of that name.
The app.config file is NEVER compiled into the application. It must reside in the same folder as the .EXE that is loading it.
In your code snippets, you try to get settings called "File_directory_path" and "File_directory_path_KARON", but these never show up in the app.config file so the values returned for those names will be null, not any string value.
When you change the setting in app.config, the new setting will be loaded on the next call to retrieve that setting in the code.
|
|
|
|
|
I did not show the values in app.config file for "File_directory_path" and "File_directory_path_KARON",
since I just wanted to show you an example. I know what the code is supposed to do by it is not working. The app.config file will not let me change the values outside of the application. The file is locked.
Once a user signs on to their computer, I try to change the values in the app.config file. The permissions are locked. The network people say that the user and I have all the rights (permissions) that are needed. I open up the app.config file in notepad in the users computer and the values are not saved. Do you know what else could be wrong so I can not change the permissions. I install the application using the old setup and deployment project that is in visual studio.
|
|
|
|
|
If the app isn't running, the only other common possibility is that the executable (and the config file) are under Program Files, which is READ ONLY to everyone on the machine, except admins. If you're an admin on the machine and can't understand why when YOU try to save the changes to app.config, it's because you have to run Notepad as an administrator. (Search for notepad.exe, right-click it, pick Run as administrator..)
If you're putting settings in a file that needs to be written to by your app or even Notepad, put them in a file under C:\ProgramData\appName\...
You can then modify the code to load the settings from that path instead of from under Program Files. See this[^] for examples.
|
|
|
|
|
In the bin directory, there is a runtime config file called 'programname.exe.config'. I do not deploy this when I deploy the application. Do I need to include the 'programname.exe.config' as part of the deployment? if so, when the application is only a user's computer, would I change the 'programname.exe.config' file and/or the app.config file in notepad?
|
|
|
|
|
|
Hello .... Please someone help me out. I want to insert new table in ms word from vb.net application, I use bookmark to define the range but it still give error "the range cannot be delete", below is my code.
Public Sub invoicePrinting1(ByVal strBasePath As String, ByVal userid As String)
Dim oWord = New Word.Application With {.Visible = False}
Dim oDoc As Word.Document = oWord.Documents.Open(strBasePath)
Dim pos, len As Integer
Dim reg As Regex
Dim bookmarkName As String
Dim rng As Object
Dim search As String = "@@Item_List1@@"
Dim dgv As DataGridView = printbox.DGVacct
Dim headers = (From ch In dgv.Columns
Let header = DirectCast(DirectCast(ch, DataGridViewColumn).HeaderCell, DataGridViewColumnHeaderCell)
Select header.Value).ToArray()
Dim headerText() As String = Array.ConvertAll(headers, Function(v) v.ToString)
Dim items() = (From r In dgv.Rows
Let row = DirectCast(r, DataGridViewRow)
Where Not row.IsNewRow
Select (From cell In row.Cells
Let c = DirectCast(cell, DataGridViewCell)
Select c.Value).ToArray()).ToArray()
Dim table As String = String.Join(vbTab, headerText) & Environment.NewLine
For Each a In items
Dim t() As String = Array.ConvertAll(a, Function(v) v.ToString)
table &= String.Join(vbTab, t) & Environment.NewLine
Next
table = table.TrimEnd(CChar(Environment.NewLine))
Clipboard.SetText(table)
' keyword that you want to search
reg = New Regex(search)
' find the text in word file
Dim m As Match = reg.Match(oDoc.Range.Text, 0)
pos = m.Index
' start is the starting position of the token in the content...
len = search.Length
' select the text
rng = oDoc.Range(pos, len + pos)
bookmarkName = "MyBookmarkName"
oDoc.Bookmarks.Add(bookmarkName, rng)
Dim tdRange As Word.Range = oDoc.Range(0, pos)
With tdRange
.Collapse(Direction:=Word.WdCollapseDirection.wdCollapseEnd)
.InsertParagraphAfter()
.Collapse(Direction:=Word.WdCollapseDirection.wdCollapseEnd)
End With
Dim oTable As Word.Tablespoons = oDoc.Tables.Add(oDoc.Bookmarks.Item(bookmarkName).Range, items.Count + 1, headers.Count)
oTable.Range.Paste()
oTable.Range.Font.Size = 9
'make the first row bold, fs 14 + change textcolor
oTable.Rows.Item(1).Range.Font.Bold = &H98967E
oTable.Rows.Item(1).Range.Font.Size = 10
oTable.Rows.Item(1).Height = 20
oTable.Rows.Item(1).Range.Font.Color = Word.WdColor.wdColorWhite
oTable.Range.AutoFormat()
'change backcolor of first row
oTable.Rows.Item(1).Range.Shading.Texture = Word.WdTextureIndex.wdTextureNone
oTable.Rows.Item(1).Range.Shading.ForegroundPatternColor = Word.WdColor.wdColorAutomatic
oTable.Rows.Item(1).Range.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25
'set table borders
With oTable
.Columns(1).SetWidth(oDoc.Application.CentimetersToPoints(wd(4.3F)), Word.WdRulerStyle.wdAdjustProportional)
.Columns(2).SetWidth(oDoc.Application.CentimetersToPoints(wd(10.5F)), Word.WdRulerStyle.wdAdjustProportional)
.Columns(3).SetWidth(oDoc.Application.CentimetersToPoints(wd(4.8F)), Word.WdRulerStyle.wdAdjustProportional)
.Columns(4).SetWidth(oDoc.Application.CentimetersToPoints(wd(5.0F)), Word.WdRulerStyle.wdAdjustProportional)
End With
'set table borders
With oTable.Range.Tables(1)
With .Borders(Word.WdBorderType.wdBorderLeft)
.LineStyle = Word.WdLineStyle.wdLineStyleSingle
.LineWidth = Word.WdLineWidth.wdLineWidth025pt
.Color = Word.WdColor.wdColorAutomatic
End With
With .Borders(Word.WdBorderType.wdBorderRight)
.LineStyle = Word.WdLineStyle.wdLineStyleSingle
.LineWidth = Word.WdLineWidth.wdLineWidth025pt
.Color = Word.WdColor.wdColorAutomatic
End With
With .Borders(Word.WdBorderType.wdBorderTop)
.LineStyle = Word.WdLineStyle.wdLineStyleSingle
.LineWidth = Word.WdLineWidth.wdLineWidth025pt
.Color = Word.WdColor.wdColorAutomatic
End With
With .Borders(Word.WdBorderType.wdBorderBottom)
.LineStyle = Word.WdLineStyle.wdLineStyleSingle
.LineWidth = Word.WdLineWidth.wdLineWidth025pt
.Color = Word.WdColor.wdColorAutomatic
End With
With .Borders(Word.WdBorderType.wdBorderHorizontal)
.LineStyle = Word.WdLineStyle.wdLineStyleSingle
.LineWidth = Word.WdLineWidth.wdLineWidth025pt
.Color = Word.WdColor.wdColorAutomatic
End With
With .Borders(Word.WdBorderType.wdBorderVertical)
.LineStyle = Word.WdLineStyle.wdLineStyleSingle
.LineWidth = Word.WdLineWidth.wdLineWidth025pt
.Color = Word.WdColor.wdColorAutomatic
End With
.Borders(Word.WdBorderType.wdBorderDiagonalDown).LineStyle = Word.WdLineStyle.wdLineStyleNone
.Borders(Word.WdBorderType.wdBorderDiagonalUp).LineStyle = Word.WdLineStyle.wdLineStyleNone
.Borders.Shadow = False
.Rows.Height = 7
End With
oDoc.Save()
oWord.Quit()
oDoc = Nothing
oWord = Nothing
End Sub
|
|
|
|
|
I'm trying to figure out how to make the Ascending / Descending extension in an Order By statement in a Linq query conditional based upon a menu selection. Here's the query:
Dim fileItem = From files In itemList
Where files.Tag(0) = "file"
Order By files.SubItems.Item(indx).Text
Select files
(itemList is a List of listviewitems)
Any advice is appreciated.
Sometimes the true reward for completing a task is not the money, but instead the satisfaction of a job well done. But it's usually the money.
|
|
|
|
|
|
Not exactly what I was hunting since the menu item isn't a part of the collection. But no big thing. I finally just added code to reverse the collection if I needed it sorted in descending order.
Sometimes the true reward for completing a task is not the money, but instead the satisfaction of a job well done. But it's usually the money.
|
|
|
|
|
Simple:
Dim fileItem = From files In itemList
Where files.Tag(0) = "file"
Select files
If shouldSortDescending Then
fileItem = From files In fileItem
Order By files.SubItems.Item(indx).Text Descending
Select files
Else
fileItem = From files In fileItem
Order By files.SubItems.Item(indx).Text
Select files
End If Or, using "method syntax":
Dim fileItem = itemList.Where(Function (files) files.Tag(0) = "file")
If shouldSortDescending Then
fileItem = fileItem.OrderByDescending(Function (files) files.SubItems.Item(indx).Text)
Else
fileItem = fileItem.OrderBy(Function (files) files.SubItems.Item(indx).Text)
End If
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
You could always create your own extension method.
Module SortingExtensions
<Extension()>
Public Function OrderBy(Of TElement, TKey)(
ByVal source As IEnumerable(Of TElement),
ByVal selector As Func(Of TElement, TKey),
ByVal sortDescending As Boolean) _
As IOrderedEnumerable(Of TElement)
Return If(sortDescending, source.OrderByDescending(selector), source.OrderBy(selector))
End Function
<Extension()>
Public Function ThenBy(Of TElement, TKey)(
ByVal source As IOrderedEnumerable(Of TElement),
ByVal selector As Func(Of TElement, TKey),
ByVal sortDescending As Boolean) _
As IOrderedEnumerable(Of TElement)
Return If(sortDescending, source.ThenByDescending(selector), source.ThenBy(selector))
End Function
End Module
...
Dim fileItem = itemList.Where(Function (files) files.Tag(0) = "file").OrderBy(Function (files) files.SubItems.Item(indx).Text, shouldSortDescending)
There's no option to extend the query syntax though.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
Thanks Richard. I ended up writing something similar to the "Simple" version. I've been shamelessly flip-flopping around on this thing for a month - good thing it's just for me and not a customer .
Sometimes the true reward for completing a task is not the money, but instead the satisfaction of a job well done. But it's usually the money.
|
|
|
|
|
I have an HTML file that I'm loading into a WebBrowser control via .Navigate(myfileURI) which works fine.
In my application I'm trapping Javascript errors in order to handle them myself via the code on this web page:
https://msdn.microsoft.com/en-us/library/system.windows.forms.htmlwindow.error%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
This seems to work fine until I tweak the compatibility mode in the html file. For example, using the meta tag:
<meta http-equiv="X-UA-Compatible" content="IE=8">
or even no such tag at all works fine. However when I use the meta tag:
<meta http-equiv="X-UA-Compatible" content="IE=10">
or
<meta http-equiv="X-UA-Compatible" content="IE=edge">
the code to trap Javascript errors no longer works.
I'd really like to know why?
I'd prefer to use IE10 or edge for access to better Javascript functionality.
Here's the code I used in a simple Visual Basic Form and WebBrowser control as well as a simple "test.html" file below it:
(Note: the "a.args" line in the html file is suppose to deliberately throw an error)
Thanks in advance,
Jeff
Form1.vb
Imports System.Runtime.InteropServices
Public Class Form1
<ComVisible(True)>
Public Class JSRequester
Public this As Form1
Public Sub log(s As String)
Debug.Print(s)
End Sub
Public Sub send(MFSYS As String)
Debug.Print("[" + this.Name + "] INPUT <" + MFSYS + ">")
this.WebBrowser1.Document.InvokeScript("eval", New Object() {"alert('Hello Script!');"})
End Sub
Public Sub New(frmSender As Form1)
this = frmSender
End Sub
End Class
<ComVisible(False)>
Public bMouseDown As Boolean = False
Public bFormActivated As Boolean = False
Public WithEvents ScriptWindow As HtmlWindow
Private Sub nav(uriFile As Uri)
Debug.Print("STARTED")
WebBrowser1.Navigate(uriFile)
End Sub
Private Sub SuppressScriptErrors()
If (WebBrowser1.Document IsNot Nothing) Then
ScriptWindow = WebBrowser1.Document.Window
End If
End Sub
Private Sub ScriptWindow_Error(ByVal sender As Object, ByVal e As HtmlElementErrorEventArgs) Handles ScriptWindow.Error
MessageBox.Show("Suppressed error!")
e.Handled = True
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'*** Change this to your path ***
Dim strAppPath As String = "D:\dev\vbnet\SuppressJavascriptErrors"
Dim uriFile As New Uri("file:///" + strAppPath + "\test.html")
Me.WebBrowser1.ObjectForScripting = New JSRequester(Me)
nav(uriFile)
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Debug.Print("COMPLETED")
End Sub
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
Debug.Print("NAVIGATED")
SuppressScriptErrors()
End Sub
End Class
test.html
<!DOCTYPE html>
<html>
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="X-UA-Compatible" content="IE=8"> <!-- change this to "10" or "edge" it FAILS -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<META HTTP-EQUIV="EXPIRES" CONTENT="0">
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>YouTube Viewer</title>
<link rel="stylesheet" type="text/css" href="ytv.css">
</head>
<body onload="init();">
<script type="text/javascript">
function testme() {
a.args = "hello"
return;
}
function init() {
window.external.log(">>>HELLO DEBUG...");
window.external.send(">>>HELLO SENDER...");
testme();
document.write("<h1>Hello World!</h1>");
}
</script>
</body>
</html>
|
|
|
|
|
Task:
Two windows have been opened.
1. Outlook
2. the Windows Explorer
If you now take a mail from the Outlokk Inbox with the left mouse button, pull it over to the Windows Explorer and release it there over a folder then the mail is stored there as a file under the name e.g. Request.msg
Request is the subject of the mail.
Now the second window should be the application to be developed.
There should be a textbox above in which the mail is dropped.
So far I have the following code:
Private Sub TextBox1_DragOver(ByVal sender As Object, ByVal e As DragEventArgs) Handles TextBox1.DragOver
'erlaubte DropEffects festlegen
If e.Data.GetDataPresent("FileGroupDescriptor") Or e.Data.GetDataPresent("FileDropList") Then
e.Effect = DragDropEffects.All
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub TextBox1_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs) Handles TextBox1.DragDrop
' Drop durchführen
Dim ioStream1 As IO.Stream = DirectCast(e.Data.GetData("FileGroupDescriptor"), IO.Stream)
Dim Array1(CInt(ioStream1.Length)) As Byte 'Array anlegen
ioStream1.Read(Array1, 0, Array1.Length) 'Array füllen
'Build the FileName from the FileGroupDescriptor block.
Dim sFileName As New System.Text.StringBuilder("")
Dim i As Integer = 76 'The FileName starts at position 76 in the FileGroupDescriptor.
While Array1(i) <> 0
sFileName.Append(Convert.ToChar(Array1(i)))
i += 1
End While
ioStream1.Close()
MessageBox.Show(sFileName.ToString) 'der Dateiname wird richtig angezeigt
'Mail Inhalt auslesen
Dim ioStream2 As IO.Stream = DirectCast(e.Data.GetData("FileDropList", True), IO.Stream)
Dim Array2(CInt(ioStream2.Length)) As Byte 'Array anlegen
ioStream2.Read(Array2, 0, Array2.Length) 'Array füllen
End Sub
The file name is displayed correctly but ioStream2 is allways nothing
"FileDropList" is probably the wrong parameter. But which one is the right one?
Microsoft.Office.Interop or
System.Runtime.InteropServices and
Dim objOL As New Microsoft.Office.Interop.Outlook.Application
may not be used because an error message is displayed on the Exchange Server.
How can I read the content of the mail?
Thanks in advance
|
|
|
|
|
There's a sample right here on CodeProject:
Outlook Drag and Drop in C#[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|