VB Script for Automating File Creation (On-Demand Opportunity!) - vbscript

I'm a Financial person and not quite the VB scripting guru, but I'm wondering if someone could create a sample vb script based on my requirements.
Whoever provides the solution first and the solution works on my end will have an opportunity (paid of course) to create more of these custom solutions where I work at. It wouldn't be full-time position, but more of an On-Demand opportunity.
Requirements:
To be able to read a text file that is delimited by comma and has various entries
For example, in text file...
SEC_E_All_Entities,HSII,SL_DIMENSION,READWRITE,#IDESCENDANTS,N
SEC_E_ENT_Americas,Americas,SL_DIMENSION,READ,MEMBER,N
And perform the following...
Create an XML file per entry, based on the first value
For example:
Create SEC_E_All_Entities.XML and SEC_E_ENT_Americas.XML
Within each file, write the contents where you can see how the values match each tag.
For example:
In the SEC_E_All_Entities.XML file, write...
<?xml version="1.0" encoding="UTF-8" ?>
<acls>
<acl>
<name>SEC_E_All_Entities</name>
<objectName>HSII</objectName>
<objectType>SL_DIMENSION</objectType>
<accessMode>READWRITE</accessMode>
<flag>#IDESCENDANTS</flag>
<isUser>N</isUser>
</acl>
</acls>
In the SEC_E_All_Americas.XML file, write...
<?xml version="1.0" encoding="UTF-8" ?>
<acls>
<acl>
<name>SEC_E_ENT_Americas</name>
<objectName>Americas</objectName>
<objectType>SL_DIMENSION</objectType>
<accessMode>READ</accessMode>
<flag>MEMBER</flag>
<isUser>N</isUser>
</acl>
</acls>
Regards,
Judy

