I'm using a suite of WatiN tests driving IE to do some periodic sanity checking for the purposes of monitoring a site.
The suite works fine when I invoke it interactively and/or when I configure the task in Task Scheduler to "Run only when the user is logged on".
However, when I set it to "Run whether the user is logged on or not", and check the "Run with highest privileges" option (WatiN can't talk to the browser satisfactorily under Windows Server 2008 and many other OSes without having admin privileges), WatiN can't communicate with it's iexplore.exe instances satisfactorily (they start, but I get a timeout exception as detailed in this post). I have added the site I'm hitting to the Trusted sites for both admin and non-admin contexts of IE. I've tried with and without elevation, with and without disabling ESC and with and with and without turning off Protected Mode for the internet zone. As my non-GUI tests are happy, I assume it's a limitation of the type of interactivity that's possible in the context of a non-interactive Scheduled Task, even when "Run with highest privileges".
Right now, my temporary workaround is to require a [TS] session to remain open at all times, ready to run the scheduled task.
If I was to persist with this, I'd at a minimum add a heartbeat notification to allow something to monitor that the task is actually getting to run [e.g., if someone logs the session off or reboots the box].
However, I'm looking for something more permanent -- something that is capable of regularly invoking my WatiN tests [run using xunit-console.x86.exe v 1.5] on my Windows Server 2008 [x64] box, just like Task Scheduler but with a proper Interactive session.
I'd prefer not to use psexec or remcom if possible, and can't see how creating a Windows Service would do anything other than add another point of failure but I'd be interested to hear of all proven solutions out there.
I was able to run Watin tests using Scheduled Task in the "Run whether user is logged on or not" mode.
In my case I tracked the issue down to m_Proc.MainWindowHandle being always 0 when IE is created from a scheduled task running without a logged on user.
In Watin sources this is in the IE.cs:CreateIEPartiallyInitializedInNewProcess function
My workaround is to manually enumerate top level windows and find a window with className == "IEFrame" that belongs to the process instead of using Process.MainWindowHandle property.
Here is the code snippet. All pinvoke i copied directly from Watin source.
public static class IEBrowserHelper
{
private static Process CreateIExploreInNewProcess()
{
var arguments = "about:blank";
arguments = "-noframemerging " + arguments;
var m_Proc = Process.Start("IExplore.exe", arguments);
if (m_Proc == null) throw new WatiN.Core.Exceptions.WatiNException("Could not start IExplore.exe process");
return m_Proc;
}
class IeWindowFinder
{
#region Interop
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32", EntryPoint = "GetClassNameA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
internal static extern int GetClassName(IntPtr handleToWindow, StringBuilder className, int maxClassNameLength);
#endregion
readonly Process IeProcess;
IntPtr HWnd = IntPtr.Zero;
public IeWindowFinder(Process ieProcess)
{
this.IeProcess = ieProcess;
}
public IntPtr Find()
{
EnumWindows(FindIeWindowCallback, IntPtr.Zero);
return HWnd;
}
bool FindIeWindowCallback(IntPtr hWnd, IntPtr lParam)
{
uint processId;
GetWindowThreadProcessId(hWnd, out processId);
if (processId == IeProcess.Id)
{
int maxCapacity = 255;
var sbClassName = new StringBuilder(maxCapacity);
var lRes = GetClassName(hWnd, sbClassName, maxCapacity);
string className = lRes == 0 ? String.Empty : sbClassName.ToString();
if (className == "IEFrame")
{
this.HWnd = hWnd;
return false;
}
}
return true;
}
}
public static WatiN.Core.IE CreateIEBrowser()
{
Process ieProcess = CreateIExploreInNewProcess();
IeWindowFinder findWindow = new IeWindowFinder(ieProcess);
var action = new WatiN.Core.UtilityClasses.TryFuncUntilTimeOut(TimeSpan.FromSeconds(WatiN.Core.Settings.AttachToBrowserTimeOut))
{
SleepTime = TimeSpan.FromMilliseconds(500)
};
IntPtr hWnd = action.Try(() =>
{
return findWindow.Find();
});
ieProcess.Refresh();
return WatiN.Core.IE.AttachTo<WatiN.Core.IE>(
new WatiN.Core.Constraints.AttributeConstraint("hwnd", hWnd.ToString()), 5);
}
}
then instead of new IE() use IEBrowserHelper.CreateIEBrowser()
From the command-prompt, you can schedule an interactive task like this:
C:\Users\someUser>schtasks /create /sc once /st 16:28 /tn someTask /tr cmd.exe
... where sc is the schedule, st is the start-time, tn is the taskname you choose (can be anything), and tr is the command you want to run. Obviously, for a recurring task, you would change sc to monthly, weekly, etc. Just type "schtasks /create /?" for more info.
Related
The goal is
I want to change the opacity of some application (target) running on win xp.
The situation
I logged in win xp as AD (active dir) user account (some-domain\username)
most of the target applications are run as local user or another ad user
The problem and my Question
SetWindowLong & SetLayeredWindowAttributes doesn't work on target application that run as other user account. But it works on target application that runs under the same user account (logged user account)
How to change other app's window opacity that run as different user account?
Illustration app
It's a win form app (let's call it OpaciToggler.exe). I have 2 buttons (btnRunSomething and btnHideThatThing) and a textbox (txtPid). As simple as that.
When I click the btnRunSomething, it run an .exe as different user. All the details is in the app.config. In this case I run this application (OpaciToggler.exe, from the debug/bin) as different user (localComputer\user1)
The txtPid is for manual pid input. Usually I open the task manager (win > run > taskmgr) and find the pid (under the process tab) of any application (target) I want to test with, then type it here.
When I click the btnHideThatThing, it'll toggle the opacity of the target application (whose pid in the txtPid)
Code C#
This is how I call the target app.
private void btnRunSomething_Click(object sender, EventArgs e)
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.Domain = ConfigurationManager.AppSettings["StartInfoDomain"];
p.StartInfo.UserName = ConfigurationManager.AppSettings["StartInfoUserName"];
p.StartInfo.FileName = ConfigurationManager.AppSettings["StartInfoFileName"];
p.StartInfo.Arguments = ConfigurationManager.AppSettings["StartInfoArguments"];
System.String rawPassword = ConfigurationManager.AppSettings["StartInfoPassword"];
System.Security.SecureString encPassword = new System.Security.SecureString();
foreach (System.Char c in rawPassword)
{
encPassword.AppendChar(c);
}
p.StartInfo.Password = encPassword;
p.StartInfo.UseShellExecute = false;
p.Start();
}
This is how I try to call the opacity thing
private void btnHideThatThing_Click(object sender, EventArgs e)
{
// manual input pid
int pid = int.Parse(txtPid.Text);
IntPtr mwh = Process.GetProcessById(pid).MainWindowHandle;
doHideThing(mwh);
// doHideThing(Process.GetProcessById(int.Parse(txtPid.Text)).MainWindowHandle);
}
The hide method
private void doHideThing(IntPtr hndl)
{
SetWindowLong(hndl, GWL_EXSTYLE, GetWindowLong(hndl, GWL_EXSTYLE) ^ WS_EX_LAYERED).ToString();
// _whatNow = Marshal.GetLastWin32Error();
SetLayeredWindowAttributes(hndl, 0, (255 * 20) / 100, LWA_ALPHA).ToString();
// _whatNow = Marshal.GetLastWin32Error();
RedrawWindow(hndl, IntPtr.Zero, IntPtr.Zero,
RedrawWindowFlags.Erase | RedrawWindowFlags.Invalidate |
RedrawWindowFlags.Frame | RedrawWindowFlags.AllChildren);
}
other codes
private const int GWL_EXSTYLE = -20;
private const int GWL_STYLE = -16;
private const int WS_EX_LAYERED = 0x80000;
private const int LWA_ALPHA = 0x2;
private const int LWA_COLORKEY = 0x1;
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
static extern bool RedrawWindow(IntPtr hWnd, IntPtr lprcUpdate, IntPtr hrgnUpdate, RedrawWindowFlags flags);
RedrawWindowFlags enum (I don't remember where I get this)
[Flags()]
enum RedrawWindowFlags : uint
{
/// <summary>
/// Invalidates the rectangle or region that you specify in lprcUpdate or hrgnUpdate.
/// You can set only one of these parameters to a non-NULL value. If both are NULL, RDW_INVALIDATE invalidates the entire window.
/// </summary>
Invalidate = 0x1,
/// <summary>Causes the OS to post a WM_PAINT message to the window regardless of whether a portion of the window is invalid.</summary>
InternalPaint = 0x2,
/// <summary>
/// Causes the window to receive a WM_ERASEBKGND message when the window is repainted.
/// Specify this value in combination with the RDW_INVALIDATE value; otherwise, RDW_ERASE has no effect.
/// </summary>
Erase = 0x4,
/// <summary>
/// Validates the rectangle or region that you specify in lprcUpdate or hrgnUpdate.
/// You can set only one of these parameters to a non-NULL value. If both are NULL, RDW_VALIDATE validates the entire window.
/// This value does not affect internal WM_PAINT messages.
/// </summary>
Validate = 0x8,
NoInternalPaint = 0x10,
/// <summary>Suppresses any pending WM_ERASEBKGND messages.</summary>
NoErase = 0x20,
/// <summary>Excludes child windows, if any, from the repainting operation.</summary>
NoChildren = 0x40,
/// <summary>Includes child windows, if any, in the repainting operation.</summary>
AllChildren = 0x80,
/// <summary>Causes the affected windows, which you specify by setting the RDW_ALLCHILDREN and RDW_NOCHILDREN values, to receive WM_ERASEBKGND and WM_PAINT messages before the RedrawWindow returns, if necessary.</summary>
UpdateNow = 0x100,
/// <summary>
/// Causes the affected windows, which you specify by setting the RDW_ALLCHILDREN and RDW_NOCHILDREN values, to receive WM_ERASEBKGND messages before RedrawWindow returns, if necessary.
/// The affected windows receive WM_PAINT messages at the ordinary time.
/// </summary>
EraseNow = 0x200,
Frame = 0x400,
NoFrame = 0x800
}
Example, Test and Test Result
logged in win xp as domainA\ad_user1
run the OpaciToggler.exe application (Instance1, run as domainA\ad_user1)
Then I click the run something. It opens another OpaciToggler.exe (Instance2), runs as another user account (run as localcomputer\l_user1) OR right click the .exe then click run as..
Instance1
pid: 1234
run as: domainA\ad_user1
txtPid: 5678 (Instance2, doesn't work)
txtPid: 1234 (self, works)
txtPid: any pid run as the same account (ex: notepad.exe, calc.exe, etc, works)
Instance2
pid: 5678
run as: localcomputer\l_user1
txtPid: 1234 (Instance 1, doesnt work)
txtPid: 5678 (self, works)
txtPid: any pid run as the same account (localcomputer\l_user1) (ex: notepad.exe, calc.exe, etc, doesn't work!!)
Again, my Question
How to change other app's window opacity that run as different user account?
Thanks and sorry for my bad English :(.
Hi,
We have a winform application that is only to be executed as a singelton, If a second instance try to start this new instance will connect to the current and transmit parameters over namedpipes.
The problem is that when starting the first instance there will be a try to connect to existing host. If the host is not existing(like in this case) an exception will be thrown. There is no problem to handle this exception but our developers is often using "Break on Exception" and that means that every time we startup the application the developer will get two(in this case) breaks about exception. Thay will have to hit F5 twice for every start.
Is there any way to check if the service is available without throw exception if its not?
BestRegards
Edit1:
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenFileMapping(uint dwDesiredAccess, bool bInheritHandle, string lpName);
The following code says : Error 152 Cannot implicitly convert type 'System.IntPtr' to 'Orbit.Client.Main.Classes.Controllers.MyClientController.SafeFileMappingHandle'
using (SafeFileMappingHandle fileMappingHandle
= OpenFileMapping(FILE_MAP_READ, false, sharedMemoryName))
{
If there is already a WCF server listening on the named pipe endpoint, there will be a shared memory object created, via which the server publishes the actual name of the pipe. See here for details of this.
You can check for the existence of this shared memory object with code something like the following, which will not throw, just return false, if there is no server running already. (I've extracted this from code I already have working, and then edited it to do what you want - but without testing the edited version, so apologies if you have to fix up assembly/namespace refs etc to get it running.)
public static class ServiceInstanceChecker
{
public static bool DoesAServerExistAlready(string hostName, string path)
{
return IsNetNamedPipeSharedMemoryMetaDataPublished(DeriveSharedMemoryName(hostName, path));
}
private static string DeriveSharedMemoryName(string hostName, string path)
{
StringBuilder builder = new StringBuilder();
builder.Append(Uri.UriSchemeNetPipe);
builder.Append("://");
builder.Append(hostName.ToUpperInvariant());
builder.Append(path);
byte[] uriBytes = Encoding.UTF8.GetBytes(builder.ToString());
string encodedNameRoot;
if (uriBytes.Length >= 0x80)
{
using (HashAlgorithm algorithm = new SHA1Managed())
{
encodedNameRoot = ":H" + Convert.ToBase64String(algorithm.ComputeHash(uriBytes));
}
}
else
{
encodedNameRoot = ":E" + Convert.ToBase64String(uriBytes);
}
return Uri.UriSchemeNetPipe + encodedNameRoot;
}
private static bool IsNetNamePipeSharedMemoryMetaDataPublished(string sharedMemoryName)
{
const uint FILE_MAP_READ = 0x00000004;
const int ERROR_FILE_NOT_FOUND = 2;
using (SafeFileMappingHandle fileMappingHandle
= OpenFileMapping(FILE_MAP_READ, false, sharedMemoryName))
{
if (fileMappingHandle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
if (ERROR_FILE_NOT_FOUND == errorCode) return false;
throw new Win32Exception(errorCode); // The name matched, but something went wrong opening it
}
return true;
}
}
private class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SafeFileMappingHandle() : base(true) { }
public SafeFileMappingHandle(IntPtr handle) : base(true) { base.SetHandle(handle); }
protected override bool ReleaseHandle()
{
return CloseHandle(base.handle);
}
}
}
The host name and path you pass in are derived from the WCF service url. Hostname is either a specific hostname (e.g. localhost) or +, or *, depending on the setting for HostNameComparisonMode.
EDIT: You'll also need a couple of P/Invoke declarations for the Win API functions:
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
static extern SafeFileMappingHandle OpenFileMapping(
uint dwDesiredAccess,
bool inheritHandle,
string name
);
EDIT2: We need to tweak the return value of DeriveSharedMemoryName to specify the Local kernel namespace, assuming that your application is not run with elevated privileges. Change the last line of this function to read:
return #"Local\" + Uri.UriSchemeNetPipe + encodedNameRoot;
You also need to specify the hostname parameter correctly to match the hostNameComparisonMode setting used in your binding. As far as I recall, this defaults to StrongWildcard matching in the NetNamedPipeBinding, so you probably need to pass in "+" rather than "localhost".
Can you try to list the named pipes available using
String[] listOfPipes = System.IO.Directory.GetFiles(#"\.\pipe\");
and then determine is your named pipe is amongst them?
My solution is the following :
if (Debugger.IsAttached)
return true;
This will make sure that the code for checking the service is never runned during debugging.
BestRegards
I have a .NET 3.5 Compact Framework application that uses MSMQ.
We are running this application on an Intermec CN3, Windows Mobile 5.0 device.
However, when our application first tries to active the MSMQ service with ActivateDevice (pinvoke), the application crashes and we get the error report message:
A problem has occuurred with myApp.exe
Please tell Microsoft about this problem, at not cost to you. ect..
What we have done is this:
Hard Reset the Device
Install NETCFv35.wm.armv4i.cab
Install msmq.arm.CAB
*Run a CF console app that sets up MSMQ and the registry
Soft reset the PDA
*Run our application which calls ActivateDevice() on startup
After doing a soft reset, the first time that ActivateDevice() is called, the application crashes.
However, now that we have called ActivateDevice(), MSMQ services are working on the device atleast until it is soft reset again.
Also, any calls to ActivateDevice() will not crash the application.
The console app that we run after a hard reset is basically this:
class InstallRegister
{
public void Main()
{
RunMsmqAdmin("install");
RunMsmqAdmin("register install");
RunMsmqAdmin("register");
SetQuotaValueRegistry("MachineQuota");
SetQuotaValueRegistry("DefaultLocalQuota");
SetQuotaValueRegistry("DefaultQuota");
RunMsmqAdmin("enable binary");
RunMsmqAdmin("enable srmp");
RunMsmqAdmin("start");
RegFlushKey(0x80000002);
}
private void SetQuotaValueRegistry(string quotaValueName)
{
Microsoft.Win32.Registry.SetValue(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSMQ\\SimpleClient\\"
, quotaValueName
, 100000);
}
private void RunMsmqAdmin(string command)
{
using (Process _process = new Process())
{
_process.StartInfo.FileName = #"\windows\msmqadm.exe";
_process.StartInfo.Arguments = command;
_process.StartInfo.UseShellExecute = true;
_process.Start();
_process.WaitForExit();
}
}
[System.Runtime.InteropServices.DllImport("CoreDll.dll", EntryPoint = "RegFlushKey", SetLastError = true)]
private static extern uint RegFlushKey(uint hKey);
}
Our applications call to ActivateDevice() is basically this:
class ActivateMSMQ
{
public void Active()
{
var handle = ActivateDevice("Drivers\\BuiltIn\\MSMQD", 0);
CloseHandle(handle);
}
[System.Runtime.InteropServices.DllImport("CoreDll.dll", SetLastError = true)]
private static extern IntPtr ActivateDevice(string lpszDevKey, Int32 dwClientInfo);
[System.Runtime.InteropServices.DllImport("CoreDll.dll", SetLastError = true)]
private extern static Int32 CloseHandle(IntPtr hProcess);
}
ActivateDevice() still causes our app the crash whenever the device is soft reset.
Has anyone else experienced this with MSMQ on the compact framework?
Yes this problem occurs. the quick and easy fix for this is to put the code into a separate executable, then on the start of you app launch this process and wait for completion. The process will terminate due to the crash but will return with your calling app still intact. Then just make sure the executable is deployed in your cab so you app can call it.
I'm using certificates to secure my communications between client and server (no code, just endpoint configuration). Certificates are currently stored in ACOS5 smart cards. Everything works very well except that every time when WCF creates a new channel to access the server, the ACOS5 driver asks user to enter “User PIN”. Unfortunately, it happens quite often.
Is there any way to configure driver to cache PIN that user has already entered within current process at least for some time or how can I cache pin and provide it every time programmatically within same session?
I have found some useful in this article:
This is because in previous versions
of Windows each CSP would cache the
PIN you entered, but Windows 7
actually converts the PIN to a secure
token and caches that. Unfortunately
there’s only one global token cache
but the CSPs can’t use tokens
generated by others, so first the
smart card CSP prompts you and caches
a token, then SSL prompts you and
caches its own token (overwriting the
first one), then the smart card system
prompts you again (because its cached
token is gone).
But I can't use solution that was proposed by author. So what should I do?
This is a way we found and use from many years in our main application:
static class X509Certificate2Extension
{
public static void SetPinForPrivateKey(this X509Certificate2 certificate, string pin)
{
if (certificate == null) throw new ArgumentNullException("certificate");
var key = (RSACryptoServiceProvider)certificate.PrivateKey;
var providerHandle = IntPtr.Zero;
var pinBuffer = Encoding.ASCII.GetBytes(pin);
// provider handle is implicitly released when the certificate handle is released.
SafeNativeMethods.Execute(() => SafeNativeMethods.CryptAcquireContext(ref providerHandle,
key.CspKeyContainerInfo.KeyContainerName,
key.CspKeyContainerInfo.ProviderName,
key.CspKeyContainerInfo.ProviderType,
SafeNativeMethods.CryptContextFlags.Silent));
SafeNativeMethods.Execute(() => SafeNativeMethods.CryptSetProvParam(providerHandle,
SafeNativeMethods.CryptParameter.KeyExchangePin,
pinBuffer, 0));
SafeNativeMethods.Execute(() => SafeNativeMethods.CertSetCertificateContextProperty(
certificate.Handle,
SafeNativeMethods.CertificateProperty.CryptoProviderHandle,
0, providerHandle));
}
}
internal static class SafeNativeMethods
{
internal enum CryptContextFlags
{
None = 0,
Silent = 0x40
}
internal enum CertificateProperty
{
None = 0,
CryptoProviderHandle = 0x1
}
internal enum CryptParameter
{
None = 0,
KeyExchangePin = 0x20
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CryptAcquireContext(
ref IntPtr hProv,
string containerName,
string providerName,
int providerType,
CryptContextFlags flags
);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool CryptSetProvParam(
IntPtr hProv,
CryptParameter dwParam,
[In] byte[] pbData,
uint dwFlags);
[DllImport("CRYPT32.DLL", SetLastError = true)]
internal static extern bool CertSetCertificateContextProperty(
IntPtr pCertContext,
CertificateProperty propertyId,
uint dwFlags,
IntPtr pvData
);
public static void Execute(Func<bool> action)
{
if (!action())
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
The full post and author is here:
http://www.infinitec.de/post/2010/11/22/Setting-the-PIN-of-a-smartcard-programmatically.aspx
Actually I have found answer on my question: the described behavior caused by bug in Advanced Card Systems CSP v1.9. After switching to Alladin eToken application works as it should.
So I can't provide PIN from code but it is remembered by CSP after entering and providing from code is not required. More good news: user sees PIN request in familiar dialog from CSP in this case.
IN Visual Studio when I try to start a windows service project it tells me I cant because I have to use "NET Start" and so forth.
I remember in VS 2003 that when I pressed play it started the service and stop stopped it. Is there any way that when I press play or start for that windows service project I can have this same functionality.
What I currently do is install them using installutil and I put a pre-processor command with System.Diagnostics.Debug.Launch() when I have a compilation variable defined and when I use the service manager it shows me the window to select the debugger. Still this method is somewhat cumbersome.
For anyone else reading this, remember to try to debug ONE thread at a time.
I usually allow for a command line switch that I can pass to my service using the command line argument settings in the IDE. When this switch is on I can run my service as a regular app. The only issue here is that you need to remember that services usually run under accounts with restricted permissions, so debugging as an app in your user context may behave differently when accessing secured resources. Here is example code:
static void Main()
{
if (IsDebugMode())
{
MyService svc = new MyService();
svc.DebugStart();
bool bContinue = true;
MSG msg = new MSG();
// process the message loop so that any Windows messages related to
// COM or hidden windows get processed.
while (bContinue && GetMessage(out msg, IntPtr.Zero, 0, 0) > 0)
{
if (msg.message != WM_QUIT)
DispatchMessage(ref msg);
else
bContinue = false;
}
}
else
{
ServiceBase.Run(new MyService());
}
}
public void DebugStart()
{
this.OnStart(null);
}
static bool IsDebugMode()
{
return (System.Environment.CommandLine.IndexOf("debug") > -1);
}