Is there a way to detect from an application written in c# if it's being launched as a remote app using RDP?
Get the parent of your application's process and check if it's raised by rdpinit.exe. If so, it's a RemoteApp.
Quick example for getting the parent-process-id (sorry, vb.net):
<Extension()>
Public Function GetParentProcessId(process As Process) As Integer
If process Is Nothing Then Throw New NullReferenceException()
Dim parentProcessId As Integer
Dim snapShot As IntPtr = IntPtr.Zero
Try
snapShot = CreateToolhelp32Snapshot(SnapshotFlags.Process, 0)
If snapShot <> IntPtr.Zero Then
Dim procEntry As New PROCESSENTRY32
procEntry.dwSize = CUInt(Marshal.SizeOf(GetType(PROCESSENTRY32)))
If Process32First(snapShot, procEntry) Then
Do
If process.Id = procEntry.th32ProcessID Then
parentProcessId = CInt(procEntry.th32ParentProcessID)
Exit Do
End If
Loop While Process32Next(snapShot, procEntry)
End If
End If
Catch ex As Exception
Throw
Finally
If snapShot <> IntPtr.Zero Then
CloseHandle(snapShot)
End If
End Try
Return parentProcessId
End Function
Now you can get the parent-process easily.
Regards,
Jan
Related
My VB.NET winforms app runs a timer which creates a background worker to update the objects in an ObjectListView.
In the timer loop, a number of 'device' objects are added to an observable collection (in the backgroundworker_progresschanged event) and (in the backgroundworker_complete event), I use an OLV.SetObjects(allDevices, true) to populate them.
This all works flawlessly. However, the currently selected items in the OLV are lost during the OLV.setobjects so I need to restore them.
To do this, (in the backgroundworker_complete event), I want to access the selecteditems property of the OLV but I keep getting a "Cross-thread operation not valid: Control 'DeviceListView1' accessed from a thread other than the thread it was created on." All attempts at trying to read the selected listviewitems (either by OLV.selecteditems or a loop reading them from the OLV) fail with the cross-thread exception.
I may misunderstand but I thought I could access GUI elements on the backgroundworker_progresschanged and backgroundworker_complete events?
Here's the relevant code:
The PopulateDevices sub is called when the timer is started and will not run again until a specific time has passed. It runs the RunWorkerAsync of the Worker.
Public Sub PopulateDevices()
' Debug
_UpdateCount += 1
' Pause the Update Timer
UpdateTimer.Stop()
' Get the Starting Time of this Update
StartTime = DateTime.Now
' Stop updating the DeviceListView1 ObjectListView
ControlHelper.ControlInvoke(DeviceListView1, Sub() DeviceListView1.BeginUpdate())
' Clear Existing Devices from the List
AllDevices = New TrulyObservableCollection(Of DeviceItem)
' Get the selected devices
'_SelectedDevices = GetSetSelectedDevices(DeviceListView1)
' Prep the BackgroundWorker
PopulateDevicesWorker = New BackgroundWorker
PopulateDevicesWorker.WorkerReportsProgress = True
' Add the Event Handlers
AddHandler PopulateDevicesWorker.DoWork, AddressOf PopulateDevicesWorkerDoWork
AddHandler PopulateDevicesWorker.ProgressChanged, AddressOf PopulateDevicesWorkerProgressChanged
AddHandler PopulateDevicesWorker.RunWorkerCompleted, AddressOf PopulateDevicesWorkerCompleted
' Start the BackgroundWorker
If Not PopulateDevicesWorker.IsBusy Then
PopulateDevicesWorker.RunWorkerAsync()
End If
End Sub
The worker will read a list of devices from a SQLite DB and (in the progresschanged event) populate an observable collection (AllDevices):
Private Sub PopulateDevicesWorkerDoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
' We only continue if the \Clients\_Cache File exists and can be read
If Not File.Exists(CacheFilePath) Then
Exit Sub
End If
' Create a new SQLite Connection & Connect to database
Dim DBC As SQLiteDatabase = OpenDB(CacheFilePath)
If Not IsNothing(DBC) Then
' Count the Rows in the \Clients\_Cache file
Dim RowCount As Integer = CountTableRows(DBC, "_Cache")
' Set the SQL Query
SqlQuery = "SELECT * FROM _Cache WHERE Archived = #Archived"
' Create the SQLite Command
Using SQLitecmd As SQLiteCommand = New SQLiteCommand(SqlQuery, DBC.Connection)
SQLitecmd.Parameters.AddWithValue(String.Empty & "Archived", IIf(fMain.ButtonItem_VIEWARCHIVE.Checked, "True", "False"))
Using SQLiteReader = SQLitecmd.ExecuteReader()
Dim Counter As Integer = 0
' Read All Properties into the Array
While SQLiteReader.Read()
Using DeviceItem As New DeviceItem
With DeviceItem
' Get the Device Info here
End With
' Report progress at regular intervals
PopulateDevicesWorker.ReportProgress(CInt(100 * Counter / RowCount), DeviceItem)
' Increment the Counter (for Progress)
Counter += 1
End Using
End While
End Using
End Using
End If
CloseDB(DBC)
End Sub
Here is the WorkerProgressChanged event. It adds the current device (from the worker) into the observable collection (AlLDevices)
Private Sub PopulateDevicesWorkerProgressChanged(sender As Object, e As ProgressChangedEventArgs)
' Update Status
LabelItem_STATUS.Text = "Working.. (" & e.ProgressPercentage & "%)"
' Add the Device to Collection
AllDevices.Add(TryCast(e.UserState, DeviceItem))
End Sub
The WorkerCompleted event will set the objects in AllDevices to the OLV (DeviceListView1)
Private Sub PopulateDevicesWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) ' Handles PopulateDevicesWorker.RunWorkerCompleted
' This is producing Cross-Thread error
If Not IsNothing(_SelectedDevices) Then
For Each item As ListViewItem In _SelectedDevices
Debug.Print(item.Text)
Next
End If
' Populate the ObjectListView
ControlHelper.ControlInvoke(DeviceListView1, Sub() DeviceListView1.SetObjects(AllDevices, True))
' Re-enable Form Updates
ControlHelper.ControlInvoke(DeviceListView1, Sub() DeviceListView1.EndUpdate())
' If the refresh rate isn't already set, set it to the time taken to complete the Update PLUS the Seconds specified in the SETTINGS.INI File
Dim difference As TimeSpan = DateTime.Now.Subtract(StartTime)
If UpdateTimeInSeconds = -1 Then
UpdateTimer.Interval = (RefreshRate + difference.TotalSeconds) * 1000
End If
' Restart the Update Timer
UpdateTimer.Start()
End Sub
I was under the impression, that I can update the GUI (get the OLV selecteditems, etc.) from the WorkerProgressChanged and WorkerCompleted backgroundworker events but I get the darn cross-thread error.
I'm also having to INVOKE the BEGIN\END UPDATE as calling them directly produces error.
I have read that the olv.setobjects in ObjectListView 2.91 (the version I am using) should persist the selections but I haven't seen this at all.
Please! What am I missing? Its probably something daft or is there another way of doing this?
If you are not using a Forms.Timer (but Timers.Timer or Threading.Timer) for your UpdateTimer, anything called from the timer "tick" event will run on a different thread.
Thus, PopulateDevices would also be called from a non GUI thread and the BackgroundWorker will run on that thread as well.
Firstly, new thread born independently of my code by external factory.
I have something integer key variable - "CODE". This variable "CODE" I received as result of a lot of calculating and request to DB (and maybe I need multi-threading protection of this "CODE").
I need lock thread only for the same "CODE", if currently "CODE" is handling now, thread with other "CODE" can not locking and handling without obstacle.
Thread with "CODE" now handling and locking need to immediately finish.
Also all this function must be working asynchronously with ASYNC/AWAIT.
I am using .NET Core 6.
It looks like a very common task, but what mechanism do I need to use?
Does code template for this task exist in inet?
This is my solution, but I'm not sure how it working with high uploading. I only try to test this code with high concurrency. If anybody has advice for me, please.
I realize solution with ConcurrentDictionary and locking critical section. To unlock main locker and using secondary locker I created new task.
This is schema of my solution.
Public Sub New(ByVal logger As ILogger(...)
....
WorkingServer = New ConcurrentDictionary(Of Integer, BashJob)()
WorkingVm = New ConcurrentDictionary(Of Integer, BashJob)()
End Sub
Private WorkingServer As ConcurrentDictionary(Of Integer, BashJob)
Private RequestNextJob As New Object
Public Async Function Execute(context As IJobExecutionContext) As Task Implements IJob.Execute
_logger.LogInformation($"Time {Now}")
Interlocked.Increment(Counter)
SyncLock RequestNextJob
' calculate CODE hidden in NextJob
...
Dim NextJob As BashJob = Res1.Result.Item1(0)
Dim Val1 As BashJob
Dim ServerWorking As Boolean = WorkingServer.TryGetValue(NextJob.toServer, Val1)
If Not ServerWorking Then
Dim AddSucess1 = WorkingServer.TryAdd(NextJob.toServer, NextJob)
If AddSucess1 Then
Dim ServerThread = New Thread(Sub() ServerJob(NextJob, New ServerClosure))
ServerThread.Start()
Else
Exit Function
End If
Else
Exit Function
End If
End SyncLock
End Function
Async Sub ServerJob(ByVal Prm As BashJob, ByVal Closure As ServerClosure)
Try
Closure.Res = Sql.ExecNonQuery(...)
...
'main processor
...
WorkingServer.TryRemove(Prm.toServer, Prm)
Catch ex As Exception
_logger.LogInformation($"ServerSsh ({Counter.ToString}) {Now.ToString} Server:{Prm.toServer} {Prm.i}:[{Prm.Command}] GettingError {ex.Message}")
Finally
WorkingServer.TryRemove(Prm.toServer, Prm)
End Try
End Sub
End Class
Public Class ServerClosure
Property Res As Integer
Property Server As ServerBashAsync
Property Connect As Tuple(Of Renci.SshNet.SshClient, Exception, Exception)
Property BashRet As Task(Of String)
Property IsCompleted As Integer
Property IsCompletedWithErr As Integer
End Class
I use VBA to automate an external application that recently changed their COM API. The new API loads files asynchronously (used to be synchronous) so I need to wait for the file loaded trigger before I continue when I try to load a file.
I have tried the methods listed on the Microsoft website (EX1, EX2) which were also part of an accepted answer on StackOverflow.
Below is the code I have in a class module named UCExternal to contain the external application object:
Public WithEvents obj As External.Application
Private fileLoaded As Boolean
Private Sub obj_OnFileLoaded(ByVal lLayer As Long, ByVal strUNCPath As String)
Debug.Print lLayer
Debug.Print strUNCPath
fileLoaded = True
End Sub
Public Sub LoadSingleFile(fileStr As String)
fileLoaded = False
obj.LoadFile 0, fileStr
Do
DoEvents
Loop Until fileLoaded
End Sub
And then this is what I had in a normal code module to run using a button on the sheet:
Sub TryLoadFile()
Dim extObj as New UCExternal
set extObj.obj = CreateObject("External.Application")
filePath = "path/to/file"
extObj.LoadSingleFile filePath
End Sub
The event code never seems to fire and instead the Do Loop just runs until Excel crashes. I don't know if there is a way to confirm the application actually sent the event trigger? I have read through the new documentation for the application and that is the event they say to wait for. I have reached out to them for help as well but I wasn't sure if there was something more general I may have been missing. I have not worked with events external to Excel in the past. If I just step through it using the debugger and manually exit the Do Loop eventually the rest of the code that works on the loaded file works as well, so it does load the file.
extObj needs to be declared outside of TryLoadFile, or it will go out of scope and get cleared as soon as TryLoadFile completes
Dim extObj as New UCExternal
Sub TryLoadFile()
Set extObj = New UCExternal
set extObj.obj = CreateObject("External.Application")
filePath = "path/to/file"
extObj.LoadSingleFile filePath
End Sub
This is more of general question, I suppose, as-well-as help with a specific line of code.
I have an Excel file that I was working on just a few days ago that was working fine, however now whenever I try to run the macro in the workbook to pull data from a website, I receive the error "Run-time error '380': A script engine for the specified language can not be created."
Here is the code block where I am running into the issue. I have starred the specific section where the error is thrown.
Dim H As Object, S As Object, jParse As Object, X64 As Object, i&
Set H = CreateObject("WinHTTP.WinHTTPRequest.5.1")
H.SetAutoLogonPolicy 0
#If Win64 Then
Set X64 = x64Solution()
X64.execScript "Function CreateObjectx86(sProgID) Set CreateObjectx86 = CreateObject(sProgID): End Function", "VBScript"
Set S = X64.CreateObjectx86("MSScriptControl.ScriptControl")
#Else
Set S = CreateObject("ScriptControl")
#End If
***S.Language = "JScript"***
S.AddCode "function keys(O) { var k = new Array(); for (var x in O) { k.push(x); } return k; } "
I have never seen this error before and I am not sure how to fix this issue. I have looked online and have thus far been unsuccessful in figuring out the problem. I have also tried downloading and installing the zip file from Microsoft in this link: https://gallery.technet.microsoft.com/scriptcenter/Registry-key-to-re-enable-835fba77 with no success.
Any help would be appreciated, because I really don't know what to do here.
Also if Stack Overflow is not really the place for this kind of question, any help in directing me somewhere that would be better suited for this kind of problem would be appreciated.
I just had a similar encounter attempting to use JScript to parse some JSON from the SO API using a x64 machine.
Disclaimer: I did not author the following procedures, but unfortunately I do not have the source of where I obtained them either.
As you've probably already figured out, MSScriptControl.ScriptControl doesn't like the x64 architecture very well. Here are a couple of functions that will allow you to do what you need.
I placed these in a separate module:
Public Function CreateObjectx86(Optional sProgID, Optional bClose = False)
Static oWnd As Object
Dim bRunning As Boolean
#If Win64 Then
bRunning = InStr(TypeName(oWnd), "HTMLWindow") > 0
If bClose Then
If bRunning Then oWnd.Close
Exit Function
End If
If Not bRunning Then
Set oWnd = CreateWindow()
oWnd.execScript "Function CreateObjectx86(sProgID): Set CreateObjectx86 = CreateObject(sProgID): End Function", "VBScript"
End If
Set CreateObjectx86 = oWnd.CreateObjectx86(sProgID)
#Else
Set CreateObjectx86 = CreateObject(sProgID)
#End If
End Function
Private Function CreateWindow()
Dim sSignature, oShellWnd, oProc
On Error Resume Next
sSignature = Left(CreateObject("Scriptlet.TypeLib").GUID, 38)
CreateObject("WScript.Shell").Run "%systemroot%\syswow64\mshta.exe about:""about:<head><script>moveTo(-32000,-32000);document.title='x86Host'</script><hta:application showintaskbar=no /><object id='shell' classid='clsid:8856F961-340A-11D0-A96B-00C04FD705A2'><param name=RegisterAsBrowser value=1></object><script>shell.putproperty('" & sSignature & "',document.parentWindow);</script></head>""", 0, False
Do
For Each oShellWnd In CreateObject("Shell.Application").Windows
Set CreateWindow = oShellWnd.GetProperty(sSignature)
If Err.Number = 0 Then Exit Function
Err.Clear
Next
Loop
End Function
Then you can go back to your S object and set it this way:
Dim S As Object
Set S = CreateObjectx86("MSScriptControl.ScriptControl")
S.Language = "JScript"
In the code below, StartSocketListener has been started as a Thread. Sometimes, the processing of a message takes long enough that a couple of messages stack up (or at least that appears to be the case). I thought I'd take the socket and start another thread with it. I thought that passing the _HostConnection into the task would make concurrent instances of MessageFunction thread safe. Not so, it appears. I regularly get two kinds of errors: one is at _HostReader.ReadString, where I either read past the end of the stream or read only a portion of the stream (as if something else has consumed part of it). The other is at _HostWriter.Write, where I get "an established connection was aborted." Is it obvious where I've failed to get the thread safety that I was expecting? [I am a C# developer, so the VB lambda may look awkward :) ]
Private Sub StartSocketListener()
Dim _Listener As TcpListener = Nothing
Dim _HostConnection As Socket
Try
_Listener = New TcpListener(IPAddress.Parse(GetIPAddress), _TCPListenerPort)
_Listener.Start()
While _KeepListening
_HostConnection = _Listener.AcceptSocket
Dim MessageFunction = Sub(socket As Socket)
Dim _ClientIP As String = socket.RemoteEndPoint.ToString
Dim _HostSocketStream As NetworkStream = New NetworkStream(socket)
Dim _HostWriter As BinaryWriter = New BinaryWriter(_HostSocketStream)
Dim _HostReader As BinaryReader = New BinaryReader(_HostSocketStream)
Try
Dim _MsgXML As String = _HostReader.ReadString
If _MsgXML.Trim <> "" Then
If _KeepListening Then
Dim _RetXML As String = ProcessMessage(_MsgXML, _ClientIP)
Try
_HostWriter.Write(_RetXML)
Catch ex As Exception
...
End Try
End If
End If
Catch ex As Exception
...
End Try
_HostReader.Close()
_HostWriter.Close()
_HostSocketStream.Close()
socket.Close()
End Sub
Task.Factory.StartNew(Sub() MessageFunction(_HostConnection))
End While
_Listener.Stop()
Catch ex As Exception
....
End Try
End Sub