Sample script
'Step 1 - Read the file and store the content in memory (an array)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\pankaj.jaju\Desktop\StackOverflow\acls.txt", 1)
arrFile = Split(objFile.ReadAll, vbCrLf) 'will store one line in each array index
objFile.Close
'Step 2 - Load the XML template in memory
Set xmlTemplate = CreateObject("MSXML2.DOMDocument.6.0")
With xmlTemplate
.ValidateOnParse = True
.Async = False
.LoadXML "<?xml version=""1.0"" encoding=""UTF-8"" ?>" & _
"<acls>" & _
"<acl>" & _
"<name></name>" & _
"<objectName></objectName>" & _
"<objectType></objectType>" & _
"<accessMode></accessMode>" & _
"<flag></flag>" & _
"<isUser></isUser>" & _
"</acl>" & _
"</acls>"
End With
'Step 3 - Load the relevant fields for which the data is to be set from csv file
Set nodeFields = xmlTemplate.DocumentElement.SelectNodes("/acls/acl/*")
'Step 4 - Read each line of text and create XML
For i = LBound(arrFile) To UBound(arrFile)
arrLine = Split(arrFile(i), ",") 'will split the line into various fields (to be used to create the xml)
For j = LBound(arrLine) To UBound(arrLine) 'set values for each field
nodeFields(j).Text = arrLine(j)
Next
Set xmlNew = xmlTemplate
xmlNew.Save objFSO.BuildPath("C:\Users\pankaj.jaju\Desktop\StackOverflow\", nodeFields(0).Text & ".xml") 'copy modified template as new xml file
Set xmlNew = Nothing
Next

Related

VBScript to copy/move file by lowest value in filename

I'm fairly new to scripting and am in need of some help. I have come across a unique situation for a Non-Profit client of ours that requires us to compare two or more files in a specific folder and move the file with the lowest numerical value in the filename.
This organization runs a non-profit radio station which has content submitted from hundreds of volunteers that name their files (when they record more than one) with various numbers at the end that either represent the date or the order in which the files are to be aired.
Essentially I am looking to create a vbscript (because I think it can be done this way) that will run with windows task scheduler 30 minutes prior to the first air date of the content and move the file with the lowest value (if more than one file exists) to a folder where it will be automatically processed by the radio automation software.
Examples of files in a folder might look something like these:
Folder1: (in this instance, "news.mp3" is the lowest value)
news.mp3
news1.mp3
news2.mp3
Folder2:
entertainment24.mp3
entertainment26.mp3
Folder3:
localnews081420.mp3
localnews081520.mp3
Honestly, on this one, I'm not even sure where to start. I've found several scripts that can look at file date or a specific numerical or date format in the filename, but none that can parse numbers from a filename and move/copy a file based on the numerical value. I'm hoping there is someone out there smarter than me that can point me in the right direction. Thanks for looking at my problem!
One script I've been playing with (from the scripting guy) looks at specific years in a filename:
strComputer = “.”
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
Set colFiles = objWMIService.ExecQuery _
(“ASSOCIATORS OF {Win32_Directory.Name=’C:\Test’} Where ” _
& “ResultClass = CIM_DataFile”)
Set objRegEx = CreateObject(“VBScript.RegExp”)
For Each objFile in colFiles
objRegEx.Global = True
objRegEx.Pattern = “\d{4}”
strSearchString = objFile.FileName
Set colMatches = objRegEx.Execute(strSearchString)
strYear = colMatches(0).Value
strNewFile = “C:\Test\” & strYear & “\” & objFile.FileName & _
“.” & objFile.Extension
objFile.Copy(strNewFile)
objFile.Delete
Next
...but I can't seem to make the leap to regular numbers and then take a lowest value...
You can use FileSystemObject to Work with Drives, Folders and Files.
Also i used GETNUM function to get number.
Try my way :
sFolder = "C:\Test\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile in oFSO.GetFolder(sFolder).Files
Number=GETNUM(objFile.Name)
strNewFile = sFolder & Number & "\" & objFile.Name
If NOT (oFSO.FolderExists(sFolder & Number)) Then
oFSO.CreateFolder(sFolder & Number)
End If
oFSO.MoveFile objFile, strNewFile
Next
Function GETNUM(Str)
For i=1 To Len(Str)
if IsNumeric(Mid(Str,i,1)) Then
Num=Num&Mid(Str,i,1)
End if
Next
GETNUM=Num
End Function
For understanding the used code and how they work, open these sites and read all pages very carefully.
MoveFile method
Vbs Script to check if a folder exist

Visual Basic Compare Files Task

I currently have this code that will compare between two files only if each file has one column:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFSO.OpenTextFile("C:\Users\Downloads\Define Kickouts\Metadata_Account.txt", ForReading)
strCurrentDevices = objFile1.ReadAll
objFile1.Close
Set objFile2 = objFSO.OpenTextFile("C:\Users\Downloads\Define Kickouts\DataFile_Account.txt", ForReading)
Do Until objFile2.AtEndOfStream
strAddress = objFile2.ReadLine
If InStr(strCurrentDevices, strAddress) = 0 Then
strNotCurrent = strNotCurrent & strAddress & vbCrLf
End If
Loop
objFile2.Close
Wscript.Echo "Addresses without current devices: " & vbCrLf & strNotCurrent
Set objFile3 = objFSO.CreateTextFile("C:\Users\Downloads\Define Kickouts\Differences.txt")
objFile3.WriteLine strNotCurrent
objFile3.Close
However, I'm trying to figure out a way to create the script where the user can define which columns in the date file to compare against the same set of metadata files.
For example, in the data file, if we want to compare Account, Entity, and Department members, in the script, we would type in columns 1, 4, 5 based on the position in the headers...
Account, Project, Practice, Entity, Department
GL1000,P5000,PP2000,USA,D120
GL2000,P6000,PP3000,CANADA,D220
Then, the script will compare 'always' against the first column in each metadata file...
Account.csv
First column sample values:
GL5000,blah,blah,blah
GL1000,blah,blah,blah
Entity.csv
First column sample values:
ASIA,blah,blah,blah
CANADA,blah,blah,blah
Department.csv
First column sample values:
D100,blah,blah,blah
D200,blah,blah,blah
The output file will have kick-outs from the data file that aren't in the metadata files for each column.
Account Kickout.txt
GL2000
Entity Kickout.txt
USA
Department Kickout.txt
D120
D220
Any help would be appreciated!

VBS Readline - using instr(), to match data whilst ignoring extra spaces

I'm trying to find a way to enhance the reliability of my script. It already works but can be thrown off with a simple extra space in the imported text file.
So I'd like to change my script to Readline if I can find a way to do something like:
Example of text in the .txt file:
FLIGHTS OVER TUSKY PLEASE FILE:
AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT
FLIGHTS OVER EBONY PLEASE FILE:
AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT
I know the following doesn't work but if there was a simple modification this would be good.
set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\Downloads\software\putty.exe -load "testing")
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
strLine = objFile.ReadAll
If InStr(strLine1, "OVER TUSKY PLEASE") and InStr(strLine2, "BAYYS..PUT..DIRECT") Then
trans307="TUSKY"
ind306="4"
WHAT I'M USING NOW:
I edit the text file in notepad++ to FIND & REPLACE "\n" with "" and "\r" with " " and then it's all one text string and I search for strings within that string.
If InStr(strLine, "FLIGHTS OVER TUSKY PLEASE FILE: AT OR WEST OF A LINE ..RBV..LLUND..BAYYS..PUT..DIRECT") _
or InStr(strLine, "FLIGHTS OVER TUSKY PLEASE FILE: AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT...DIRECT") Then
trans308C="TUSKY"
ind308C="4"
Problem: If the creators of the text file put another space " " anywhere in this line "AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT" the script will not identify the string. In the above example I have had to create another or InStr(strLine, "") statement with an extra space or with a couple of dots.
UPDATE:
I will try something like:
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
strLine1 = objFile.Readline(1)
strLine2 = objFile.Readline(2)
If InStr(strLine1, "FLIGHTS OVER TUSKY") and InStr(strLine2, "RBV..LLUND..BAYYS..PUT..DIRECT") Then
trans1="TUSKY"
ind1="4"
and see if I can get that to read 2 lines at a time, and loop through the text file.
If you're scared of regex and looking for an alternative, you could create a clunky function to add to your script. Based on your samples, it would seem that fullstops are also never normally used for normal purposes and tend to represent spaces. (I would recommend using Regex instead!)
Using these presumptions, you could create a clunky function like this, that looks for fullstops, and converts them to spaces, removing extra spaces.. Obviously, this relies heavily on your input source files not changing too much - you really should be using a regex to work this stuff out properly.
You could test for the basic expected results using something like the function below.
For example say you had a line of text set in firLine with multiple spaces or fullstops, the function would recognize this:
firLine = "THIS.IS.A.TEST..YOU...SEE MULTIPLE SPACES"
if instr(sanitize(firLine),"THIS IS A TEST YOU SEE MULTIPLE SPACES") then
wscript.echo "Found it"
End If
Here's the clunky function that you could just paste at the end of your script:
Function sanitize(srStr)
Dim preSanitize, srC, spaceMarker
preSanitize = ""
for srC = 1 to len(srStr)
if mid(srStr, srC, 1) = "." then
preSanitize = preSanitize & " "
else
preSanitize = preSanitize & mid(srStr, srC, 1)
End If
spaceMarker = false
sanitize = ""
for srC = 1 to len(preSanitize)
If mid(preSanitize, srC, 1) = " " then
if spaceMarker = false then
sanitize = sanitize & mid(preSanitize, srC, 1)
spaceMarker = true
End If
else
sanitize = sanitize & mid(preSanitize, srC, 1)
spaceMarker = false
End If
Next
End Function
InStr() is a good tool for checking whether a strings contains a fixed/literal string or not. To allow for variation, you should use Regular Expressions (see this or that).
First of all, however, you should work on your specs. Describe in plain words and with some samples what you consider (not) to be a match.
E.g.: A string containing the words "FLIGHTS", "OVER", and "TUSKY" in that order with at least one space in between is a match - "FLIGHTS OVER TUSKY", "FLIGHTS OVER TUSKY"; "FLIGHTS OVER TUSKANY" is a 'near miss' - what about "AIRFLIGHTS OVER TUSKY"?
GREAT NEWS! I finally figured out how to do this.
Here is a snippet from "Entries1.txt"
FLIGHTS OVER BRADD KANNI PLEASE FILE:
VIA J174.RIFLE..ACK..DIRECT
OR RBV.J62.ACK..DIRECT
FLIGHTS OVER KANNI WHALE PLEASE FILE:
VIA J174.RIFLE..ACK..DIRECT OR
FLIGHTS OVER WHALE PLEASE FILE:"
ETC, ETC
set WshShell = WScript.CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
Do until objFile.AtEndOfStream
firLine = objFile.ReadLine
If InStr(firLine, "FLIGHTS OVER KANNI WHALE PLEASE") Then
secLine = objFile.ReadLine
If InStr(secLine, "J174.RIFLE..ACK..DIRECT") Then
'I'm going to change the below once I piece it all together.
WScript.Echo "works"
Else WScript.Echo "Not found"
'cut, paste and modify all my "IF" statements below
End If
End If
loop

