Try
If Not MyCache.GetInstance.AzureCacheOn Then
reader = New IO.StreamReader(FilePathUtility.GetInstance.MapPath(objUrl))
Else
request = System.Net.HttpWebRequest.Create(objUrl)
response = DirectCast(request.GetResponse, System.Net.HttpWebResponse)
strm = DirectCast(response.GetResponseStream, IO.Stream)
reader = New IO.StreamReader(strm)
End If
Dim list = New List(Of String)()
Using reader
Dim line As String
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
list.Add(line)
End While
End Using
lines = list.ToArray()
Catch ex As Exception
Throw ex
End Try
Private Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
I have this code snippet which is working fine but now in csv file i need to add some information in first line so i need to skip the first line how I can do that please help screenshot of csv is attached
You can simply use ReadLine once before you start processing the lines:
Using reader
reader.ReadLine())
Dim line As String
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
list.Add(line)
End While
End Using
Call read line before while, also check if the line is not blank and then only go to loop.
This will skip your first line.
Code something like :
Using reader
Dim line As String
// if reader.ReadLine() is not empty
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
list.Add(line)
End While
// end if
End Using
To skip nth line (2nd in your case) use :
Using reader
Dim line As String
// count = 0, n = 1 // 0 = first line, 1 = 2nd line etc
While (InlineAssignHelper(line, reader.ReadLine())) IsNot Nothing
// if(count++ != n)
list.Add(line)
// end if
End While
End Using
Related
I am using the OpenXML library to auto generate Word files. I have a function that takes a group of files and merges them into one document. As I merge a new file into a document, I want each file to start on a new page. But, I don't want to have any blank pages. The code I have mostly works, but an issue comes up is if a file being merged in is a filled page, then a page break is still added, resulting in an empty page being added. I am not sure how to best deal with this, to prevent blank pages from being added. Here is my code:
Public Sub MergeFiles(ByVal filePaths As List(Of String), ByVal fileName As String)
Dim newFile As String = HttpRuntime.AppDomainAppPath & "PDF_Templates\TempFolder\catalog-" & Guid.NewGuid.ToString & ".docx"
File.Copy(fileName, newFile)
Dim counter As Integer = 0
For Each filePath As String In filePaths
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(newFile, True)
Using wordDoc
Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart
Dim altChunkId As String = "altChunkId" & counter
Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId)
Dim fileStream As FileStream = File.Open(filePath, FileMode.Open)
Using fileStream
chunk.FeedData(fileStream)
End Using
Dim AltChunk As AltChunk = New AltChunk()
AltChunk.Id = altChunkId
' Dont add a page break to the first page.
If counter > 0 Then
Dim last As OpenXmlElement = wordDoc.MainDocumentPart.Document.Body.Elements().LastOrDefault(Function(e) TypeOf e Is Paragraph OrElse TypeOf e Is AltChunk)
last.InsertAfterSelf(New Paragraph(New Run(New Break() With {
.Type = BreakValues.Page
})))
End If
mainPart.Document.Body.InsertAfter(Of AltChunk)(AltChunk, mainPart.Document.Body.Elements(Of Paragraph).Last())
mainPart.Document.Save()
wordDoc.Close()
End Using
counter = counter + 1
Next
End Sub
This topic is related to Loop through links and download PDF's
I am trying to convert my current VBA code into VBScript. I have already understood that I have to remove the variable types (As ... part of Dim statements) and use CreatObject to get those objects but otherwise everything should port as-is. DoEvents will also have to be replaced with something like Wscript.sleep.
I came up with some problems. Currently while running VBS file I am getting an error saying "Object required: 'MSHTML'". Pointing to line 65, where I have Set hDoc = MSHTML.HTMLDocument. I have tried to search on Google but got nothing helpful for this one.
How I should proceed with this one?
DownloadFiles("https://www.nordicwater.com/products/waste-water/")
Sub DownloadFiles(p_sURL)
Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim xHttp
Dim hDoc
Dim Anchors
Dim Anchor
Dim sPath
Dim wholeURL
Dim internet
Dim internetdata
Dim internetlink
Dim internetinnerlink
Dim arrLinks
Dim sLink
Dim iLinkCount
Dim iCounter
Dim sLinks
Set internet = CreateObject("InternetExplorer.Application")
internet.Visible = False
internet.navigate (p_sURL)
Do Until internet.ReadyState = 4
Wscript.Sleep 100
Loop
Set internetdata = internet.document
Set internetlink = internetdata.getElementsByTagName("a")
i = 1
For Each internetinnerlink In internetlink
If Left(internetinnerlink, 36) = "https://www.nordicwater.com/product/" Then
If sLinks <> "" Then sLinks = sLinks & vbCrLf
sLinks = sLinks & internetinnerlink.href
i = i + 1
Else
End If
Next
wholeURL = "https://www.nordicwater.com/"
sPath = "C:\temp\"
arrLinks = Split(sLinks, vbCrLf)
iLinkCount = UBound(arrLinks) + 1
For iCounter = 1 To iLinkCount
sLink = arrLinks(iCounter - 1)
'Get the directory listing
xHttp.Open "GET", sLink
xHttp.send
'Wait for the page to load
Do Until xHttp.ReadyState = 4
Wscript.Sleep 100
Loop
'Put the page in an HTML document
Set hDoc = MSHTML.HTMLDocument
hDoc.body.innerHTML = xHttp.responseText
'Loop through the hyperlinks on the directory listing
Set Anchors = hDoc.getElementsByTagName("a")
For Each Anchor In Anchors
'test the pathname to see if it matches your pattern
If Anchor.pathname Like "*.pdf" Then
xHttp.Open "GET", wholeURL & Anchor.pathname, False
xHttp.send
With CreateObject("Adodb.Stream")
.Type = 1
.Open
.write xHttp.responseBody
.SaveToFile sPath & getName(wholeURL & Anchor.pathname), 2 '//overwrite
End With
End If
Next
Next
End Sub
Function:
Function getName(pf)
getName = Split(pf, "/")(UBound(Split(pf, "/")))
End Function
Instead of Set hDoc = MSHTML.HTMLDocument, use:
Set hDoc = CreateObject("htmlfile")
In VBA/VB6 you can specify variable and object types but not with VBScript. You have to use CreateObject (or GetObject: GetObject function) to instantiate objects like MSHTML.HTMLDocument, Microsoft.XMLHTTP, InternetExplorer.Application, etc instead of declaring those using Dim objIE As InternetExplorer.Application for example.
Another change:
If Anchor.pathname Like "*.pdf" Then
can be written using StrComp function:
If StrComp(Right(Anchor.pathname, 4), ".pdf", vbTextCompare) = 0 Then
or using InStr function:
If InStr(Anchor.pathname, ".pdf") > 0 Then
Also, at the beginning of your sub, you do the following:
Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim xHttp
You should declare your variables before assigning them values or objects. In VBScript this is very relaxed, your code will work because VBScript will create undefined variables for you but it's good practice to Dim your variables before using them.
Except for Wscript.sleep commands, your VBScript code will work in VB6/VBA so you can debug your script in VB6 or VBA apps (like Excel).
Dim EAM017 As EAM017_LNG_SI_GetDetails_Out_SyncService.SI_GetDetails_Out_SyncSoapClient
If URL.Contains("http") Then
Dim endPointHttp = New System.ServiceModel.EndpointAddress(URL)
binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly
binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic
EAM017 = New EAM017_LNG_SI_GetDetails_Out_SyncService.SI_GetDetails_Out_SyncSoapClient(binding, endPointHttp)
EAM017.ClientCredentials.UserName.UserName = UserName
EAM017.ClientCredentials.UserName.Password = Password
End If
EAM017.FunctionalLocation(MyMTFuncLocRequest)
Now error is EAM017 has been used before a value is assigned.
The solution is to put it inside the if block but I don't want to do that and should be outside becuase more code is going to be there in future in the same way.
What should I do?
Consider the following
' EAM017 is declared, but not assigned to anything, thus is Nothing / null
Dim EAM017 As EAM017_LNG_SI_GetDetails_Out_SyncService.SI_GetDetails_Out_SyncSoapClient
' your URL doesn't contain http
URL = "ftp://123.456.789.001"
' this condition is false ...
If URL.Contains("http") Then
' ... so this line doesn't happen
EAM017 = New EAM017_LNG_SI_GetDetails_Out_SyncService.SI_GetDetails_Out_SyncSoapClient(binding, endPointHttp)
End If
' EAM017 was never assigned, and is null. A null object exception will happen at runtime
EAM017.FunctionalLocation(MyMTFuncLocRequest)
Now you might say that your URL will always contain "http", then you don't need the If.
But if it's possible it won't contain "http" then you shouldn't be doing anything with a null object. You should either
Add another case (where URL contains "ftp" for example) and assign the object in there accordingly
Move the line EAM017.FunctionalLocation(MyMTFuncLocRequest) inside the If
Move the line EAM017 = New EAM017_LNG_SI_GetDetails_Out_SyncService.SI_GetDetails_Out_SyncSoapClient(binding, endPointHttp) outside the If
You can add a Not to the if statement and exit the sub if the requirements are not met. If they are met then just continue with the rest of he code.
To answer your question in the title. Not all code paths include the initialization of EAM017.
Private Sub OPCode(URL As String)
Dim EAM017 As EAM017_LNG_SI_GetDetails_Out_SyncService.SI_GetDetails_Out_SyncSoapClient
If Not URL.Contains("http") Then
'Notify the user and exit the sub
Return
End If
Dim endPointHttp = New System.ServiceModel.EndpointAddress(URL)
Binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly
Binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Basic
EAM017 = New EAM017_LNG_SI_GetDetails_Out_SyncService.SI_GetDetails_Out_SyncSoapClient(Binding, endPointHttp)
EAM017.ClientCredentials.UserName.UserName = UserName
EAM017.ClientCredentials.UserName.Password = Password
EAM017.FunctionalLocation(MyMTFuncLocRequest)
End Sub
i been given a assignment to create one console application using VB.NET. The assignment will able to open the file that based on the date modified entered by user. can anyone help me to solve my problem. I'm new in vb.net and most of the tutorial are using C# . together i put the latest code i has already done but still if i put the date modified the error file will display .
Thank you in advance
Imports System.IO
Module Module3
Sub Main()
While True
' Read value.
Dim s As DateTime = Console.ReadLine()
' Test the value.
If s = File.GetLastWriteTime("path") Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path")
p.Start()
Else
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", "path2")
p.Start()
End If
' Write the value.
Console.WriteLine("You typed " + s)
End While
End Sub
End Module
in the code snippet you are not searching for a file you are setting the time last modified which isn't what you want to do.
you will need to search through each file until you find the date modified information which is inputted by the user:-
dim s as datetime = console.readline()
'Target Directory
Dim directory = "C:\Users\Peter\Desktop\TestFolder\"
For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
Dim fName As String = IO.Path.GetExtension(filename)
dim datemod as string = File.GetLastWriteTime(directory & fname)
If s = datemod Then
Dim p As New Process()
p.StartInfo = New ProcessStartInfo("notepad.exe", directory & fname)
p.Start()
Else
'do something else
endif
next
things that you will need to add are, what to do when it doesn't find a file with that variable.
hope this gets you a little further.
I have found a function which invokes Microsoft.DirectX.AudioVideoPlayback to get the length of a video file.
Here is that code:
`Private Function GetVideoInformation(ByVal videoFilePath As String) As VideoInfo
Try
If My.Computer.FileSystem.FileExists(videoFilePath) Then
Dim videoToGetInfoOn As Microsoft.DirectX.AudioVideoPlayback.Video
videoToGetInfoOn = New Microsoft.DirectX.AudioVideoPlayback.Video(videoFilePath)
Dim atpf As Double = videoToGetInfoOn.AverageTimePerFrame
Dim vidSize As New Size
vidSize = videoToGetInfoOn.Size
Dim thisVideoInfo As New VideoInfo
thisVideoInfo.videoWidth = vidSize.Width
thisVideoInfo.videoHeight = vidSize.Height
thisVideoInfo.videoDuration = videoToGetInfoOn.Duration
If videoToGetInfoOn.Duration > 0 Then
defaultLength = videoToGetInfoOn.Duration
End If
If atpf > 0 Then
thisVideoInfo.videoFps = 1 / atpf
Else
thisVideoInfo.videoFps = 0
End If
Return thisVideoInfo
Else
Throw New Exception("Video File Not Found" & vbCrLf & vbCrLf & videoFilePath)
Return Nothing
End If
Catch ex as Exception
msgbox(ex.message)
End Try
End Function`
I have a timer that calls this function once on 2 seconds to check many videos, and the app works fine for the first 10 videos or so. After that, it throws
"Error in application"
message instead.
In general, things from DirectShow/DirectX MUST be disposed of in the way the docs require or this sort of thing happens. Here, you are creating videoToGetInfoOn objects but never releasing them.
You need to explicitly release all the resources you and it allocated with videoToGetInfoOn = Nothing before your procedure exits. Try that.
I will add that MediaInfo.DLL can be used to get everything from a media file without the overhead of Dx. There is a commandline version that you might be able to read from reading stdout.
I got it working.
The code needs a dispose method.
Here is the final code:
`Private Function GetVideoInformation(ByVal videoFilePath As String) As VideoInfo
Try
If My.Computer.FileSystem.FileExists(videoFilePath) Then
Dim videoToGetInfoOn As Microsoft.DirectX.AudioVideoPlayback.Video
videoToGetInfoOn = New Microsoft.DirectX.AudioVideoPlayback.Video(videoFilePath)
Dim atpf As Double = videoToGetInfoOn.AverageTimePerFrame
Dim vidSize As New Size
vidSize = videoToGetInfoOn.Size
Dim thisVideoInfo As New VideoInfo
thisVideoInfo.videoWidth = vidSize.Width
thisVideoInfo.videoHeight = vidSize.Height
thisVideoInfo.videoDuration = videoToGetInfoOn.Duration
If videoToGetInfoOn.Duration > 0 Then
defaultLength = videoToGetInfoOn.Duration
End If
If atpf > 0 Then
thisVideoInfo.videoFps = 1 / atpf
Else
thisVideoInfo.videoFps = 0
End If
videoToGetInfoOn.Dispose() 'this line here needed to be added
Return thisVideoInfo
Else
Throw New Exception("Video File Not Found" & vbCrLf & vbCrLf & videoFilePath)
Return Nothing
End If
Catch ex as Exception
msgbox(ex.message)
End Try
End Function`