Use VB.net to create scheduled task that has "Run with highest privileges" enabled - vb.net

I have a function that creates a task but I can not get the checkbox enabled for "Run with highest privileges". I commenrted out the line for Runlevel as it was giving an error.
Below is the funcion.
Sub VaultProFullBackupTask()
Using tService As New TaskService()
Dim tDefinition As TaskDefinition = tService.NewTask
tDefinition.RegistrationInfo.Description = "Vault Pro Full Backup"
tDefinition.Settings.Priority = ProcessPriorityClass.AboveNormal
'tDefinition.Principal.RunLevel = TaskRunLevel.Highest
Dim tTrigger As New WeeklyTrigger()
tTrigger.StartBoundary = DateTime.Today.AddDays(2)
tTrigger.DaysOfWeek = DaysOfTheWeek.Monday
tTrigger.WeeksInterval = 1
tDefinition.Triggers.Add(tTrigger)
tDefinition.Actions.Add(New ExecAction(VaultScriptFolder & "\VaultBackupFull.bat"))
tService.RootFolder.RegisterTaskDefinition("Vault Pro Full Backup", tDefinition)
End Using
End Sub

Related

How to select a tray on a printer thorugh code when printing from a word document in VB (VS2019)

Hi I'm trying to create a word document and then print it with VB in visual studio 2019.
Creation works ok, the document saves fine, and prints fine to the general tray but I cannot get the application to send the print job to a specified tray. the prints will just come out of the default paper try
the customers have an array of different printer makes and models
ive tried printing the document through word, ive also tried changing the printer itself on the computer to set the tray then change it back after
TRY 1
Dim intTray As Integer = varibleNumber
If intTray = 1 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterUpperBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterUpperBin
ElseIf intTray = 2 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterMiddleBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterMiddleBin
ElseIf intTray = 3 Then
oWord.ActiveDocument.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterLowerBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterLowerBin
Else
'else print default tray
oWord.ActiveDocument.p.PageSetup.FirstPageTray = Word.WdPaperTray.wdPrinterDefaultBin
oWord.ActiveDocument.PageSetup.OtherPagesTray = Word.WdPaperTray.wdPrinterDefaultBin
End If
TRY 2
Dim intTray As Integer = varibleNumber
Dim oPS As New System.Drawing.Printing.PrinterSettings
If intTray = 1 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 1")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 1"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 1"
ElseIf intTray = 2 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 2")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 2"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 2"
ElseIf intTray = 3 Then
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Tray 3")
oWord.ActiveDocument.PageSetup.FirstPageTray = "Tray 3"
oWord.ActiveDocument.PageSetup.OtherPagesTray = "Tray 3"
Else
'else print default tray
oPS.DefaultPageSettings.PaperSource = oPS.DefaultPageSettings.PrinterSettings.PaperSources.Item("Automatically Select")
End If
modPrint.printWordDoc(oWord)
Pages just come out of the main printer tray.
Any help much appreciated
One quick solution that pops to my mind is to use VBA Printer Setup Dialog to change the Tray on your printer settings. Try executing this line of code and change the options on the printer you're using:
Application.Dialogs(xlDialogPrinterSetup).Show
Edit:
Try using this code specific to VB framework. It's a valid starting point, since it allows you to select which print to use:
Public Sub Printing(printer As String)
Try
streamToPrint = New StreamReader(filePath)
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Specify the printer to use.
pd.PrinterSettings.PrinterName = printer
If pd.PrinterSettings.IsValid then
pd.Print()
Else
MessageBox.Show("Printer is invalid.")
End If
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
You can find more info here on Microsoft Documentation.
Hope this helps.
Managed to resolve the issue finally :) each printer has its own tray numbers for every tray, even if they are labelled Tray1 Tray2 etc.
so had to look through the papersources find when the source name equalled the tray number I wanted then grab the rawkind value of that source and use that as the tray number when allocating to the word firstpagetray
Dim intTray As Integer = <tray number i'm looking for>
Dim oPS As New System.Drawing.Printing.PrinterSettings
Dim paper_Source As PaperSource = New PaperSource
Dim i As Integer = 0
For Each ps As PaperSource In oPS.PaperSources
If ps.SourceName.Contains(intTray.ToString) Then
i = ps.RawKind
Exit For
End If
Next
oWord.ActiveDocument.PageSetup.FirstPageTray = i
Hope this helps others with the same issue

