I'm writing a remote log out tool for the school I attend. As system admins, we use it to log out users after our on-campus labs have closed to make sure that all the computers get updates at night. With windows 7, the tool we have now works fine. But we're updating to windows 10 for all of our machines and the tool has mysteriously stopped functioning. It's written in VB.net as of right now (open to a change to c# if needed). Currently we have 2 main functions for the program:
Private Sub LogOut()
Dim AdminAccount As String = txtUsr.Text
Dim AdminDomain As String = txtDomain.Text
Dim AdminPassword As String = txtPwd.Text
Dim ShutDownLocal As String = "c:\bin\"
Dim LogOutProgram As String = "c:\bin\Logout.cmd"
Dim TargetMachine As String = cboDom.Text & ComboBox1.Text & "p" & txtMachine.Text & txtDomain.Text
Dim ShutDownCommand As String = "shutdown -t 300 /r /m \\" & TargetMachine
If RunAs.RunAs(AdminAccount, AdminPassword, AdminDomain, ShutDownCommand, ShutDownLocal) Then
Status.Text = "5 Minute Logout sent to machine"
End If
End Sub
and
Public Shared Function RunAs(ByVal UserName As String, _
ByVal Password As String, _
ByVal DomainName As String, _
ByVal CommandLine As String, _
ByVal StartIn As String) As Boolean
Dim iRet As Integer
Dim si As New STARTUPINFO
Dim pi As PROCESS_INFORMATION
si.cb = Marshal.SizeOf(si)
si.wShowWindow = 0
iRet = CreateProcessWithLogonW(UserName, DomainName, Password, _
LOGON_WITH_PROFILE, Nothing, CommandLine, _
NORMAL_PRIORITY_CLASS, 0, StartIn, si, pi)
If iRet = 0 Then
MessageBox.Show("Password incorrect.", "Error")
Return False
Else
CloseHandle(pi.hThread)
CloseHandle(pi.hProcess)
Return True
End If
End Function
Currently this functions absolutely fine on windows 7 machines but for attempting it on windows 10 machines we either get "access denied(5)" or "The entered computer name is not valid or remote shutdown is not supported on the target computer. Check the name and then try again or contact your system administrator.(53)"
I already checked with the administrator and he said that it is enabled. We use a domain level firewall so the individual computers aren't rejecting the connection. Every machine has the same administrator groups (Which I am using the credentials for every attempt). I'm not sure of any other solutions to look into. Sorry for the wall of text, any solutions can be tested for the most part. No third party software unfortunately.
Thanks!
Related
I'm trying to automatize some Excel reports. Currently I need to retrieve some data from an Essbase Server, in order to achieve this I've created a macro to retrieve and set data in an Excel sheet, my VBA code is the following:
Option Explicit
Declare Function EssVRetrieve Lib "ESSEXCLN.XLL" (ByVal sheetName As Variant, ByVal range As Variant, ByVal lockflag As Variant) As Long
Declare Function EssVConnect Lib "ESSEXCLN.XLL" (ByVal sheetName As Variant, ByVal userName As Variant, ByVal password As Variant, ByVal server As Variant, ByVal application As Variant, ByVal database As Variant) As Long
Declare Function EssVDisconnect Lib "ESSEXCLN.XLL" (ByVal sheetName As Variant) As Long
Sub Essbase_Update_Pulls()
Dim rangeString As String
rangeString = "B3:AC5033"
MsgBox ("Starting macro")
Dim wbSrc As Workbook
Dim m As Variant
Dim mySheetname As Variant, myUserName As Variant, myPassword As Variant, myServer, myApp As Variant, myDB As Variant
Dim lockflag As Integer
Dim myrng As range
Dim x As Integer
Dim y As Integer
Dim z As Integer
Dim strMsgTxt As String
Dim blnRetVal As Boolean
Set wbSrc = ActiveWorkbook
Set myrng = range(rangeString)
lockflag = 1
MsgBox ("Data set")
mySheetname = "Sheet"
myServer = "Server"
myApp = "App"
myDB = "DB"
myUserName = "User"
myPassword = "Pass"
MsgBox ("Trying connection")
x = EssVConnect(mySheetname, myUserName, myPassword, myServer, myApp, myDB)
MsgBox (CStr(x))
If x < 0 Then
blnRetVal = False
strMsgTxt = "Essbase Login - Local Failure"
MsgBox (strMsgTxt)
ElseIf x > 0 Then
blnRetVal = False
strMsgTxt = "Essbase Login - Server Failure"
MsgBox (strMsgTxt)
Else
blnRetVal = True
strMsgTxt = "Success"
MsgBox ("Connection Succeeded")
y = EssVRetrieve(mySheetname, myrng, lockflag)
If y = 0 Then
MsgBox ("Retrieve successful.")
z = EssVDisconnect(mySheetname)
If z = 0 Then
MsgBox ("Disconnect Succeed.")
Else
MsgBox ("Disconnect failed.")
End If
Else
MsgBox ("Retrieve failed.")
End If
End If
End Sub
Variable x is supposed to return the status code (0 is success any other is failed).
So here comes the trick, whenever I run this macro within Excel it runs perfectly, however when I call it from C# using xlApp.Run("Essbase_Update_Pulls"); it returns a status code of -3.
Doing some research I found out that whenever an Excel Application is created in code it doesn't have the add-ins loaded, so they have to be manually loaded
https://community.oracle.com/thread/2480398 .
I iterated over the xlApp.AddIns and found that the "essexcln.xll" was correctly installed so I have no idea what to do now. Also I found out that Add-Ins can be added during runtime but this just causes an exception, here is the source:
http://www.network54.com/Forum/58296/thread/957392331/Visual+Basic-Excel+Api+call+to+Essbase
Found out that excel isn't loading all the dll's and xll's required to connect to de Essbase server. In order to make it work it is necessary to start excel as a process and the acquire the instance and relate it to the interop class. I found the solution here:Excel interop loading XLLs and DLLs. The user pretty much had the same problem but with Bloomberg. I would just add that in the SearchExcelInterop method it needs a Thread.Sleep() to wait for Excel to load properly, in my case it threw a StackOverflowException.
I am trying to convert Excel file to PDF using interop.excel, while executing ExportAsFixedFormat 'publishing' progress bar displays on the site. Is there any way to hide this? I found this issue for Excel files having size above 300KB.
Code is given below:
//(tried using Application instead of ApplicationClass)
Microsoft.Office.Interop.Excel.ApplicationClass excelApplication = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelApplication.ScreenUpdating = false;
excelApplication.DisplayAlerts = false;
excelApplication.Visible = false;
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
return false;
}
var exportSuccessful = true;
try
{
excelApplication.AlertBeforeOverwriting = false;
excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);
}
catch (System.Exception ex)
{
exportSuccessful = false;
}
I can't find any solution. My project is a C# web application.
It took me a few days to figure out, but finally here is a workarround which uses some WinAPI functions to observe windows events. While the hook is active, every new window is compared to whether its class is the same one as the PDF save dialog class. If that's the case, the window gets hidden.
Thanks for solution ideas go to some chinese guys:
http://www.itjie.wang/officebase/516998.html
Usage requirement:
OS (= Operating System) must be Windows because of WinAPI usage.
Warning:
If the "SetWinEventHook" isn't stopped again due to some errors, it is better to restart your system, otherwise you could run into some serious problems with Windows.
Note:
By default, the PDF save dialog doesn't appear regularly. It depends on the time necessary to save the PDF file. If it takes longer the save popup will show up. If it takes shorter the save popup won't show up. Anyway, you don't have to worry about whether the save dialog would appear or not, the code already does this for you.
Instruction:
In your Excel workbook, if you don't already have a module, create a new one (name doesn't matter) & paste following code:
' WINDOWS API FUNCTIONS:
Private Declare Function SetWinEventHook Lib "user32" (ByVal eventMin As Long, ByVal eventMax As Long, ByVal hmodWinEventProc As Long, ByVal pfnWinEventProc As Long, ByVal idProcess As Long, ByVal idThread As Long, ByVal dwFlags As Long) As Long
Private Declare Function UnhookWinEvent Lib "user32" (ByVal hWinEventHook As Long) As Long
Private Declare Function apiGetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassname As String, ByVal nMaxCount As Long) As Long
Private Declare Function apiShowWindow Lib "user32" Alias "ShowWindow" (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
' CONSTANT VARIABLES:
Private Const SW_HIDE = 0
Private Const DLG_CLSID = "CMsoProgressBarWindow"
Private Const EVENT_SYSTEM_FOREGROUND = &H3&
Private Const WINEVENT_OUTOFCONTEXT = 0
' GLOBAL VARIABLES:
Dim long_WinEventHook As Long
Public Function StartEventHook() As Long
long_WinEventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, 0&, AddressOf WinEventFunc, 0, 0, WINEVENT_OUTOFCONTEXT)
StartEventHook = long_WinEventHook
End Function
Public Sub StopEventHook()
Dim b_unhooked As Boolean
If long_WinEventHook = 0 Then
MsgBox "WinEventHook couldn't be stopped! " & _
"Variable 'long_WinEventHook' is empty! " & _
"Better restart Windows now!"
Exit Sub
End If
b_unhooked = UnhookWinEvent(long_WinEventHook)
If b_unhooked = True Then
Else
MsgBox "WinEventHook couldn't be stopped! " & _
"Variable 'b_unhooked' is false! " & _
"Better restart Windows now!"
End If
End Sub
' CALLBACK FUNC OF "SetWinEventHook" (DEFINE ACTIONS TO RUN ON THE EVENTS):
' http://stackoverflow.com/questions/20486944/detecting-in-vba-when-the-window-containing-an-excel-instance-becomes-active
Public Function WinEventFunc(ByVal HookHandle As Long, ByVal LEvent As Long, ByVal hWnd As Long, ByVal idObject As Long, ByVal idChild As Long, ByVal idEventThread As Long, ByVal dwmsEventTime As Long) As Long
'This function is a callback passed to the win32 api
'We CANNOT throw an error or break. Bad things will happen
On Error Resume Next
Dim l_handle As Long
Dim s_buffer As String
Dim b_visible As Boolean
Dim i_bufferLength As Integer
s_buffer = String$(32, 0)
i_bufferLength = apiGetClassName(hWnd, s_buffer, Len(s_buffer))
If Left(s_buffer, i_bufferLength) = DLG_CLSID Then
b_visible = apiShowWindow(hWnd, SW_HIDE)
WinEventFunc = hWnd
End If
End Function
In your VBA code, when you want to save your excel workbook as PDF, you would call above macros like this:
' ADD WINDOWS EVENT HOOK BEFORE SAVING:
Application.Run XL_WB.Name & "!StartEventHook"
' SAVE EXCEL AS PDF:
' https://msdn.microsoft.com/de-de/library/microsoft.office.tools.excel.worksheetbase.exportasfixedformat.aspx
XL_WB.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\PDF.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
' REMOVE WINDOWS EVENT HOOK AFTER SAVING:
Application.Run XL_WB.Name & "!StopEventHook"
In the above VBA code example "XL_WB" is a variable. You have to adjust it to your needs. For example use "ActiveSheet" instead.
From following other websites users also asked for help with that particular problem:
https://social.msdn.microsoft.com/Forums/office/en-US/e6078904-0715-46a2-8937-c38626464425/exportasfixedformat-progress-bar-can-you-hide-it?forum=exceldev
http://www.vbaexpress.com/forum/archive/index.php/t-41431.html
http://www.excelbanter.com/showthread.php?t=446463
...
I need copy a file from server to another server using asp.net/VB.NET for example:
'We copy the original file to the Temp dir
If File.Exists(sFileSource) Then
File.Copy(sFileSource, sFileDest, True)
Else
'The file doesn't exist
End If
But when validate if file exists get that the file doesn't exist, I saw another forum that is a problem of network credentials because the paths are way //192.168.1.10/TemFile/file01.txt.
I have the answer, using a system dll alow connect to oter servers by NetBios
<DllImport("advapi32.DLL", SetLastError:=True)> _
Public Shared Function LogonUser(ByVal lpszUsername As String, ByVal lpszDomain As String, _
ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Integer
End Function
Private _adminToken As IntPtr
Private _widCurrent As WindowsIdentity
Private _widAdmin As WindowsIdentity
Private _wic As WindowsImpersonationContext
Private _admin As AdminShared.AdminManager
If LogonUser(sUser, sDomain, sPassword, 9, 0, _adminToken) <> 0 Then
_widAdmin = New WindowsIdentity(_adminToken)
_wic = _widAdmin.Impersonate()
File.Copy(sFileSource, sFileDest)
Else
I'm developing an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS.
I want to get the device name using code lines.
Any one have an idea on this ?
Note : I'm working with VS2008 using C# on win7.
private const string IDENTITY = #"HKEY_LOCAL_MACHINE\Ident";
private const string NAME = "Name";
string DeviceName = (string)Registry.GetValue(IDENTITY, NAME, "NAME");
We developed an application for the same device, we used this sentense to get device name.
Private Sub deviceidt_ParentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deviceidt.ParentChanged
Dim deviceidn As String = System.Net.Dns.GetHostName
deviceidt.Text = deviceidn
End If
End Sub
I'm trying to delete an user in Active Directory via C#.When I attempt to run the following the code,I got an error.
Error Message:
A local error has occurred
Code:
DirectoryEntry ent = new DirectoryEntry("LDAP://192.168.1.99/OU=FIRMA");
ent.Username = "idm\administrator";
ent.Password = "123123QQ";
DirectorySearcher dsrc = new DirectorySearcher(ent);
dsrc.Filter = string.Format("(&(objectCategory=user)(SAMAccountName=adKullaniciadi))");
DirectoryEntry silsunuya = ent.Children.Find("CN=adKullaniciadi","objectClass=person");
ent.Children.Remove(silsunuya);
ent.Close();
silsunuya.Close();
dsrc.Dispose();
I have an ASP.Net website running local that our IT team uses to delete AD accounts, and it seems to work ok. I remember when I was developing this application there were a lot of nuances I had to deal with, which can make it painful to figure out what's going on with AD. Here is the code I am using (in VB.Net):
Public Shared Function GetUser(ByVal username As String) As DirectoryEntry
If String.IsNullOrEmpty(username) Then Return Nothing
Dim path As String = ConfigurationManager.ConnectionStrings("ADConnectionString").ConnectionString
Dim ds As New DirectorySearcher(path)
ds.Filter = "(&(objectClass=user)(sAMAccountName=" + username + "))"
ds.PropertiesToLoad.Add("sAMAccountName") ' username
ds.PropertiesToLoad.Add("mail") ' e-mail address
ds.PropertiesToLoad.Add("description") ' Bureau ID
ds.PropertiesToLoad.Add("company") ' company name
ds.PropertiesToLoad.Add("givenname") ' first name
ds.PropertiesToLoad.Add("sn") ' last name
ds.PropertiesToLoad.Add("name") ' client name
ds.PropertiesToLoad.Add("cn") ' common name
ds.PropertiesToLoad.Add("dn") ' display name
ds.PropertiesToLoad.Add("pwdLastSet")
ds.SearchScope = SearchScope.Subtree
Dim results As SearchResult = ds.FindOne
If results IsNot Nothing Then
Return New DirectoryEntry(results.Path)
Else
Return Nothing
End If
End Function
Public Shared Sub DeleteUser(ByVal username As String, Optional ByVal useImpersonation As Boolean = False)
Dim user As DirectoryEntry = GetUser(username)
Dim ou As DirectoryEntry = user.Parent
ou.Children.Remove(user)
ou.CommitChanges()
End Sub
Looking at your code, here are some ideas that come to mind:
Try using dsrc.PropertiesToLoad.Add("sAMAccountName")
Try adding a call to ent.CommitChanges()
Can you verify the path and credentials are correct, say, using a command-line AD query tool?
Can you determine specifically what line the error occurs on?