I want to create a script that shows the files created on a specific date in a specific location.
As for now I created this:
Set objWMIService = GetObject("winmgmts:" & "!\\" & "." & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery ("Select * from CIM_DataFile where Drive='C:' AND Path='\\' AND CreationDate Like '20071107%' ")
For Each objFile in colFiles
Buffer = Buffer & objFile.FileName & " - " & objFile.CreationDate & vbNewLine
Next
Wscript.echo Buffer
But I am getting error in this line: " AND CreationDate Like '20071107%' "
So it does not work in such a way as I thought it will be - in C:\ I have a lot eula.txt files created on 2007 11 07.
I do not ask about finished code, but only for a clue. Thanks!
WHERE clause of a WQL query defends or inhibits from using wildcards in CIM_DATETIME values. Use SWbemDateTime object as follows:
option explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim objWMIService, colFiles, objFile, dTargetDate, dMinDate, dMaxDate, dateTime
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dTargetDate = #2007-11-07# ' date literal in yyyy-mm-dd format
dateTime.SetVarDate( dTargetDate) ' convert to CIM_DATETIME
dMinDate = datetime
dateTime.SetVarDate( DateAdd( "d", 1, dTargetDate))
dMaxDate = datetime
strResult = strResult & vbNewLine & dMaxDate
Set objWMIService = GetObject("winmgmts:" & "!\\" & "." & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery ( _
"Select * from CIM_DataFile where Drive='c:' AND Path='\\'" _
& " AND CreationDate >= '" & dMinDate & "'" _
& " AND CreationDate < '" & dMaxDate & "'" _
)
If colFiles.Count = 0 Then
strResult = strResult & vbNewLine & "no files found"
Else
For Each objFile in colFiles
strResult = strResult & vbNewLine & objFile.FileName & " " & objFile.Extension _
& " - " & objFile.CreationDate
Next
End If
Wscript.Echo strResult
Wscript.Quit
I'm writing this script to help with logging when my workplace re-images computers. The problem is that I am somewhat inexperienced with VBS and troubleshooting VBS scripts.
This script is built to take in an argument and log the section indicated by the argument. Ex: Someone passes in /1 and then the script logs section 1.
Here is the full script(with some elements redacted).
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Dim strDriveLetter, strRemotePath, strusername, strpassword, strRemoteNewPath
WScript.sleep 5000
Dim iRetVal
Dim sCmd
Dim begImg, begDrivers, begAppInstalls, finalCheck, finalConfig, complete
set begImg = WScript.Arguments
set begDrivers = WScript.Arguments
set begAppInstalls = WScript.Arguments
set finalCheck = WScript.Arguments
set finalConfig = WScript.Arguments
set complete = WScript.Arguments
'my solution
set sequence = Wscript.Arguments
sCmd = "Net use L: /del"
iRetVal = WshShell.Run(sCmd, 0, true)
strDriveLetter = "L:"
strRemotePath = "\\FileServ1\LogShare"
strRemoteNewPath = "\\FileServ1\LogShare"
strusername = "domain\admin"
strpassword = "password"
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, , strusername, strpassword
'|------------------------------------|
'| Get Serial Number |
'| Variable objSN = Machine Serial # |
'|------------------------------------|
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colBIOS = objWMIService.ExecQuery _
("Select * from Win32_BIOS")
For each objBIOS in colBIOS
objSN = objBIOS.SerialNumber
Next
' This appears to be the first part 1
'|--------------------------------------|
'| Create Text File with Machine S/N |
'|--------------------------------------|
'8 is ForAppending
If sequence = 1 Then
Set trs = objFSO.OpenTextFile(strDriveLetter & "\" & objSN & ".txt", 8, True)
trs.WriteLine ""
trs.WriteLine "*************************************************************************"
trs.WriteLine(Now & " BEGINNING IMAGING SESSION ON: " & objSN)
trs.WriteLine(Now & " mapped " & strRemotePath & " as " & strDriveLetter)
trs.WriteLine(Now & " Beginning to apply image...")
trs.WriteLine ""
End If
If Err.Number <> 0 Then
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
trs.WriteLine(Now & ": Error: " & Err.Number )
trs.WriteLine(Now & ": Error (Hex): " & Hex(Err.Number ))
trs.WriteLine(Now & ": Source: " & Err.Source )
trs.WriteLine(Now & ": Description: " & Err.Description )
Err.Clear
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
End If
' Part 2
'|--------------------------------------|
'| BEGIN DRIVER AND WINDOWS UPDATES |
'|--------------------------------------|
If sequence = 2 Then
trs.WriteLine(Now & " IMAGE APPLIED; BEGINNING DRIVERS AND WINDOWS UPDATES...")
trs.WriteLine ""
End If
If Err.Number <> 0 Then
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
trs.WriteLine(Now & ": Error: " & Err.Number )
trs.WriteLine(Now & ": Error (Hex): " & Hex(Err.Number ))
trs.WriteLine(Now & ": Source: " & Err.Source )
trs.WriteLine(Now & ": Description: " & Err.Description )
Err.Clear
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
End If
'Part 3
'|----------------------------------------------------------|
'| APPLY UPDATES AND DRIVERS, GO TO APPLICATION INSTALLS |
'|----------------------------------------------------------|
If sequence = 3 Then
trs.WriteLine(Now & " INITIAL UPDATES AND DRIVERS APPLIED; PROCEEDING TO APPLICATION INSTALLS...")
End If
If Err.Number <> 0 Then
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
trs.WriteLine(Now & ": Error: " & Err.Number )
trs.WriteLine(Now & ": Error (Hex): " & Hex(Err.Number ))
trs.WriteLine(Now & ": Source: " & Err.Source )
trs.WriteLine(Now & ": Description: " & Err.Description )
Err.Clear
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
End If
'Part 4
'|--------------------------------------|
'| STARTING FINAL CHECKS |
'|--------------------------------------|
If sequence = 4 Then
trs.WriteLine(Now & " APPLICATIONS COMPLETE; STARTING FINAL CHECK FOR UPDATES...")
trs.WriteLine ""
End If
If Err.Number <> 0 Then
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
trs.WriteLine(Now & ": Error: " & Err.Number )
trs.WriteLine(Now & ": Error (Hex): " & Hex(Err.Number ))
trs.WriteLine(Now & ": Source: " & Err.Source )
trs.WriteLine(Now & ": Description: " & Err.Description )
Err.Clear
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
End If
'Part 5
'|--------------------------------------|
'| FINAL CONFIGURATIONS |
'|--------------------------------------|
'8 is ForAppending
'Set trs = objFSO.OpenTextFile(strDriveLetter & "\" & objSN & ".txt", 8, True) - I might need to delete this to make sure its on the same txt file
If sequence = 5 Then
trs.WriteLine(Now & " UPDATES COMPLETE; PROCEEDING TO FINAL CONFIGURATIONS...")
trs.WriteLine ""
End If
If Err.Number <> 0 Then
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
trs.WriteLine(Now & ": Error: " & Err.Number )
trs.WriteLine(Now & ": Error (Hex): " & Hex(Err.Number ))
trs.WriteLine(Now & ": Source: " & Err.Source )
trs.WriteLine(Now & ": Description: " & Err.Description )
Err.Clear
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
End If
'Part 6
'this should be the final part
'|--------------------------------------|
'| IMAGING SESSION COMPLETE |
'|--------------------------------------|
If sequence = 6 Then
trs.WriteLine(Now & " FINAL CONFIGURATION COMPLETE; IMAGING SESSION COMPLETE...")
trs.WriteLine "*************************************************************************"
'Use netbeans to remove the following 4 spaces if necessary
trs.WriteLine ""
trs.WriteLine ""
trs.WriteLine ""
trs.WriteLine ""
End If
If Err.Number <> 0 Then
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
trs.WriteLine(Now & ": Error: " & Err.Number )
trs.WriteLine(Now & ": Error (Hex): " & Hex(Err.Number ))
trs.WriteLine(Now & ": Source: " & Err.Source )
trs.WriteLine(Now & ": Description: " & Err.Description )
Err.Clear
trs.WriteLine("<<<<<<<<<<<<<<<<<<<<<----------ERROR---------->>>>>>>>>>>>>>>>>>>>>")
End If
trs.close
wscript.quit
Here is my input: cscript OneScriptRuleThemAll.vbs /1
Here is the output and error message: OneScriptToRuleThemAll.vbs(55, 1) Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment
From what I can tell I am not putting in the wrong number of arguments and I don't see the problem with my property assignments.
Any and all help would be appreciated.
I believe the error is occurring on the line If sequence = 1 Then For your intent to work, you need to change it to If sequence.Item(0) = 1 Then
Your arguments can continue to go from 1 to 6.
It looks to me that the if statements are not being used to take the input of the parameters properly. Why is there an error check after each if? it seems like it could just be one big if statement.
Your arguments are a collection so are in the form
Set Arg = WScript.Arguments
If LCase(Arg(0)) = "menu" or LCase(Arg(0)) = "m" then
ShowMenu
...
1st is 0, 2nd is 1, etc
I have this vbscript that works well on Windows 7 32-bit without proxy
In order to improve it, I seek for this solution: How to test internet connection behind a proxy ?
The solution perhaps it will be in VBScript or Powershell or Batch, much as I find a way to check whether i am connected or not behind a proxy !
The piece of code to improve it when i'm behind a proxy
If there is a trick to check if i'm connected to internet when i'm behind a proxy this is my question ?
If CheckConnection = true then
Msgbox "i'm connected to internet",vbinformation+vbSystemModal,"Check connection to internet"
Else
Msgbox "i'm not connected to internet",vbCritical+vbSystemModal,"Check connection to internet"
End if
'***************************************************************************
Function CheckConnection()
CheckConnection = False
strComputer = "smtp.gmail.com"
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
("select * from Win32_PingStatus where address = '" & strComputer & "'")
For Each objStatus in objPing
If objStatus.Statuscode = 0 Then
MyLoop = False
CheckConnection = True
Exit Function
End If
Next
End Function
'******************************************************************************
The hole code :
Option Explicit
Dim Title,MyScriptPath,DJBuzzRadio,MyLoop,strComputer,objPing,objStatus,FSO,FolderScript,URLICON,Icon
Title = "Radio DJ Buzz Live by © Hackoo © 2015"
MyScriptPath = WScript.ScriptFullName
Set FSO = Createobject("Scripting.FileSystemObject")
FolderScript = FSO.GetParentFolderName(MyScriptPath) 'Chemin du dossier ou se localise le Vbscript
Icon = FolderScript & "\akg.ico"
URLICON = ChrW(104)&ChrW(116)&ChrW(116)&ChrW(112)&ChrW(58)&ChrW(47)&ChrW(47)&ChrW(104)&ChrW(97)&ChrW(99)&ChrW(107)&ChrW(111)&ChrW(111)&ChrW(46)&ChrW(97)&ChrW(108)&ChrW(119)&ChrW(97)&ChrW(121)&ChrW(115)&ChrW(100)&ChrW(97)&ChrW(116)&ChrW(97)&ChrW(46)&ChrW(110)&ChrW(101)&ChrW(116)&ChrW(47)&ChrW(97)&ChrW(107)&ChrW(103)&ChrW(46)&ChrW(105)&ChrW(99)&ChrW(111)
If Not FSO.FileExists(Icon) Then Call Download(URLICON,Icon)
DJBuzzRadio = ChrW(104)&ChrW(116)&ChrW(116)&ChrW(112)&ChrW(58)&ChrW(47)&ChrW(47)&ChrW(119)&ChrW(119)&ChrW(119)&ChrW(46)&ChrW(99)&ChrW(104)&ChrW(111)&ChrW(99)&ChrW(114)&ChrW(97)&ChrW(100)&ChrW(105)&ChrW(111)&ChrW(115)&ChrW(46)&ChrW(99)&ChrW(104)&ChrW(47)&ChrW(100)&ChrW(106)&ChrW(98)&ChrW(117)&ChrW(122)&ChrW(122)&ChrW(114)&ChrW(97)&ChrW(100)&ChrW(105)&ChrW(111)&ChrW(95)&ChrW(119)&ChrW(105)&ChrW(110)&ChrW(100)&ChrW(111)&ChrW(119)&ChrW(115)&ChrW(46)&ChrW(109)&ChrW(112)&ChrW(51)&ChrW(46)&ChrW(97)&ChrW(115)&ChrW(120)
Call Shortcut(MyScriptPath,"DJ Buzz Radio")
MyLoop = True
If CheckConnection = True Then Call AskQuestion()
'***************************************************************************
Function CheckConnection()
CheckConnection = False
While MyLoop = True
strComputer = "smtp.gmail.com"
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
("select * from Win32_PingStatus where address = '" & strComputer & "'")
For Each objStatus in objPing
If objStatus.Statuscode = 0 Then
MyLoop = False
CheckConnection = True
Exit Function
End If
Next
Pause(10) 'To sleep for 10 secondes
Wend
End Function
'***************************************************************************
Sub Play(URL)
Dim Sound
Set Sound = CreateObject("WMPlayer.OCX")
Sound.URL = URL
Sound.settings.volume = 100
Sound.Controls.play
do while Sound.currentmedia.duration = 0
wscript.sleep 100
loop
wscript.sleep (int(Sound.currentmedia.duration)+1)*1000
End Sub
'***************************************************************************
Sub Shortcut(CheminApplication,Nom)
Dim objShell,fso,DesktopPath,objShortCut,MyTab,strCurDir
Set objShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
strCurDir = fso.GetParentFolderName(WScript.ScriptFullName)
MyTab = Split(CheminApplication,"\")
If Nom = "" Then
Nom = MyTab(UBound(MyTab))
End if
DesktopPath = objShell.SpecialFolders("Desktop")
Set objShortCut = objShell.CreateShortcut(DesktopPath & "\" & Nom & ".lnk")
objShortCut.TargetPath = Dblquote(CheminApplication)
ObjShortCut.IconLocation = strCurDir & "\akg.ico"
objShortCut.Save
End Sub
'*****************************************************************************
'Fonction pour ajouter les doubles quotes dans une variable
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************************************************
Function AppPrevInstance()
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptFullName) & _
" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")
AppPrevInstance = (.Count > 1)
End With
End With
End Function
'******************************************************************************
Function CommandLineLike(ProcessPath)
ProcessPath = Replace(ProcessPath, "\", "\\")
CommandLineLike = "'%" & ProcessPath & "%'"
End Function
'******************************************************************************
Sub Pause(NSeconds)
Wscript.Sleep(NSeconds*1000)
End Sub
'******************************************************************************
Sub AskQuestion()
Dim Question,MsgAR,MsgFR,MsgEN
MsgFR = "Voulez-vous écouter DJ Buzz Radio en direct ?" & vbcr & "Oui = Pour écouter" & vbcr & "Non = Pour arrêter" & vbcr & String(50,"*")
MsgEN = "Did you want to listen to the Radio DJ Buzz Live ?" & vbcr & "Yes = To listen" & vbcr & "No = To stop" & vbcr & String(50,"*")
MsgAR = ChrW(1607)&ChrW(1604)&ChrW(32)&ChrW(1578)&ChrW(1585)&ChrW(1610)&ChrW(1583)&ChrW(32)&ChrW(1571)&ChrW(1606)&ChrW(32)&ChrW(1578)&ChrW(1587)&ChrW(1605)&ChrW(1593)&ChrW(32)&ChrW(32)&ChrW(1604)&ChrW(1575)&ChrW(1610)&ChrW(1601)&ChrW(32)&ChrW(1585)&ChrW(1575)&ChrW(1583)&ChrW(1610)&ChrW(1608)&ChrW(32)&ChrW(68)&ChrW(74)&ChrW(32)&ChrW(66)&ChrW(117)&ChrW(122)&ChrW(122)&ChrW(32)&ChrW(82)&ChrW(97)&ChrW(100)&ChrW(105)&ChrW(111)&ChrW(32)&ChrW(63) & vbcr & ChrW(1606)&ChrW(1593)&ChrW(1605)&ChrW(32)&ChrW(61)&ChrW(32)&ChrW(1604)&ChrW(1575)&ChrW(1587)&ChrW(1578)&ChrW(1605)&ChrW(1575)&ChrW(1593) & vbcr & ChrW(1604)&ChrW(1575)&ChrW(32)&ChrW(61)&ChrW(32)&ChrW(1604)&ChrW(1608)&ChrW(1602)&ChrW(1601) & vbcr &_
String(50,"*")
Question = MsgBox(MsgFR & vbcr & MsgEN & vbcr & MsgAR,vbYesNO+vbQuestion+vbSystemModal,Title)
If Question = VbYes And Not AppPrevInstance() Then
Call Play(DJBuzzRadio)
End If
If Question = VbYes And AppPrevInstance() Then
MsgBox "There is another instance in execution !" & VbCrLF &_
"Il y a une autre instance en cours d'exécution !"& VbcrLF &_
ChrW(1607)&ChrW(1606)&ChrW(1575)&ChrW(1603)&ChrW(32)&ChrW(1605)&ChrW(1579)&ChrW(1575)&ChrW(1604)&ChrW(32)&ChrW(1570)&ChrW(1582)&ChrW(1585)&ChrW(32)&ChrW(1601)&ChrW(1610)&ChrW(32)&ChrW(1575)&ChrW(1604)&ChrW(1578)&ChrW(1606)&ChrW(1601)&ChrW(1610)&ChrW(1584)& VbcrLF &_
CommandLineLike(WScript.ScriptName),VbExclamation+vbSystemModal,Title
WScript.Quit()
End If
If Question = VbNo And Not AppPrevInstance() Then
Call Kill("wscript.exe")
End If
If Question = VbNo And AppPrevInstance() Then
Call Kill("wscript.exe")
End If
End Sub
'******************************************************************************
Sub Kill(MyProcess)
Dim Titre,colItems,objItem,Processus,Question
Titre = " Processus "& DblQuote(MyProcess) &" en cours d'exécution "
Set colItems = GetObject("winmgmts:").ExecQuery("Select * from Win32_Process " _
& "Where Name like '%"& MyProcess &"%' AND commandline like " & CommandLineLike(WScript.ScriptFullName) & "",,48)
For Each objItem in colItems
objItem.Terminate(0)' Tuer ce processus
Next
End Sub
'******************************************************************************
Sub Download(strFileURL,strHDLocation)
Dim objXMLHTTP,objADOStream
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0 'Set the stream position to the start
objADOStream.SaveToFile strHDLocation,2
objADOStream.Close
Set objADOStream = Nothing
End If
Set objXMLHTTP = Nothing
Shortcut MyScriptPath,"DJ Buzz Radio"
MsgBox "Un raccourci a été crée sur votre bureau !"& vbcr &_
"A shortcut was created on your desktop !"& vbcr &_
ChrW(1578)&ChrW(1605)&ChrW(32)&ChrW(1573)&ChrW(1606)&ChrW(1588)&ChrW(1575)&ChrW(1569)&ChrW(32)&ChrW(1575)&ChrW(1582)&ChrW(1578)&ChrW(1589)&ChrW(1575)&ChrW(1585)&ChrW(32)&ChrW(1593)&ChrW(1604)&ChrW(1609)&ChrW(32)&ChrW(1587)&ChrW(1591)&ChrW(1581)&ChrW(32)&ChrW(1575)&ChrW(1604)&ChrW(1605)&ChrW(1603)&ChrW(1578)&ChrW(1576),vbSystemModal+vbInformation,Title
End Sub
'**************************************************************************
If you mean the settings of the local computer you can query the registry:
REG QUERY "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable
If the value is 0x1 then the there is set proxy. You can check also the proxy value through the value of ProxyServer at the same location. More info here.
You can check if your external IP is the same like your internal IP address.
This uses winhttpjs.bat
for /f "skip=1 tokens=* delims=" %%a in ('winhhttpjs.bat "http://www.telize.com/ip" -saveTo con') do (
set "ip=%%a"
)
ipconfig| find "%ip%" || (
echo not real IP/proxy
)
I am writing email sending code in Classic ASP using CDOSYS, but what i found when i try to write variables concatenation with CDOSYS parameters its gives me error.
I could not write code in following way-
mail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "admin#" & website
it givees me following error while execution - CDO.Message.1 error '80040213'
while following code works fine as its having single variable-
http://schemas.microsoft.com/cdo/configuration/sendusername") = websiteemail
Note:- Reason to use in that way because my client having many sites and previously we used CDONTS and ASPEMAILS and it used to work fine.
Here is the function I created:
function email(s_from,s_reply_to,s_recipients,s_bcc,s_subject,s_msg,s_type,s_msg_error_add,s_remote_host)
if (s_msg_error_add<>"") then s_msg_error_add = "<hr>" & vbCrLf & s_msg_error_add
if (s_remote_host="default") then s_remote_host = application("s_mail_server")
if (s_remote_host="") then s_remote_host = "localhost"
s_remote_host=lcase(s_remote_host)
's_recipients looks like "Scott <scott#domain.net>; Sue <andy#domain.net>" etc
s_from = replace(s_from,","," ",1,-1,1)
s_from = replace(s_from," "," ",1,-1,1)
s_from = replace(s_from,"[","<",1,-1,1)
s_from = replace(s_from,"]",">",1,-1,1)
if (s_reply_to<>"") then
s_reply_to = replace(s_reply_to,","," ",1,-1,1)
s_reply_to = replace(s_reply_to," "," ",1,-1,1)
s_reply_to = replace(s_reply_to,"[","<",1,-1,1)
s_reply_to = replace(s_reply_to,"]",">",1,-1,1)
end if
s_recipients = replace(s_recipients,",",";",1,-1,1)
s_recipients = replace(s_recipients," "," ",1,-1,1)
s_recipients = replace(s_recipients,"[","<",1,-1,1)
s_recipients = replace(s_recipients,"]",">",1,-1,1)
if (s_bcc<>"") then
s_bcc = replace(s_bcc,","," ",1,-1,1)
s_bcc = replace(s_bcc," "," ",1,-1,1)
s_bcc = replace(s_bcc,"[","<",1,-1,1)
s_bcc = replace(s_bcc,"]",">",1,-1,1)
end if
err.clear
Dim MailerConfig
Dim Mailer
Dim strRet
dim sch
strRet = ""
sch = "http://schemas.microsoft.com/cdo/configuration/"
Set MailerConfig = CreateObject("CDO.Configuration")
Set Mailer = CreateObject("CDO.Message")
With MailerConfig.Fields
'.Item(sch & "sendusing") = 2 'send using port - if err then this is really "SendUsingMethod"
'.Item(sch & "sendusingmethod") = 2 'send using port - if err then this is really "SendUsingMethod"
.Item(sch & "smtpconnectiontimeout") = 900
'.Item(sch & "smtpauthenticate") = 1 'use basic (clear-text) authentication
.Item(sch & "smtpserver") = s_remote_host
'.Item(sch & "smtpserverport") = 25
'.Item(sch & "sendusername") = SMAUTHUSER
'.Item(sch & "sendpassword") = SMAUTHPASS
.Update
End With
Mailer.Configuration = MailerConfig
'Mailer.Fields(cdoImportance) = 1
'Mailer.Fields("urn:schemas:mailheader:X-MSMail-Priority") = 1
'Mailer.Fields("urn:schemas:mailheader:X-Mailer") = ""
'Mailer.Fields.Update
'-- Set the Mail Properties
'on error resume next
Mailer.From = s_from
Mailer.To = s_recipients
if (s_reply_to<>"" and s_reply_to<>"na") then Mailer.ReplyTo = s_reply_to
b_redirect=false
if (err.number<>0 and err.number<>13) then
session("msg") = "Error in i_fn_email_cdo.asp line 72, Error: " & err.number & "<br>" & err.description
if (b_redirect) then response.redirect ("error_report.asp?send_mail=yes")
end if
if (s_bcc<>"" AND s_bcc<>"na" AND s_bcc<>"n/a") then Mailer.BCC = s_bcc
if (err.number<>0 and err.number<>13) then
session("msg") = "Error in i_fn_email_cdo.asp line 79, Error: " & err.number & "<br>" & err.description
if (b_redirect) then response.redirect ("error_report.asp?send_mail=yes")
end if
Mailer.Subject = s_subject
if (err.number<>0 and err.number<>13) then
session("msg") = "Error in i_fn_email_cdo.asp line 86, Error: " & err.number & "<br>" & err.description
if (b_redirect) then response.redirect ("error_report.asp?send_mail=yes")
end if
if (s_type="html") then
Mailer.AutoGenerateTextBody = True
s_msg = replace(s_msg,vbCrLf,"<br>",1,-1,1)
else
Mailer.AutoGenerateTextBody = False
end if
if (err.number<>0 and err.number<>13) then
session("msg") = "Error in i_fn_email_cdo.asp line 103, Error: " & err.number & "<br>" & err.description
if (b_redirect) then response.redirect ("error_report.asp?send_mail=yes")
end if
Mailer.MimeFormatted = False
if (err.number<>0 and err.number<>13) then
session("msg") = "Error in i_fn_email_cdo.asp line 110, Error: " & err.number & "<br>" & err.description
if (b_redirect) then response.redirect ("error_report.asp?send_mail=yes")
end if
if (s_type = "text") then
Mailer.TextBody = fn_dirty(s_msg)
else
's_msg_html = replace(s_msg,vbCrLf,"<br>",1,-1,1)
s_msg_html = s_msg
Mailer.HTMLBody = fn_dirty(s_msg_html)
end if
if (err.number<>0 and err.number<>13) then
session("msg") = "Error in i_fn_email_cdo.asp line 123, Error: " & err.number & "<br>" & err.description
if (b_redirect) then response.redirect ("error_report.asp?send_mail=yes")
end if
'-- Fire off the email message
Mailer.Send
if (err.number<>0 and err.number<>13) then
Select Case err.Number
Case -2147220973
strRet = " Failure to Send Report Message - Server Not Found" & vbCrLf & " Error: " & err.Number & " - " & err.Description
Case -2147220975
strRet = " Failure to Send Report Message - Server Authentication Failed" & vbCrLf & " Error: " & err.Number & " - " & err.Description
Case Else
strRet = " Failure to Send Report Message - Error: " & err.Number & " - " & err.Description
End Select
msg = "<br>Error in i_fn_email_cdo.asp: " & strRet & "<br><br>"
msg = msg & "remote host = " & s_remote_host & "<br>"
s_from = replace(s_from,"<","[",1,-1,1)
s_from = replace(s_from,">","]",1,-1,1)
s_reply_to = replace(s_reply_to,"<","]",1,-1,1)
s_reply_to = replace(s_reply_to,">","[",1,-1,1)
s_recipients = replace(s_recipients,"<","[",1,-1,1)
s_recipients = replace(s_recipients,">","]",1,-1,1)
s_bcc = replace(s_bcc,"<","[",1,-1,1)
s_bcc = replace(s_bcc,">","]",1,-1,1)
msg = msg & "from = " & s_from & "<br>"
msg = msg & "to = " & s_recipients & "<br>"
msg = msg & "subject = " & s_subject & "<br>"
msg = msg & "recipients = " & s_recipients & "<br><br>"
if (s_type = "text") then
msg = msg & s_msg
else
msg = msg & s_msg_html
end if
msg = msg & "<br>"
msg = msg & s_msg_error_add
session("msg") = msg
Set Mailer = Nothing
set MailerConfig = nothing
if (b_redirect) then response.redirect ("error_report.asp?send_mail=yes")
end if
Set Mailer = Nothing
set MailerConfig = nothing
email = true
end function
My organization has extremely restrictive and rigid rules our code must comply with in order to obtain certification and accreditation. For the last decade or so we have developed nearly a hundred VS macros that format code, generate comments blocks, enforce style rules, etc.
Our macros are not the kind you record some mouse movements; they all depend on the EnvDTE* VS automation objects. With VS 2012 dropping macros we are at a loss as to whether or not we will even be able to upgrade, without imposing a drastic impact on the team.
I am aware that the direction Microsoft is going is the VS Addins route and I am willing to investigate that route but I am having trouble finding code samples or documentation on how a VS Add-In can interact with the active code file in Visual Studio.
For example, here is a macro we use all the time that applies our Try wrapper design pattern to all methods that are capable of throwing unhandled exceptions
''' <summary>
''' Wraps active method in Try* access wrappers.
''' </summary>
Sub InsertSingleMethodTryWrappers()
Dim textSelection As TextSelection
Dim codeElement As CodeElement
textSelection = DTE.ActiveWindow.Selection
DTE.UndoContext.Open("Generate Try Wrappers") 'Allow for single Undo operation to rollback all changes
Try
codeElement = textSelection.ActivePoint.CodeElement(vsCMElement.vsCMElementFunction)
If Not (codeElement Is Nothing) Then
Dim textSelection2 As TextSelection
Dim codeFunction As CodeFunction
'Dim codeFunction2 As CodeFunction2
Dim editPoint As EditPoint
Dim codeParameter As CodeParameter
Dim parameters As CodeElements
Dim codeElement2 As CodeElement
Dim isVirtual As Boolean = False
Dim strVirtual As String = String.Empty
Dim strTypeName As String = String.Empty
'' Cast the codeElement to codeFunction object
codeFunction = codeElement
'' Move cursor to the start of the method
textSelection.MoveToPoint(codeFunction.GetStartPoint(vsCMPart.vsCMPartHeader))
'' Should be able to use codeFunction.Kind.ToString to retrieve the function type
'' vsCMFunctionVirtual if the method is virtual but there is a bug in the API
'' that returns vsCMFunctionFunction even if the function is virtual (C# parsing bug?)
''
'' vsCMFunction Type
'' http://msdn.microsoft.com/en-us/library/envdte.vscmfunction(v=vs.80).aspx
''
'' This frustrating bug means that we have to parse the header to determine if virtual
textSelection.EndOfLine(True)
If (textSelection.Text.IndexOf("virtual") > 0) Then
isVirtual = True
strVirtual = " virtual"
End If
textSelection.StartOfLine()
'' Try not to screw up comments and attributes
editPoint = GetNoneCommentOrAttribHeaderEditPoint(textSelection)
If editPoint Is Nothing Then
MsgBox("Could not find a line above the method that isn't a comment or attribute", _
MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error")
Exit Sub
End If
'' Create an EditPoint to inject Try* methods
'editPoint = textSelection.TopPoint.CreateEditPoint()
'editPoint.LineUp() 'Move up 1 line
editPoint.EndOfLine() 'Go to end of line above signature
editPoint.Insert(Environment.NewLine) 'Insert blank line for cleanliness
editPoint.Insert(Environment.NewLine) 'Insert blank line for cleanliness
editPoint.LineUp() 'Move up 1 line
parameters = codeFunction.Parameters
Dim strAccess As String : strAccess = GetAccessModifierString(codeFunction.Access) 'Access Modifier
Dim strName As String : strName = codeElement.Name 'Member Name
Dim strType As String : strType = codeFunction.Type.AsString 'Type Name
'' Get the un-qualified object name
If (strType.IndexOf(".") > 0) Then
Dim arrType() As String = strType.Split(".")
strTypeName = arrType(arrType.Length - 1)
Else
strTypeName = strType
End If
''' Create parameter type/name arrayList
Dim arrParams As System.Collections.ArrayList
arrParams = New System.Collections.ArrayList()
For Each codeElement2 In parameters
codeParameter = codeElement2
arrParams.Add(codeParameter.Type.AsString.Trim & " " & codeParameter.Name.Trim & ", ")
Next
Dim strParams As String
Dim strParamNames As String
'' Capture a string with parameter names and types and one just of names
For Each strParam As String In arrParams
strParams += strParam
strParamNames += strParam.Split(" ")(1)
Next
'' Trim excess comma for members of type void
If strType = "void" Then
If Not String.IsNullOrEmpty(strParams) Then
If strParams.TrimEnd.EndsWith(",") Then
strParams = strParams.TrimEnd()
strParams = strParams.Remove(strParams.Length - 1, 1)
End If
End If
End If
'' -- Try* swallow methods --
'' we don't care what the exception is, we just want to know success or failure
Dim strTrySwallowSignature As String
Dim strTrySwallowBody As String
Dim strTryOutParams As String
Dim strOutDef As String
Dim strOutSig As String
'' Members of type 'void' get no out parameters
If Not strType = "void" Then
strTryOutParams = "out " & strTypeName & " outObjType"
strOutDef = "outObjType = null;"
strOutSig = " out outObjType,"
End If
strTrySwallowSignature = vbTab & vbTab & strAccess & strVirtual & " bool Try" & strName & "(" & strParams & strTryOutParams & ")"
strTrySwallowBody = vbCrLf & vbTab & vbTab & "{" _
& vbCrLf & vbTab & vbTab & vbTab & "Exception exception;" _
& vbCrLf & vbTab & vbTab & vbTab & strOutDef _
& vbCrLf & vbTab & vbTab & vbTab & "return Try" & strName & "(" & strParamNames & strOutSig & " out exception);" _
& vbCrLf & vbTab & vbTab & "}"
'' -- Try* re-throw methods --
'' We want to know success or failure as well as the exception if it failed
Dim strTryReThrowSignature As String
Dim strTryReThrowBody As String
'' Members of type 'void' only get out exception parameter
If Not strType = "void" Then
strTryOutParams = "out " & strTypeName & " outObjType, out Exception exception"
'strOutDef = "outObjType = new " & strTypeName & "();"
strOutDef = "outObjType = null;"
Else
strTryOutParams = "out Exception exception"
End If
strTryReThrowSignature = vbTab & vbTab & strAccess & strVirtual & " bool Try" & strName & "(" & strParams & strTryOutParams & ")"
strTryReThrowBody = vbCrLf & vbTab & vbTab & "{" _
& vbCrLf & vbTab & vbTab & vbTab & "bool result = false;" _
& vbCrLf & vbTab & vbTab & vbTab & "exception = null;" _
& vbCrLf & vbTab & vbTab & vbTab & strOutDef _
& vbCrLf & vbTab & vbTab & vbTab & "try" _
& vbCrLf & vbTab & vbTab & vbTab & "{" _
& vbCrLf & vbTab & vbTab & vbTab & vbTab & "// insert code here " _
& vbCrLf & vbTab & vbTab & vbTab & vbTab & "//result = true; " _
& vbCrLf & vbTab & vbTab & vbTab & vbTab & "throw new NotImplementedException();" _
& vbCrLf & vbTab & vbTab & vbTab & "}" _
& vbCrLf & vbTab & vbTab & vbTab & "catch (Exception e)" _
& vbCrLf & vbTab & vbTab & vbTab & "{" _
& vbCrLf & vbTab & vbTab & vbTab & vbTab & "exception = e;" _
& vbCrLf & vbTab & vbTab & vbTab & "}" _
& vbCrLf & vbTab & vbTab & vbTab & "return result;" _
& vbCrLf & vbTab & vbTab & "}"
editPoint.Insert(strTrySwallowSignature)
editPoint.Insert(strTrySwallowBody)
editPoint.Insert(vbCrLf & vbCrLf)
editPoint.Insert(strTryReThrowSignature)
editPoint.Insert(strTryReThrowBody)
editPoint.Insert(vbCrLf)
End If
Catch Ex As Exception
MsgBox(Ex.Message)
Finally
DTE.UndoContext.Close()
End Try
End Sub
Can someone direct me to how a VS 2012 Add-in can manipulate the active/open code file (using EnvDTE* or whatever object model is available for 2012)?
Well that turned out to be really simple. Turns out the Macro object model is part of the VS model so no problem.
http://msdn.microsoft.com/en-us/library/za2b25t3%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/ms228776.aspx
I should have know Microsoft wouldn't have left us Macro-dependant developers out in the cold like that!