VB.Net - Program can't Edit HKEY_Local_Machine registry entry

I have a similar problem, VB.Net - Program can't Edit HKEY_Local_Machine registry entry, that was listed, but the fix did not work for me. I am using Visual Studio 2017. I am trying to create a portable app that will work in Windows 7 Professional and Windows 10 Professional. The idea is to reset the last logged on person to either Blank or a different user. My colleagues and I have to logged into member computers with an elevated account to work on them, but the member does not pay attention and causes our account to get locked out. we are not allowed to use group policy to correct this problem, so I am trying to do it with my app. I can make changes via regedit, vbs and batch files, but I cannot seem to get my program in VB2017 to work. I took off the preferred 32bit checkbox and tried running it as an administrator or a different user with administrative rights. I get the same error . . . cannot write to the registry (HKEY_Local_Machine registry). Below is my code. Any help would be appreciated.
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
Dim regVersion64 As Microsoft.Win32.RegistryKey = Microsoft.Win32.RegistryKey.OpenBaseKey _
(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64).
OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI")
If chkbClearEverything.Checked = True Then
regVersion64.SetValue("LastLoggedOnDisplayName", "")
regVersion64.SetValue("LastLoggedOnSAMUser", "")
regVersion64.SetValue("LastLoggedOnUser", "")
Else
tbd1 = TBLogon.Text
tbs1 = TBsam.Text
tbu1 = TBllu.Text
regVersion64.SetValue("LastLoggedOnDisplayName", tbd1)
regVersion64.SetValue("LastLoggedOnSAMUser", tbs1)
regVersion64.SetValue("LastLoggedOnUser", tbu1)
End If
Dim rvLastLoggedOnDisplayName As String = regVersion64.GetValue("LastLoggedOnDisplayName")
Dim rvLastLoggedOnSANuser As String = regVersion64.GetValue("LastLoggedOnSAMUser")
Dim rvLastLoggedOnUser As String = regVersion64.GetValue("LastLoggedOnUser")
If Not rvLastLoggedOnDisplayName = "" Then
TBLogon.Text = rvLastLoggedOnDisplayName
tbd1 = rvLastLoggedOnDisplayName
End If
If Not rvLastLoggedOnSANuser = "" Then
TBsam.Text = rvLastLoggedOnSANuser
tbs1 = rvLastLoggedOnSANuser
End If
If Not rvLastLoggedOnUser = "" Then
TBllu.Text = rvLastLoggedOnUser
tbu1 = rvLastLoggedOnUser
End If
regVersion64.Close()
End Sub

vb.net runs gpg.exe step of job runs ok from PC but not from SQL Server Agent schedule

