Set IP address from a list in VBS - networking

Ok so i'm in the process of imaging a bunch of PC's with Fog. My boss is a stickler for setting everything manually, he won't even let me use Print servers to manage the printers...
Anyway, to make a long story short I've made great strides by writing a bunch of printer install scripts and a couple other small monitoring and other scripts.
So it's now come down to setting IP addresses, which as usual must be set static without the normal AD\DHCP ezmode.
So i was hoping to get some help with this new script i Frankensteined together.
This script "Should"
Read the hostname it's run on (Working!)
Open Computerlist.csv on a network share (Mostly working)
Parse ComputerList.csv, looking for hostname (Works usually, but is case sensative)
take the information listed for hostname, and set variables (Looses .'s when pulled)
Use those variables to configure the network connection. (problematic because of the above #4)
I'm actually pretty surprised i wasn't able to google search a script that had already been built to do this.
Here is what i've cobbled together so far, it seems to be pretty close but I'm missing something wrong and i just can't sort it out.
option explicit
Dim WshShell
Dim ObjShell
Dim objSysInfo
Dim strComputerName
Dim strFile
Set WshShell = WScript.CreateObject("WScript.Shell")
If WScript.Arguments.length = 0 Then
Set ObjShell = CreateObject("Shell.Application")
ObjShell.ShellExecute "wscript.exe", """" & _
WScript.ScriptFullName & """" &_
" RunAsAdministrator", , "runas", 1
Else
end if
'* Pulls Computer name and sets it to variable
Set objSysInfo = CreateObject( "WinNTSystemInfo" )
strComputerName = objSysInfo.ComputerName
'* Loop through CSV file, read entries, store them in an array
dim CONNECTION : set CONNECTION = CreateObject("ADODB.CONNECTION")
dim RECORDSET : set RECORDSET = CreateObject("ADODB.RECORDSET")
CONNECTION.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\carmichaels\e\PCSetup\IPchanger\;Extended Properties=""text;HDR=YES;FMT=Delimited"""
RECORDSET.Open "SELECT * FROM ComputerList.csv WHERE ComputerName = '" & strComputerName & "'", CONNECTION, 3, 3
' //// For testing \\\\
WScript.Echo RECORDSET.Source
' \\\\ For testing ////
if RECORDSET.EOF then
WScript.Echo "Record not found"
WScript.Quit
else
dim strIPAddress : strIPAddress = RECORDSET("IPAddress") & ""
dim strSubnetMask : strSubnetMask = RECORDSET("SubnetMask") & ""
dim strGateway : strGateway = RECORDSET("Gateway") & ""
dim intGatewayMetric : intGatewayMetric = 1
dim strDns1 : strDns1 = RECORDSET("Dns1") & ""
dim strDns2 : strDns2 = RECORDSET("Dns2") & ""
dim strDns3 : strDns3 = RECORDSET("Dns3") & ""
WScript.Echo strIPAddress
end if
'* Set IP address information stored in variables
Set objShell = WScript.CreateObject("Wscript.Shell")
objShell.Run "netsh interface ip set address name=""Local Area Connection"" static " & strIPAddress & " " & strSubnetMask & " " & strGateway & " " & intGatewayMetric, 0, True
objShell.Run "netsh interface ip set dns name=""Local Area Connection"" static "& strDns1, 0, True
objShell.Run "netsh interface ip add dns name=""Local Area Connection"" addr="& strDns2, 0, True
objShell.Run "netsh interface ip add dns name=""Local Area Connection"" addr="& strDns3, 0, True
Set objShell = Nothing
My problem is when i run this script, It claims line 28 chr 1 cannot open the file (on 32 bit machines).
And on a 64 Bit machine, (i run it with the following in a .bat [%windir%\SysWoW64\cscript \server\share\folder\folder\IPchanger.vbs] ) it runs through but the IP address is missing dots. ex. 10.1.0.57 appears as 10.1057 in my test window, and will fail to run again claiming the file is open or locked.
Here's the CSV file
ComputerName,IPAddress,SubnetMask,Gateway,Dns1,Dns2,Dns3
CLONE2,10.1.0.57,255.255.255.0,10.1.0.1,10.1.0.18,10.1.0.13,10.1.0.12

Dont know about your file open errors, for me line 28 is
Set objShell = WScript.CreateObject("Wscript.Shell")
But to avoid the problem with the dots, using Jet OLEDB text filter, you need to define a Schema.ini file for the csv. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms709353%28v=vs.85%29.aspx
I think Jet asumes your IPs to be decimal numbers, not text.

Related

GetCurrentUserName() is causing crash in MS Access 2010

I am running Windows 7 Professional. I have an MS Access frontend to an MS Access backend. The form that opens at the start of opening the frontend causes the app to crash.
Here is the code:
Private Sub Form_Open(Cancel As Integer)
Dim strMyDir As String
Dim intPos As Integer
Dim rst As dao.Recordset
Dim strSQL As String
Dim rstWhatsNew As dao.Recordset
DoCmd.ShowToolbar "Database", acToolbarNo
DoCmd.ShowToolbar "Toolbox", acToolbarNo
DoCmd.ShowToolbar "Form View", acToolbarNo
If Application.GetOption("ShowWindowsInTaskbar") = -1 Then
Application.SetOption "ShowWindowsInTaskbar", 0
End If
If DLookup("Locked", "luLockOut") <> 0 Then
MsgBox "Database is being worked on. Please try back in a couple minutes.", vbInformation, " "
DoCmd.Quit
Else
strSQL = "Select * From tblLastLogins Where UserName = '" & GetCurrentUserName() & "'"
This is where I have traced the error to: GetCurrentUserName()
Set rst = CurrentDb.OpenRecordset(strSQL)
With rst
If Not .EOF Then
.Edit
strSQL = "Select WhatsNewID From tblWhatsNew Where DateAdded >= #" & !LastLoginDate & "#"
Set rstWhatsNew = CurrentDb.OpenRecordset(strSQL)
While Not rstWhatsNew.EOF
DoCmd.OpenForm "frmWhatsNew", , , , , acDialog, rstWhatsNew!WhatsNewID
rstWhatsNew.MoveNext
Wend
rstWhatsNew.Close
Set rstWhatsNew = Nothing
Else
.AddNew
!UserName = GetCurrentUserName()
End If
!LastLoginDate = Now()
!IsLoggedIn = -1
Me.txtLastLoginID = !LastLoginID
.Update
.Close
End With
Set rst = Nothing
DoCmd.OpenForm "frmPrivacyNote"
Debug.Print Me.txtLastLoginID
End If
I need to track the username, so if GetCurrentUserName() is outdated, what is the current syntax?
Further follow up. I could not find data on Bing for GetCurrentUserName(), for good reason. It is a function within a MOD, so I need to figure out why the MOD is not getting called, or is malfunctioning.
After further delving, I found a Referenced MDB that has another function created by one of our users that is the cause of this error.
This is currently not an issue of MS Access working incorrectly. It is an issue with user created code.
GetCurrentUserName() is not defined by Access, so you should have looked at (and posted) its code.
If you are looking for the Windows user name, use this function:
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Environ("USERNAME") is easily spoofed, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
Source
The link below would suggest that
CurrentUser()
is the function
CurrentUser()
Andre, thank you very much for the insight! I found this link:
http://www.codeproject.com/Articles/1422/Getting-User-Information-Using-WSH-and-VBScript
Dim objNet
On Error Resume Next
'In case we fail to create object then display our custom error
Set objNet = CreateObject("WScript.NetWork")
If Err.Number <> 0 Then 'If error occured then display notice
MsgBox "Don't be Shy." & vbCRLF &_
"Do not press ""No"" If your browser warns you."
Document.Location = "UserInfo.html"
'Place the Name of the document.
'It will display again
End If
Dim strInfo
strInfo = "User Name is " & objNet.UserName & vbCrLf & _
"Computer Name is " & objNet.ComputerName & vbCrLf & _
"Domain Name is " & objNet.UserDomain
MsgBox strInfo
Set objNet = Nothing 'Destroy the Object to free the Memory

How to Sync 6 Laptops in network in MS Access 2010 Application with Split database [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i created an Application build in MS Access 2010, this create Jobs Orders, I am using split database which let me keep the tables in the server and the Front end program in the Work Station. Now, the problem is i have 6 laptops with the same application, but when the go out to the field the Laptops disconnect from network. I NEED A WAY TO SYNC TABLES WITH THE JOBS DONE when laptops come back to the office and connect to the network again.
I am Syncing pressing a button that copy files to server, delete tables locally and then copy back from server the records, but i want to find a way to Sync automatic when laptops find the network.
'*************IN THIS PART AM SENDING UPDATING SERVER AND SENDING NEW RECORDS ************
Dim x As Integer
Dim i As Integer
Dim strSQL As String
x = MsgBox("Are you Sure you want to Send to Server?????", vbOKCancel, "Are you sure?")
If x = vbOK Then
Dim intX, intY As Integer
Dim intW As Integer
Dim db As Database
Dim LSQL, SOurce, DestinaTion, fILE As String
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
SOurce = "O:\fieldticket\"
'DestinaTion = "\\rvfile03\Departments\Water\Common\FieldTickets\"
DestinaTion = "\\rwmain01\gis\FieldTicket\"
fILE = Dir$(SOurce & "*.one")
' Do While Len(fILE) > 0 And FSO.FileExists(DestinaTion & fILE) = True
Do While Len(fILE) > 0
If FSO.FileExists(fILE & DestinaTion) = False Then
FileCopy SOurce & fILE, DestinaTion & fILE
End If
fILE = Dir$()
Loop
fILE = Dir$(SOurce & "*.pdf")
Do While Len(fILE) > 0
If FSO.FileExists(fILE & DestinaTion) = False Then
FileCopy SOurce & fILE, DestinaTion & fILE
End If
fILE = Dir$()
Loop
Set db = CurrentDb()
' REINIT PROGRESS BAR
ProgressBarB.WIDTH = 0
Me.Repaint
' FILL IN OUR SQL QUERIES COLLECTION
Define_SQL_Queries
DoCmd.SetWarnings False
Me.Refresh
Me.Repaint
DoCmd.SetWarnings False
Me.Refresh
With CurrentDb
' ******* COUNT HOW MANY NEW RECORD ARE TRANSFERING **************************************************
intX = DCount("*", "RECORDS IN JobsOrder NOT IN JobsOrder1")
' ********** UPDATE JOBSORDER TABLE AND COUNT HOW MANY RECORDS ARE UPDATED ******************************
LSQL = "UPDATE_Jobsorder1_SERVER_WITH_Jobsorder"
db.Execute LSQL
' **************** GIVE A MESSAGE OF HOW MANY RECORDS ARE UPDATED AND TRANSFERED **********************
MsgBox CStr(db.RecordsAffected) & " RECORDS UPDATED " & intX & " NEW RECORDS WILL BE ADDED AND "
'************ new progress bar code using for command *************
Me.ProgressBarA.Visible = True
Me.ProgressBarB.Visible = True
For i = 1 To colSQL.Count
strSQL = colSQL(i)
Debug.Print "Executing : " & strSQL
Call .QueryDefs(strSQL).Execute
ProgressBarB.WIDTH = (ProgressBarA.WIDTH / colSQL.Count) * i
Me.Repaint
Next i
Call Me.Requery
DoCmd.SetWarnings True
End With
' MsgBox ("TRANSFER AND UPDATE HAS BEEN FINISHED!!!")
Me.ProgressBarA.Visible = False
Me.ProgressBarB.Visible = False
' Exit Sub
ElseIf x = vbCancel Then
Exit Sub
End If
'*******NOW I AM SENDING BACK FROM SERVER TO HANDHELD ************************
Dim y As Integer
Dim ii As Integer
Dim strSQL1, SOurce1, DestinaTion1, fIL1E As String
Beep
'x = MsgBox("Are you Sure you want to UPDATE HANDHELD?????", vbOKCancel, "Are you sure?")
'If y = vbOK Then
'If PASSWORD = "222222" Then
Dim intX1, intY1 As Integer
Dim intW1 As Integer
DoCmd.SetWarnings False
ProgressBarB.WIDTH = 0
Me.Repaint
'SOurce = "\\rvfile03\Departments\Water\Common\FieldTickets\"
'DestinaTion = "c:\mapping\"
'fILE = Dir$(SOurce & "*.one")
'Do While Len(fILE) > 0
' If Dir$(fILE) & "" = "" Then
' FileCopy SOurce & fILE, DestinaTion & fILE
' End If
' fILE = Dir$()
'Loop
' FILL IN OUR SQL QUERIES COLLECTION
Define_SQL_Queries1
DoCmd.SetWarnings False
Me.Refresh
With CurrentDb
intX1 = DCount("*", "RECORD IN Jobsorder1 not Finished")
' MsgBox (intX1 & " RECORDS WILL BE ADDED")
Me.ProgressBarA.Visible = True
Me.ProgressBarB.Visible = True
For ii = 1 To colSQL1.Count
strSQL1 = colSQL1(ii)
Debug.Print "Executing : " & strSQL1
Call .QueryDefs(strSQL1).Execute
ProgressBarB.WIDTH = (ProgressBarA.WIDTH / colSQL1.Count) * ii
Me.Repaint
Next ii
Call Me.Requery
DoCmd.SetWarnings True
End With
MsgBox ("HANDHELD UPDATE COMPLETED!!!"), vbInformation
ProgressBarA.Visible = False
ProgressBarB.Visible = False
Exit Sub
'ElseIf y = vbCancel Then
' Exit Sub
'End If
MsgBox (intX1 & " RECORDS ADDED TO HANDHELD")
'******** FINISHING THE HANADHEL UPDATING *******************
You'll need to write some code to check connectivity (On Error Resume next when connecting to the back end tables and check for an Error) and then connect to another local table if offline. Then once back in the office that code can then connect as normal and then you can upload your Jobs. Bottom line is that it'll take some VBA to do this. I can't give you a solution in code but this is the gist of it.
If you know how to code in VBA then you can really just check for a Network Folder that will be there if you're on the network. If it's not there, then you can assume you're offline. Then you will need to write more code to deal with local tables rather than linked tables.
Dim fso As FileSystemObject
Set fso = New FileSystemObject
If fso.FolderExists("[Path to Network Folder]") Then
' I'm online
Else
' I'm offline
End If

Creating dynamic ADODB connections in Classic ASP

I have a list of Database connection strings, Database Name. These databases have the same table structure. What I am trying to do is dynamically create a connection to each one, add/delete/modify a table, however, if an error pops up anywhere, then RollbackTrans, else, CommitTrans.
My basic question to get my on the correct path is this:
Is this code possible in Classic ASP to make Dynamically named connections?
'create the dynamic object
execute("Set Con" & index & " = Server.CreateObject(""ADODB.connection"")")
'connect to the dynamic object
execute("Con" & index & ".Open " & DBString(index))
The error I get is 'Expected end of statement' on the .open line (the last one)
This might do the trick: Just use an array of connection strings. From this you create an array of connections. Then you can iterate over this array and send your commands to the separate databases.
dim connectionStrings(1)
dim connections(1)
dim curConn
connectionStrings(0) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=master;uid=youruser;pwd=yourpwd"
connectionStrings(1) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=model;uid=youruser;pwd=yourpwd"
for curConn = 0 to ubound( connectionStrings)
set connections(curConn) = Server.CreateObject("ADODB.Connection")
connections(curConn).Open connectionStrings(curConn)
next
dim cmd : cmd = "select ##servername, db_name()"
for curConn = 0 to ubound( connectionStrings)
dim rs
set rs = connections(curConn).Execute( cmd)
Response.write( rs( 0) & ":" & rs(1) & "<br />")
rs.close
set rs = nothing
next
for curConn = 0 to ubound( connectionStrings)
call connections(curConn).Close
set connections(curConn) = nothing
next
Mysql Dynamic Connection String , sample for t=1 to 4 , four different database connection conns(t)
dim conns(4)
Set Conns(1)=Server.Createobject("ADODB.Connection")
Conns(1).Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost;port=3306;DATABASE=dbname;UID=root;PASSWORD=pass;OPTION=3"
Conns(1).Execute "SET NAMES 'latin5'"
Conns(1).Execute "SET CHARACTER SET latin5"
Conns(1).Execute "SET COLLATION_CONNECTION = 'latin5_turkish_ci'"

Why 'The local device name is already in use' in asp.net when mapping drive but OK with command line

In command line it works fine:
net USE T: \123.45.67.89\TEST mytestuser /user:MYTESTUSER
But using asp.net, with the following code, the Exception with the following error is always thrown: 'The local device name is already in use' when mapping drive
I have tried disconnecting from all drives first, mapping to a different Drive letter. I have done this from different servers, and to different servers
Is the problem definitely with drive letter?
temp = MapDrive("T", "\\123.45.67.89\TEST", "MYTESTUSER", "mytestuser")
Public Shared Function MapDrive(ByVal DriveLetter As String, ByVal Path As String, ByVal Username As String, ByVal Password As String) As Boolean
Dim ReturnValue As Boolean = False
Dim p As New System.Diagnostics.Process()
p.StartInfo.UseShellExecute = False
p.StartInfo.CreateNoWindow = True
p.StartInfo.RedirectStandardError = True
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.FileName = "net.exe"
p.StartInfo.Arguments = " use " & DriveLetter & ": " & Path & " /user:" & Username & " " & Password & " /persistent:yes"
p.Start()
p.WaitForExit()
Dim ErrorMessage As String = p.StandardError.ReadToEnd()
Dim OuputMessage As String = p.StandardOutput.ReadToEnd()
Dim StoreFile As System.IO.Directory
Dim Files As String()
Dim File As String
If ErrorMessage.Length > 0 Then
Throw New Exception("Error:" & ErrorMessage)
Else
ReturnValue = True
End If
Files = StoreFile.GetFiles("T:\FINDTHIS\", "*")
For Each File In Files
HttpContext.Current.Trace.Warn(File)
Next
Return ReturnValue
End Function
Aren't mapped drives particular to the user that is running the net command?
Your asp.net page usually runs under a different identity to the current user's. This means that your code might possibly map the network path successfully the first time you run it. Then when you run it the second time you will get that error.
But then you are looking in vain to delete the mapping for that letter in your cmd window since the drive was not mapped via your user identity (under which your cmd window is running after all)
Then there's also the permissions needed to run the net command, although that might have thrown a different error.

ASP.NET - remote screenshot

I made a very very simple small app to take screenshot of the desktop and send to network share. About 10 PC's would have this app installed.
My idea is, that there will be one dashboard in ASP.NET, which simply shows those screenshots on the webpage. So far, easy stuff.
But, because I don't want to clog the network and send the screenshot every 1 minute, I would like to launch the .exe on the remote PC's by demand of ASP.NET user.
Unfortunately I haven't found any information (and I'm a complete ASP.NET n00b), how to launch remote executable IN the context of the remote PC (so I won't see screenshots of ASP server :) )
If there is no such possibility, please advise about other way to solve this.
Update after clarification:
Take a look at the situation from another angle:
Why don't you run a web server on the clients that host an asp.net page that triggers the capture. Then you can, from your root server, simply sent http requests to the clients and fetch the image.
You can try http://CassiniDev.codeplex.com - it supports external IP and hostnames.
And you may also consider simply embedding the CassiniDev-lib (a very simple example is shown here - Using CassiniDev to host ASP.Net in your application, that way you can use the web server as the reciever and the forms app can do whatever it wants on the client.
I am confident in this approach as I designed cassinidev with this as one of the primary use cases.
From asp.net you cannot. It is only HTML/JavaScript once it gets to the browser.
ActiveX is a possibility but it is quite painful and dated and limited. And painful.
The new way to do something like this is to deploy a .net Forms application or WPF app via Click Once.
You can also write a WPF Browser Application but getting the kind of permissions you would need would entail setting the site as full trust.
If a web page could launch an arbitrary .exe file on your machine, that would be a security disaster.
However, since these are your PCs, you can require them to install an ActiveX control of some kind that you could then embed in your ASP.NET page.
As others have said, there is really no way for ASP.Net to call out to the apps, but reversing the control flow should work OK...
I suppose you could have the grabber application running all the time on the users desktop, but have it make a call to a web service / file served by the server that contains an instruction for that instance of the app to grab a screenshot.
Something like...
App : Do I have to do anything? (GET /workinstruction.aspx)
Server : no. (server decides whether to request work, and return the result in (workinstruction.aspx)
App : (waits 1 minute)
App : Do I have to do anything?
Server : yes.
App : (takes screenshot and submits)
App : (waits 1 minute)
App : Do I have to do anything?
etc...
Thank you all for answering, those were interesting approaches to the subject.
Yet due to many factors I ended up with following solution:
Pseudo-service (Windows Forms with tray icon and hidden form) application on client PC's. It is serving as TCP server.
ASP.Net web app on the server, with TCP client function.
On request of the web user, web app is sending preformatted TCP 'activation' string to the chosen PC. Tray app is making a screenshot and sending it to predefined SMB share, available for web app to display.
Thanks again!
I've done this exact thing a few times for monitoring remote display systems. What I found was that using MiniCap.exe to capture image also took video (which was required on remote display systems).
I also used Cassini as described by Sky Sanders with an ASPX-page with the following code.
Then I just reference the page from an img src="http://computer/page.aspx?paramters". (Let me know if you need more info)
<%# Import NameSpace="System.IO" %>
<%# Import NameSpace="System.Drawing" %>
<%# Import NameSpace="System.Drawing.Imaging" %>
<%# Import NameSpace="System.Diagnostics" %>
<%
Response.Buffer = True
Response.BufferOutput = True
Dim CompressionLevel As Integer = 1
Dim compress As Integer = 1
If Not Request.Item("compress") Is Nothing Then
If IsNumeric(Request.Item("compress")) = True Then
CompressionLevel = CInt(Request.Item("compress"))
End If
End If
compress = CompressionLevel
' Resize requested?
Dim SizeX As Integer = 100
Dim SizeY As Integer = 75
If Not Request.Item("width") Is Nothing Then
If IsNumeric(Request.Item("width")) = True Then
SizeX = CInt(Request.Item("width"))
CompressionLevel = 10
End If
End If
If Not Request.Item("height") Is Nothing Then
If IsNumeric(Request.Item("height")) = True Then
SizeY = CInt(Request.Item("height"))
CompressionLevel = 10
End If
End If
Dim Region As String = ""
If Not Request.Item("region") Is Nothing Then
Region = Request.Item("region")
End If
Dim XS As Integer = 0
Dim YS As Integer = 0
Dim XE As Integer = 1023
Dim YE As Integer = 766
Try
If Region.IndexOf(",") > -1 Then
Dim Rec() As String = Region.Split(",")
If Rec.GetUpperBound(0) >= 3 Then
If IsNumeric(Rec(0)) Then XS = Rec(0)
If IsNumeric(Rec(1)) Then YS = Rec(1)
If IsNumeric(Rec(2)) Then XE = Rec(2)
If IsNumeric(Rec(3)) Then YE = Rec(3)
End If
End If
Catch : End Try
Dim FileType As String = "jpg"
Dim MimeType As String = "jpeg"
If Not Request.Item("filetype") Is Nothing Then
FileType = Request.Item("filetype")
MimeType = FileType
End If
If Not Request.Item("mimetype") Is Nothing Then
FileType = Request.Item("mimetype")
End If
Dim ImageFile As String = ""
Dim ImageThumbFile As String = ""
Dim ImageFolder As String = Server.MapPath("~/ScreenShots/")
If IO.Directory.Exists(ImageFolder) = False Then
IO.Directory.CreateDirectory(ImageFolder)
End If
' Delete files older than 30 minutes
For Each File As String In IO.Directory.GetFiles(ImageFolder)
Response.Write("File: " & File & "<br>")
If IO.File.GetCreationTimeUtc(File).AddMinutes(30) < Now.ToUniversalTime Then
IO.File.Delete(File)
End If
Next
' Find available filename
Dim tmpC As Integer = 0
While tmpC < 100
tmpC += 1
ImageFile = "ScreenShot_" & CStr(tmpC).PadLeft(5, "0") & "." & FileType
ImageThumbFile = "ScreenShot_" & CStr(tmpC).PadLeft(5, "0") & "_thumb." & FileType
If IO.File.Exists(ImageFolder & "\" & ImageFile) = False Then
' Found our filename
' Reserve it
Dim ios As IO.FileStream = IO.File.Create(ImageFolder & "\" & ImageFile)
ios.Close()
ios = Nothing
Exit While
End If
End While
' Run MiniCap
' " -capturedesktop" & _
Dim CMD As String = """" & Server.MapPath("/MiniCap.EXE") & """" & _
" -save """ & ImageFolder & "\" & ImageFile & """" & _
" -captureregion " & XS & " " & YS & " " & XE & " " & YE & _
" -exit" & _
" -compress " & CompressionLevel
If Not CMD Is Nothing Then
Dim myProcess As Process = New Process
Dim RouteFB As String
With myProcess
With .StartInfo
.FileName = "cmd.exe"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
.Start()
End With
Dim sIn As IO.StreamWriter = myProcess.StandardInput
sIn.AutoFlush = True
' Create stream reader/writer references
Dim sOut As IO.StreamReader = myProcess.StandardOutput
Dim sErr As IO.StreamReader = myProcess.StandardError
' Send commands
sIn.Write(CMD & System.Environment.NewLine)
sIn.Write("exit" & System.Environment.NewLine)
' Wait one second
'Threading.Thread.CurrentThread.Sleep(60000)
' Read all data
Response.Write(sOut.ReadToEnd)
' Kill process if still running
If Not myProcess.HasExited Then
myProcess.Kill()
End If
sIn.Close()
sOut.Close()
sErr.Close()
myProcess.Close()
End If
Response.Clear()
Response.ClearContent()
If Not Request.Item("width") Is Nothing Or Not Request.Item("length") Is Nothing Then
' Resize, making thumbnail in desired size
Dim b As Bitmap = Bitmap.FromFile(ImageFolder & "\" & ImageFile)
Dim thumb As Bitmap = b.GetThumbnailImage(SizeX, SizeY, Nothing, IntPtr.Zero)
' Jpeg image codec
Dim jpegCodec As ImageCodecInfo
' Get image codecs for all image formats
Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
' Find the correct image codec
For i As Integer = 0 To codecs.Length - 1
If (codecs(i).MimeType = "image/" & MimeType) Then
jpegCodec = codecs(i)
Exit For
End If
Next i
Dim qualityParam As New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compress * 10)
Dim encoderParams As New EncoderParameters(1)
encoderParams.Param(0) = qualityParam
thumb.Save(ImageFolder & "\" & ImageThumbFile, jpegCodec, encoderParams)
thumb.Dispose()
b.Dispose()
' Send thumb
Response.TransmitFile(ImageFolder & "\" & ImageThumbFile)
Else
' Send normal file
Response.TransmitFile(ImageFolder & "\" & ImageFile)
End If
Response.End()
%>

Resources