Convert vb.net shell to c# - 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 + "\"");

Related

Pass a path with space as an argument

I'm running some code in C# where I call a batch file, and I need to pass a Path with space as an argument and it does not work.
I have tried to call my argument different ways in the batch %1 , %~1, "%1", '%1'. None of these work. Also in my C# code I tried to convert it to string and it wont work either
C# code.
string argument = textBox10.Text.ToString() ;
string command = #"/c powershell -executionpolicy unrestricted X:\PathToBatch\Run.bat" + " " + argument;
System.Diagnostics.Process.Start("cmd.exe", command);
Batch code :
echo %1
Pause
When I pass an argument C:\Program Files\Test as a directory, it prints "C:\Program" and stops at the space.
How can I get the full path ?
Try this :
string command = #"/c powershell -executionpolicy unrestricted X:\PathToBatch\Run.bat"+ " \""+ argument +"\" ";
System.Diagnostics.Process.Start("cmd.exe", command);
This will "write" the following line in your console :
/c powershell -executionpolicy unrestricted X:\PathToBatch\Run.bat "C:\Program Files\Test"
pass your argument double quoted, like so: "C:\Program Files\Test".
the issue is that your argument contains a space so it treated as two different arguments
It worked with simples quotes " '" + arg + "' ", and by calling it in the batch as %~1

userprofile path returns Default while running as a schedule task

I have created following C# console app:
var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path2 = Environment.ExpandEnvironmentVariables("%userprofile%");
File.AppendAllText(#"D:\logs\info.txt", userName + " -- " + path + " -- " + path2);
When I create a scheduled task using Windows Task Scheduler and set the user account to run the task to my account (ht-laptop\huseyin), I am getting the following output in info.txt file:
ht-laptop\huseyin -- C:\Users\Default\Documents -- C:\Users\Default
This seems to be random though, I had seen cases where the printed text was as follows:
ht-laptop\huseyin -- C:\Users\huseyin\Documents -- C:\Users\huseyin
Any idea why this happens?
Are you running this on Windows 8+ (or similar)? If so, this is a known issue with user profile loading. The technote (kb2968540) has a workaround (which is kind of kludgy IMO).

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

Converting VBScript snippet to C#

I have looked through the code but I simply do not have the understanding to know what functions are doing what and how in relation to C# my primary coding language.
Set mSkype = WScript.CreateObject("Skype4COM.Skype", "Skype_")
ContactName=InputBox ("Enter the contact's Skype User Name" & CHR(13) & "Note that this must be the User Name and not the Display Name", "User Name:")
If ContactName = "" Then
WScript.Quit
Else
If mSkype.User(ContactName).FullName="" then
WScript.Echo ("The name " & ContactName & " is not in your Contact List")
WScript.Quit
End If
End If
PictureFileName=InputBox ("Enter the path and name of the Picture" & CHR(13) & "The file extension must be .jpg", "Save Picture as:")
If PictureFileName="" Then
WScript.Quit
End If
cmdStr = "GET USER" & " " & ContactName & " " & "AVATAR 1" & " " & PictureFileName
mSkype.SendCommand mSkype.Command(0, cmdStr)
Oh and I do have skype4com imported and im using that api, that is not the issue with conversion.
InputBox is a window that displays that prompts for input. It is available in VB.NET, and you can actually use it in C# by adding a reference to Microsoft.VisualBasic. See here.
WScript is also not available in VB and it would probably be good to research how to use the Skype plugin in the Skype Developer Forum. Here's a link about how to use the Skype DLL in C#.

How to "End Task" not "Kill" or "Terminate"?

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.)

Categories

Resources