How to "End Task" not "Kill" or "Terminate"? - c#

I have a 3G card to provide internet to a remote computer... I have to run a program(provided with the card) to establish the connection... since connections suddenly is lost I wrote a script that Kills the program and reopens it so that the connection is reestablished, there are certain versions of this program that don't kill the connection when killed/terminated, just when closed properly.
so I am looking for a script or program that "Properly Closes" a window so I can close it and reopen it in case the connection is lost.
this is the code that kills the program
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill
strComputer = "."
strProcessKill = "'Telcel3G.exe'"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
objProcess.Terminate()
Next
WSCript.Echo "Just killed process " & strProcessKill _
& " on " & strComputer
WScript.Quit

If you have to use VBScript, one easy way would be to activate the app and then use SendKeys to restore it if it's minimized and send it "alt-f4". It's hacky, but it may be easier than finding the main window's handle, and it might work well enough for you.
Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill
strComputer = "."
strProcessKill = "'Telcel3G.exe'"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
dim WshShell
set WshShell = CreateObject("WScript.Shell")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
WshShell.AppActivate objProcess.ProcessId
WScript.Sleep 1000
WshShell.Sendkeys "% r"
WScript.Sleep 1000
WshShell.Sendkeys "%{F4}"
Next

As I understand it, the basic idea is to shut the process down cleanly, as opposed to abruptly terminating it. One way would be to post a Windows message to the main window with WM_CLOSE.
(You might be able to simulate this by sending keystrokes corresponding to Alt+F4, but it's best to just send WM_CLOSE.)

Related

How to add programmatically information to an email using VSTO Outlook?

We are currently developing an addin that interact with the end user visually to give some informations, and we wanted to use Mailtips but apparently it is not possible from what we saw
Nevertheless, is it possible to have something similar or to mimic this kind of tip (2nd sshot would be ideal)..
Option 1:
https://i.stack.imgur.com/vcQYb.png
Option 2:
https://i.stack.imgur.com/7k19w.png
We also looked and form region but that would be the last option, ideal would be to have the tooltip in 2nd screenshot to display a small message to help user (any clue appreciated).
We were also looking for a function to disable links in the body (as the junk filter does), but also no chance finding this through the documentation (maybe internal procedure)
Looking everywhere for documented elements...
On the screenshot you have seen a standard Outlook notification and MailTips - that is a feature of Exchange, not Outlook.
We also looked and form region but that would be the last option, ideal would be to have the tooltip in 2nd screenshot to display a small message to help user (any clue appreciated).
The Outlook object model doesn't provide anything for that, there is no built-in property or method for that. The only possible option is to use a form region where you could put your custom UI at the bottom of the standard form/window in Outlook. The Adjoining layout available for Outlook form regions appends the form region to the bottom of an Outlook form's default page. So, if you want to place the form at the top you need to use Windows API functions to subclass Outlook windows or consider using the Advanced Outlook view and form regions where the top layout is provided out of the box.
Also you may consider developing a web add-in for Outlook where you could set up notification items programmatically from the add-in, see Office.NotificationMessages interface for more information. For example:
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/outlook/35-notifications/add-getall-remove.yaml
const id = $("#notificationId").val();
const details =
{
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Non-persistent informational notification message with id = " + id,
icon: "icon1",
persistent: false
};
Office.context.mailbox.item.notificationMessages.addAsync(id, details, handleResult);
See Build your first Outlook add-in to get started quickly on that.
We were also looking for a function to disable links in the body (as the junk filter does), but also no chance finding this through the documentation (maybe internal procedure)
You need to process the message body on your own. The Outlook object model doesn't provide any property or method for that out of the box.
The Outlook object model supports three main ways of customizing the message body:
The Body property returns or sets a string representing the clear-text body of the Outlook item.
The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately.
The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.
You can add a special MAPI property (used by Web addins, DASL name "http://schemas.microsoft.com/mapi/string/{A98A1EF9-FF40-470B-A0D7-4D7DCE6A6462}/WebExtNotifications") to show the notification banner.
Something along the following lines (VBA, you'd need to deselect and select again the currently selected message to see the change):
notificationXml = "<?xml version=""1.0""?>" & vbCrLf & _
"<Apps>"& vbCrLf & _
" <App id=""00000000-0000-0000-0000-000000000000"">"& vbCrLf & _
" <Notifications>"& vbCrLf & _
" <Notification key=""notification"">"& vbCrLf & _
" <type>0</type>"& vbCrLf & _
" <message>Test notification
with two lines</message>"& vbCrLf & _
" </Notification>"& vbCrLf & _
" </Notifications>"& vbCrLf & _
" </App>"& vbCrLf & _
" <App id=""00000000-0000-0000-0000-000000000001"">"& vbCrLf & _
" <Notifications>"& vbCrLf & _
" <Notification key=""notification"">"& vbCrLf & _
" <type>0</type>"& vbCrLf & _
" <message>Another notification</message>"& vbCrLf & _
" </Notification>"& vbCrLf & _
" </Notifications>"& vbCrLf & _
" </App>"& vbCrLf & _
"</Apps>"
set msg = Application.ActiveExplorer.Selection(1)
msg.PropertyAccessor.SetProperty "http://schemas.microsoft.com/mapi/string/{A98A1EF9-FF40-470B-A0D7-4D7DCE6A6462}/WebExtNotifications", notificationXml
msg.Save

Convert vb.net shell to c#

I used this code to create a scheduled task in vb.net, now I'm learning C# and want to make this code to work with C#:
`Shell("schtasks.exe /create /TN " & ChrW(34) & "Updataas\AAMyname task" & ChrW(34) & " /XML " & ChrW(34) & path & ChrW(34))`
You may want to use Process.Start:
Process.Start("schtasks.exe", "/create /TN \"Updataas\\AAMyname task\" /XML \"" + path + "\"");

Get Windows User Display Name

How do I get the display name of the user that is logged in? Not the username, but the display name, such as is shown in the screenshot below - and as seen on the start menu in any Windows Vista/7 computer.
I tried a bunch of different suggestions from other questions, but they all show the username, not the display name. You can see the results of these attempts in the above screenshot.
Imports System.Security.Principal
Imports System.Threading
Imports System.IO
Imports System
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MsgBox("1: " & System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString & vbCrLf & _
"2: " & Environment.UserDomainName & vbCrLf & _
"3: " & WindowsIdentity.GetCurrent().Name & vbCrLf & _
"4: " & Thread.CurrentPrincipal.Identity.Name & vbCrLf & _
"5: " & Environment.UserName & vbCrLf & _
"6: " & My.User.Name & vbCrLf &
"7: " & My.Computer.Name)
End Sub
End Class
You should use UserPrincipal.DisplayName:
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
To do so, you'll need to and add a reference to System.DirectoryServices.AccountManagement.dll from your project.
Note: Doesn't work when machine is unplugged from the network or domain server is not reachable.
Try this
http://msdn.microsoft.com/en-us/library/sfs49sw0(v=vs.110).aspx
using System.IO;
using System;
using System.Security.Principal;
class Program
{
static void Main()
{
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
}
}
This is contained within the System.DirectoryServices namespace so you need to add this in the using section.
Then you can use System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName which returns the Display Name. This is typically shown in the Start Menu.

Process not working when called from a web service VB.NET

I'm writing a program that moves docs from one app to another in ApplicationXtender (AX). The AX full-featured client already has such a program (Migration Wizard) that can handle the task, so I created a function that launches it using Process.Start() and supplying the arguments necessary to automate it. When I call the function from a console app or windows form app, the Migration Wizard works perfectly. But the process must be initiated by an event in a web-based workflow project, so I wrote a web service that contains the same function, and then I use an invoke web service control in the workflow to start it. When I consume the function from the web service, the process doesn't complete. I can see it hanging in the task manager. I'm pretty sure it has to do with the user settings in IIS, but I'm not familiar enough with IIS to make any significant difference. I've configured the anonymous authentication's user identity in IIS to launch with a specific user with full rights to AX, and set the DefaultAppPool to run as Local System, but neither worked. I'm thinking I may need to impersonate the user, but I don't know how to do that. Any suggestions?
For reference, here is my code:
Consume Service Code-
Sub Main()
Dim dbName As String
Dim appName As String
Dim preSalesNum As String
Console.WriteLine("Database: ")
dbName = Console.ReadLine
Console.WriteLine("")
Console.WriteLine("Application")
appName = Console.ReadLine
Console.WriteLine("")
Console.WriteLine("Pre-Sales Number:")
preSalesNum = Console.ReadLine
Console.WriteLine("")
MoveDocs.MoveDocs(dbName, appName, preSalesNum)
End Sub
MoveDocs Function (inside of a separate class)-
Public Shared Function MoveDocs(ByVal dbName As String, ByVal appName As String,
ByVal preSalesNum As String) As String
Try
Dim sourceApp As String
If appName = "PRE_SALES_PROJECTS" Then
sourceApp = "PROJECTS"
Else
sourceApp = "LOOSE-FURNITURE"
End If
Dim argsString As String = "/SD " & dbName & " /SU username /SP password /SA
" & appName & " /DD " & dbName & " /DU username /DP password /DA " &
sourceApp & " /S " & """" & preSalesNum & """" & " /A"
Dim procProp As New System.Diagnostics.ProcessStartInfo
With procProp
.FileName = "C:\Program Files (x86)\XtenderSolutions\Content
Management\MigrateWiz32.exe"
.Arguments = argsString
End With
Dim proc As System.Diagnostics.Process =
System.Diagnostics.Process.Start(procProp)
Return argsString
Catch ex As Exception
Return ex.ToString()
End Try
End Function
The MoveDocs() function in the service.asmx file is identical to the one above, minus the 'shared' modifier in the declaration. The app works, the web service doesn't.
ProcessStartInfo has properties for username, password and domain. There's more info on MSDN -
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.password.aspx

Send/Receive http request/response from MS Word addin

I'm trying to write a add-in for MS Word. Is it possible to for a MS Word add-in to listen on specific port and send/receive http request/response? Will there be a firewall between MS Word and an application that is running outside of Word?
An Office AddIn can make HTTP requests without triggering a firewall issue (using Windows Firewall in its default configuration), but it can't listen without triggering firewall issues.
If you're making requests from inside word to a service you have living outside of Word that service may encounter Firewall issues while listening on a port.
Windows Firewall, by default blocks incoming requests. Windows Firewall is included with all versions of Windows XP SP2 or later.
See MSDN for more.
Additionally,
Function GetRateCBR(dDate As Date) As String
Dim sUrlRequest, intTry As Integer, _
strResponse As String
Dim oXMLHTTP As Object
Dim oResponse As Object
Set oResponse = CreateObject("MSXML2.DOMDocument")
'Build URL for request
sUrlRequest = _
"http://www.cbr.ru/scripts/XML_dynamic.asp?date_req1=" _
& Format(dDate, "dd.mm.yyyy") _
& "&date_req2=" & Format(dDate, "dd.mm.yyyy") _
& "&VAL_NM_RQ=" & "R01235"
'Try to get a response, 10 tries
intTry = 1
Do Until intTry > 10
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.Open "GET", sUrlRequest, False
oXMLHTTP.send
If oXMLHTTP.Status = 200 Then
If oResponse.loadXML(oXMLHTTP.responseText) Then _
Exit Do
End If
If Not oXMLHTTP Is Nothing Then oXMLHTTP.abort: _
Set oXMLHTTP = Nothing
DoEvents
intTry = intTry + 1
Loop
If Not oXMLHTTP Is Nothing Then oXMLHTTP.abort: _
Set oXMLHTTP = Nothing
If intTry <= 10 Then
GetRateCBR = Mid$(oResponse.Text, 3)
End If
If Not oResponse Is Nothing Then oResponse.abort: _
Set oResponse = Nothing
End Function
Example via Access Blog

Categories

Resources