CrystalReports DataTable Error VB.NET

I'm trying to pass all data from a DB to a report: but I get an error (The report has no tables)
Dim sqlConn As String = "SELECT (SUM(item_selldetail * item_quantity )/ 100 * 12) AS isv_report," & _
" (SUM( item_selldetail * item_quantity ) - (SUM(item_selldetail * item_quantity )/ 100 * 12)) " & _
" AS capital_report,SUM( item_selldetail * item_quantity ) AS total_report FROM qa_items;"
Dim objDataAdapter As New MySqlDataAdapter(sqlConn, objConn)
' DataSet
Dim ds As New DataSet
' llenar el DataSet
objDataAdapter.Fill(ds)
Dim mireporte As New ReportDocument()
mireporte.Load("C:\Users\Jonathan\Desktop\Proyectos\Quickadmon\Quickadmon\Reportes\report_capital_rpt.rpt")
mireporte.SetDataSource(ds)
Me.capitalreport_viewer_capital_report.ReportSource = mireporte
Anyone have any idea what I can do?
Sample code here , try to dolike this
sql = "SELECT Product_id,Product_name,Product_price FROM Product"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet1
dscmd.Fill(ds, "Product")
cnn.Close()
Dim objRpt As New CrystalReport1
objRpt.SetDataSource(ds.Tables(1))
CrystalReportViewer1.ReportSource = objRpt
CrystalReportViewer1.Refresh()
If you need full source code :
http://vb.net-informations.com/crystal-report/crystal_report_from_sql_query_string.htm
merca.
Here's what I've done in the past.
1.) Create an ADO.NET (XML) Connection in Crystal. You will need to provide a path to an XML file to do this, the XML file will include the DataTable (or DataReader's) schema. It would look something like this (the x0020 represents a space in a field if you have one, see http://www.blakepell.com/Blog/?p=14 for more details on that):
<?xml version="1.0" encoding="utf-8" ?>
<people>
<first_x0020_name>
<last_x0020_name>
<phone>
</people>
2.) Set your data source like you did, in my wrapper code I had something like this where I was setting it from properties on the wrapper:
If _dataReader IsNot Nothing Then
report.SetDataSource(_dataReader)
End If
If _dataTable IsNot Nothing Then
report.SetDataSource(_dataTable)
End If
3.) Put it in your viewer control (or export it which is usually what I do since I'm generating the PDF output from it).
report.Export()
If this doesn't work for you, then post the specific stack trace and exception that you receive whenever you do this so we can troubleshoot it better. ;)

how to make ascii file for accounting software with vbscript and ASP

i need to have an ascii file that have several lines in it for accounting.
in everyline i will have the text and numbers for example numbers and spaces with specific length for every column of data
first column is 3 char length
second is 5
third is 10 and etc...
then i need the end of the line to end with CR + LF
how do i do an ascii file from classic asp and vbscript?
You use FSO (FileSystemObject) to work with files in VBScript. This MSDN Page, Working with Files, shows you how to create and write to files.
Here's a page that has a sample that uses VBScript in an ASP page to create a text file.
My guess, you need to manage a text file like a database. If I'm right, you can do it using Text File Driver.
You need a schema.ini file for the data construct configuration and an existing text file (myfile.csv).
schema.ini
[myfile.csv]
Format=FixedLength
CharacterSet=ANSI
ColNameHeader=False
Col1=first Text Width 3
Col2=second Text Width 5
Col3=third Text Width 10
;[myotherfile.csv]
;Format=FixedLength
;CharacterSet=ANSI
; etc.
myfile.csv (maybe not certain but there are three columns per line with the above configuration.)
abcdefghijklmnopqrstu
123123451234567890
Things to do side of ASP are like classical database operations also.
Const adLockReadOnly = 1
Dim adoCon, adoRS
Set adoCon = Server.CreateObject("Adodb.Connection")
adoCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& Server.Mappath(".") & _
";Extended Properties=""text"""
Set adoRS = Server.CreateObject("Adodb.Recordset")
With adoRS
.Open "Select * From [myfile.csv]", adoCon, , adLockReadOnly
While Not .Eof
Response.Write( _
.Fields("first").Value & " - "& _
.Fields("second").Value & " - "& _
.Fields("third").Value & _
"<br />")
.MoveNext
Wend
.Close
End With
Set adoRS = Nothing
'Data insert : new line ends with CR + LF automatically.
adoCon.Execute "Insert Into [myfile.csv] Values('aaa','bbbbb','cccccccccc')"
adoCon.Close
Set adoCon = Nothing

Resources