Everything worked great from my Visual Studio on my PC running this from the Start button. When I build the executable and copied the executable to the production box and scheduled the job via SQL Server Agent on the production machine – everything worked fine to create the file, but the encryption bit does not work.
The gpg.exe is here on the production server: \sql2014\c$\Program Files (x86)\GnuPG\bin
The gpg is here on my PC: C:\Program Files (x86)\GnuPG\bin
The filename.csv gets created in the proper location ok - I tested with both these names
Dim Extract_File As String = “\sql2014\e$\Extracts\ProgramName\filename.csv”
‘Dim Extract_File As String = “E:\Extracts\ProgramName\filename.csv” ‘do to this from my PC I had to change the E: to a C:
This line calls the function:
FileEncrypted = Encrypt_File(Extract_File, Batch_Timestamp)
Private Function Encrypt_File(File_To_Encrypt As String, Batch_Timestamp As Date)
On Error GoTo Encrypt_File_Error
Dim Success As Boolean = False
Dim sourceName As String = File_To_Encrypt
Dim gpgProcess = New Process()
‘Test with working directory - no effect
‘gpgProcess.StartInfo.UseShellExecute = False
'gpgProcess.StartInfo.WorkingDirectory = "\\sql2014\c$\Program Files (x86)\GnuPG\bin\"
‘gpgProcess.StartInfo.FileName = "gpg.exe"
gpgProcess.StartInfo.FileName = \\sql2014\c$\Program Files (x86)\GnuPG\bin\gpg.exe ‘This works from my PC
‘gpgProcess.StartInfo.FileName = \\sql2014\c$\Program Files (x86)\GnuPG\bn\gpg.exe ‘If I change this path took the “i” out of bin I get an error: The system cannot find the file specified
gpgProcess.StartInfo.UseShellExecute = False
gpgProcess.StartInfo.CreateNoWindow = True
gpgProcess.StartInfo.Arguments = "--batch --yes --recipient reciptname --encrypt " & sourceName
gpgProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
gpgProcess.Start()
gpgProcess.WaitForExit()
If FileExists(sourceName & ".gpg") Then
Success = True
End If
Encrypt_File_Exit:
On Error Resume Next
‘gpgProcess.WaitForExit() moved this up to
gpgProcess.Close()
Return Success
Exit Function
Encrypt_File_Error:
Error_Handler("SomeModule.vb", "Encrypt_File", Err, System_Output, Batch_Timestamp)
Resume Encrypt_File_Exit
End Function
Any suggestions for how I can resolve this. When it worked on my PC it creates a filename.csv.gpg in the same directory as filename.csv. On the production server it does not create the gpg and it does not give a visible error message either.
This is how I solved this issue. I Installed the OpenPgpLib from the NuGet Package Manager and re-wrote this Function as shown here.
I created the .asc file from the Kleopatra tool and saved it in the location used in the pubkey in the code bit below. The OpenPgp is from the package.
Private Function Encrypt_File(File_To_Encrypt As String, Log_File As String, Batch_Timestamp As Date)
Dim Success As Boolean = False
Dim encryptthis As String = File_To_Encrypt
Dim thisencrypted As String = File_To_Encrypt & ".gpg"
Dim pubkey As String = "\\sql2014\c$\Data_Programs\MyDirectory\<thepublickeyfile>.asc"
Try
OpenPgp.EncryptFile(encryptthis, thisencrypted, pubkey, False, False)
If FileExists(thisencrypted) Then
Success = True
End If
Catch ex As Exception
App_Logger(Log_File, ex.StackTrace.ToString(), System_Output, Batch_Timestamp)
Success = False
End Try
Return Success
End Function

Check if Mage.exe batch manifest update was successful or not - ClickOnce

I have created a console app that creates a batch file in code, that will automatically update and re-sign my app manifest file using mage.exe when a new version gets published.
This batch file then gets executed by the same console app after it has created it.
I want to know if there is a way to determine if the mage.exe batch file failed in updating or signing the manifest?
Any help or ideas will be appreciated.
UPDATE
As per TnTinMn's comment, I forced the batch to fail on updating the manifest. This returned a exit code of 1. How is it then possible for me to extract that exit code to do my error handling? Im doing the following:
Dim procInfo As New ProcessStartInfo()
procInfo.UseShellExecute = True
procInfo.FileName = (sDriveLetter & ":\updatemanifest.bat")
procInfo.WorkingDirectory = ""
procInfo.Verb = "runas"
procInfo.WindowStyle = ProcessWindowStyle.Hidden
Dim sval As Object = Process.Start(procInfo) 'I tested the object to see if there is indeed a value that i can use.
While debugging and looking at the sval object's properties, the exit code is set to 1 but i can't seem to extract it from there.
There are two ways (that I know of) that you can wait for the process to exit before retrieving the Process.ExitCode.
The first as is a blocking call: Process.WaitForExit
and the second is to use the Exit event.
Private Sub RunProcess()
Dim psi As New ProcessStartInfo()
psi.UseShellExecute = True
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = "cmd.exe"
psi.Arguments = "/c Exit 100"
Dim proc As Process = Process.Start(psi)
proc.EnableRaisingEvents = True
AddHandler proc.Exited, AddressOf ProcessExited
End Sub
Private Sub ProcessExited(sender As Object, e As EventArgs)
Dim proc As Process = DirectCast(sender, Process)
proc.Refresh()
Dim code As Int32 = proc.ExitCode
Me.BeginInvoke(Sub() MessageBox.Show(String.Format("Process has exited with code: {0}", code)), Nothing)
proc.Dispose()
End Sub

Provisioned XlstViewWebPart in root web gives me List does not exist when delete

Consider following:
I have an Admin sub site which have all lists and Document Libraries, I provision most of Document Libraries in the Root web programmatically using XlstViewWebPart, when I try to select an item and delete it using delete button on the ribbon I get:
The server has encountered the following error(s):
List does not exist. The page you selected contains a list that does not exist. It may have been deleted by another user.
But if delete the item from item popup menu, it is working fine and deleted !!!!
Platform: SharePoint Server 2010 SP1, VS 2010, CU June 2012
Thanks in advance
========================================
Update (My Code to provision web parts)
Dim _web As SPWeb = SPContext.Current.Site.RootWeb
Try
'Get refrence to publishing web
Dim _pubWeb As PublishingWeb = PublishingWeb.GetPublishingWeb(_web)
Dim WPM As Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager
If _pubWeb IsNot Nothing Then
'Loop each publishing page in the web
'Check out the file
'If the current page have CustomWebPart (It is an Custom System Page), Then
'If XsltListViewWebPart is not provisiond (double check in case of click the button more than one time), then
'Create an XsltListViewWebPart
'Assign properties of the new XsltListViewWebPart with Document Lib. Name and Admin web
'Add the new XsltListViewWebPart to the current page in the loop
For Each curPage As PublishingPage In _pubWeb.GetPublishingPages()
If curPage.ListItem.File.RequiresCheckout AndAlso curPage.ListItem.File.CheckOutType = SPFile.SPCheckOutType.None Then curPage.CheckOut()
WPM = curPage.ListItem.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared)
Dim CustomWebPart As CustomWebPart = WPM.WebParts.OfType(Of CustomWebPart)().FirstOrDefault()
If CustomWebPart IsNot Nothing Then
If CustomWebPart.DocLibName.ToLower = Constants.List.MeetingSchedular.ListName.ToLower Then Continue For
Dim web As SPWeb = _web.Site.RootWeb.Webs(Constants.WebNames.AdminWeb) 'Get Admin Web
Dim LVWP As WebPartPages.XsltListViewWebPart = WPM.WebParts.OfType(Of WebPartPages.XsltListViewWebPart)().FirstOrDefault()
If LVWP Is Nothing Then
LVWP = New WebPartPages.XsltListViewWebPart
Dim lst As SPList = web.Lists(CustomWebPart.DocLibName)
With LVWP
.WebId = web.ID
.ViewGuid = lst.DefaultView.ID.ToString("B").ToUpper()
.ListName = lst.ID.ToString("B").ToUpper()
.ListId = lst.ID
.ListUrl = "/Admin/" + CustomWebPart.DocLibName
.TitleUrl = "/Admin/" + CustomWebPart.DocLibName
.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None
.AllowClose = False
.AllowEdit = True
.AllowMinimize = True
.AllowConnect = True
End With
_web.AllowUnsafeUpdates = True
WPM.AddWebPart(LVWP, "MainZone", 0)
curPage.Update()
_web.AllowUnsafeUpdates = False
End If
curPage.CheckIn("By cmdProvisionWebParts_Click")
curPage.ListItem.File.Publish("By cmdProvisionWebParts_Click")
End If
Next
End If
RegisterNotification("Provision Web Parts Completed successfully")
Catch ex As Exception
SiteHelper.WriteErrors("Custom_Settings.ProvisioningRootWebParts", ex)
RegisterNotification("Error: " + ex.Message)
End Try
Maybe, the error happens because your list belongs to another site (or subsite) and SP says you, that it doesn't have the list.
Try to create the list in your site and delete again.
And if it wouldn't work, please show us your XlstViewWebPart code.