How to obtain DefragAnalysis using C# - c#

I am currently developing an application in C# (.NET 4.0) that should have as a part of its functionality the ability to determine the percentage of fragmentation on a particular volume. All the other features have been tested and are working fine but I’ve hit a snag trying to access this data. I would ideally prefer to use WMI as this matches the format I’m using for the other features but at this point I’m willing to use anything that can be efficiently integrated into the application, even if I have to use RegEx to filter the data. I am currently doing the development on a Windows 7 Professional (x64) machine. I have tested the following Powershell snippet using Administrator rights and it works flawlessly.
$drive = Get-WmiObject -Class Win32_Volume -Namespace root\CIMV2 -ComputerName . | Where-Object { $_.DriveLetter -eq 'D:' }
$drive.DefragAnalysis().DefragAnalysis
This is the method I’m using in C# to accomplish the same thing, but the InvokeMethod keeps returning 11 (0xB).
public static Fragmentation GetVolumeFragmentationAnalysis(string drive)
{
//Fragmenation object initialization removed for simplicity
try
{
ConnectionOptions mgmtConnOptions = new ConnectionOptions { EnablePrivileges = true };
ManagementScope scope = new ManagementScope(new ManagementPath(string.Format(#"\\{0}\root\CIMV2", Environment.MachineName)), mgmtConnOptions);
ObjectQuery query = new ObjectQuery(string.Format(#"SELECT * FROM Win32_Volume WHERE Name = '{0}\\'", drive));
scope.Connect();
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
object[] outputArgs = new object[2];
foreach (ManagementObject moVolume in searcher.Get())
{
// Execution stops at this line as the result is always 11
UInt32 result = (UInt32)moVolume.InvokeMethod("DefragAnalysis", outputArgs);
if (result == 0)
{
Console.WriteLine("Defrag Needed: = {0}\n", outputArgs[0]);
ManagementBaseObject mboDefragAnalysis = outputArgs[1] as ManagementBaseObject;
if (null != mboDefragAnalysis)
{
Console.WriteLine(mboDefragAnalysis["TotalPercentFragmentation"].ToString());
}
}
else
{
Console.WriteLine("Return Code: = {0}", result);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Could not acquire fragmentation data.\n" + ex);
}
return result;
}
I have even added the following line to the app.manifest but still nothing.
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
Could somebody please tell me what I’m overlooking? Failure is not an option for me on this, so if it cannot be done using C# I don’t mind creating a DLL in another language (even if I have to learn it), that will give me the results I need. Ideally the application should be able work on any OS from XP upwards and must be totally transparent to the user.
These are the resources I have already used. I wanted to add the jeffrey_wall blog on msdn as well but as a new user I can only add 2 hyperlinks at a time. Thanks again.
http://www.codeproject.com/Messages/2901324/Re-the-result-of-DefragAnalysis-method-in-csharp.aspx
http://social.technet.microsoft.com/Forums/vi-VN/winserverfiles/thread/9d56bfad-dcf5-4258-90cf-4ba9247200da

Try building your application targeting 'Any CPU' - on the Build tab of the project properties. I suspect you're using a target of x86. I get the same error code on my Win7 x64 machine if I do that.
In fact, running your PowerShell snippet in the x86 version of PowerShell gives an empty set of results, too.
You get the same error if you run either piece of code without full Administrator privileges, as you've found, so also ensure your app.manifest is correct. A UAC prompt is a handy hint that it's taking effect!
No idea why this WMI query doesn't like running under WoW64, I'm afraid, but hopefully this will give you a head-start.

You could simply call the PowerShell command you mentioned in your post, since you said the PowerShell code works. From C# you would want to follow this workflow:
Instantiate a PowerShell RunSpace
Open the RunSpace
Add a script to the Commands property
Invoke the command list
Here is an example of how to achieve this, and process the resulting object output.
http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C
For Windows XP and Windows Vista, you would have to ensure that PowerShell was installed on each of the systems you want to run your program on. Not a bad prerequisite to have, but something to keep in mind as a dependency.
Hope this helps.

The 32-bit WMI provider for Win32_Volume doesn't seem to be able to start the defragsvc for whatever reason. You can force the 64-bit WMI provider even in a 32-bit client running under WOW64 by changing your code to add an additional WMI connection option:
ConnectionOptions mgmtConnOptions = new ConnectionOptions {
EnablePrivileges = true,
Context = new ManagementNamedValueCollection() {
{ "__ProviderArchitecture", 64 }
}
};

Related

Directory exists is producing inconsistant results on desktop vs server

I have a C# program which checks if a specific directory exists.
It is simply doing:
Directory.Exists(path).
I tried other ways as well. Using DirectoryInfo and using AlphaFS
On my local machine, the path exists. When I run the same program on a server with the same credentials it doesn't exist.
I wonder if it is a group policy issue. But I am able to go up one level and see it.
\server\volume\share\sub directory - Doesn't exist remotely but on my desktop it does
\server\volume\share - Does exist both on my desktop and remote server
Update
I forgot to mention, that since I had access to my desktop, I got the ACL information.
None of the groups were able to translate.
I really just want to get this application to behave the same way is on the server and find out why it is behaving differently.
Update 2
These are physical servers.
My desktop is Liquid VDI
Below is the code:
var path = txtPath.Text;
using (var user = new Impersonation(fuserdomain, fc_user, fc_pass))
{
var alphaExists = Alphaleonis.Win32.Filesystem.Directory.Exists(path);
var alphaDIExists = new Alphaleonis.Win32.Filesystem.DirectoryInfo(path).Exists;
var SystemExists = System.IO.Directory.Exists(path);
var SystemDIExists = new System.IO.DirectoryInfo(path).Exists;
var AlphaHasFiles = false;
var AlphaDIHasFiles = false;
var SystemHasFiles = false;
var SystemDIHasFiles = false;
try
{
Directory.GetFiles(path);
AlphaHasFiles = true;
}
catch { }
try
{
new DirectoryInfo(path).GetFiles();
AlphaDIHasFiles = true;
}
catch { }
try
{
System.IO.Directory.GetFiles(path);
SystemHasFiles = true;
}
catch { }
try
{
new System.IO.DirectoryInfo(path).GetFiles();
SystemDIHasFiles = true;
}
catch { }
MessageBox.Show(string.Format("alphaExists: {0}\nalphaDIExists: {1}\nSystemExists: {2}\nSystemDIExists: {3}\nAlphaGetFiles: {4}\nAlphaDIGetFiles: {5}\nSystemGetFiles: {6}\nSystemDIGetFiles: {7}\n", alphaExists, alphaDIExists, SystemExists, SystemDIExists, AlphaHasFiles, AlphaDIHasFiles, SystemHasFiles, SystemDIHasFiles));
}
Update 3
Although I have workaround this issue; I am still not sure why I would have a difference between my desktop and server. Is there any tool that can help me see where the issue may be?
I've seen the same thing with File.Exists. I never found an answer and finally threw in the towel, I simply try to use it and catch the exception.
Robust code has to catch it anyway, all the test does is avoid trying if the file or directory is not there. (And the PITA that Visual Studio no longer as any way to ignore an exception on a certain line. No problem runtime, annoying in development.)
This is a complete shot in the dark, since we don't have any specific details to go on. e.g. Is the server you're talking about physically yours, or is it a cloud-based server service?
I'd guess that your machine is an older operating system than the server, and the folder that you're trying to access is one of those special folders that has become more locked down with more recent operating systems (particularly on server operating systems) like the "Program Files" folder. So even though the folder exists on both, the method works on your machine but not on the server, due to permissions.
Hope this helps.
As far as I can tell, the Impersonation class in your code is not part of the dot net framework. Googling finds a couple of implementations. Where does it come from and How confident are you that it actually works in your scenario?
For example, if you remove the Impersonation code, and actually run it as that user, does that make it work?
One other clarification... When you say
\server\volume\share
Do you mean this is a network location (e.g. a UNC location), so is the same network path you are trying to access from both machines? If so, this would open up new possibilities for problems like firewalls, etc... Is that location on either of the two machines that we know about from the question, or a different location?

C# .NET 4.5 Getting target of shortcut without shell32.shell()

I'm not a very experienced programmer and new at C#, and I'm having some problems getting the target of a shortcut using shell32.shell().
I found the code here on stackoverflow - and it works beautifully on regular Windows PC's, but when executed on a Citrix virtualized Windows desktop (where I need it to run) it breaks.
The code runs through shortcuts in a folder via a foreach loop, and filters out any that has an executable target. Problem is that to find the target of the shortcut I use the code below, and as soon as it is called the foreach breaks and doesn't progress any further (on Citrix).
I have determined that the break happens at the line "var shl = new Shell32.Shell();", the code after that line doesn't fire and it exits the foreach (but continues executing code after the foreach).
public static string GetLnkTarget(string lnkPath)
{
var shl = new Shell32.Shell();
lnkPath = System.IO.Path.GetFullPath(lnkPath);
var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
var lnk = (Shell32.ShellLinkObject)itm.GetLink;
return lnk.Target.Path;
}
Does anyone know of an alternate way to find the target of a shortcut that'll work in a Citrix virtualized environment?
I don't know what caused the issue with Shell32.Shell() specifically in the Citrix environment, but I found another way that works for me.
The answer was provided by user djdanlib here: https://stackoverflow.com/a/8661371/5992820
"Add IWshRuntimeLibrary as a reference to your project. Add Reference, COM tab, Windows Scripting Host Object Model.
Here is how I get the properties of a shortcut:
IWshRuntimeLibrary.IWshShell wsh = new IWshRuntimeLibrary.WshShellClass();
IWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)wsh.CreateShortcut(filename);
The shortcut object "sc" has a TargetPath property."

Accessing Internet Explorer with Shdocvw results in UnauthorizedAccessException

I'm working on a portion of an application that has a 'finder' tool that allows the user to drag and drop a finder onto an application or internet explorer web browser so that our program can locate it and do what it needs to do. This portion of the application was not under any active development for the last few years (last time I believe IE 7 was the latest browser), but it has worked for IE 9 and below. Starting at IE 10 we get problems, and I specifically am using IE 11.
The following code locates the different Internet explorer windows (including tabs) and file explorer windows. We made a quick VB script for extra testing -
dim objShell
dim objShellWindows
set objShell = CreateObject("shell.application")
set objShellWindows = objShell.Windows
if (not objShellWindows is nothing) then
WScript.Echo objShellWindows.Count
for each win in objShellWindows
wscript.Echo TypeName(win)
WScript.Echo win.LocationUrl
WScript.Echo win.LocationName
WScript.Echo win.HWND
next
end if
set objShellWindows = nothing
set objShell = nothing
The above code will execute without error, and it gives the URL and title bar name of all the tabs we have open.
Below is our C# code. It attempts to get the main IE window (not the tab). this.Handle is the handle of this main IE window that the finder tool gets when the user drops it. We're attempting to iterate through the open windows and find the Internet Explorer window that the user selected. This particular snippet is changed slightly from our original implementation, but the end result is the same. As soon as it hits test = window.Item(i) it throws a UnauthorizedAccessException.
ShellWindows windows = null;
IWebBrowser2 shellWindow = null;
IHTMLDocument2 actualDoc = null;
Type shellApplicationType = Type.GetTypeFromProgID("Shell.Application");
Shell32.Shell shellInterface = (Shell32.Shell)Activator.CreateInstance(shellApplicationType);
windows = (ShellWindows)shellInterface.Windows();
bool found = false;
for (int i = 0; i < windows.Count; i++)
{
try
{
object test;
try
{
test = windows.Item(i); //Exception here
shellWindow = (IWebBrowser2)test;
}
catch
{
}
if (shellWindow != null && (IntPtr)shellWindow.HWND == this.Handle)
{
//the rest of the code gets the correct tab from the main IE window
This is the original unedited code from when we first revisited this portion of the program.
ShellWindows windows = null;
IWebBrowser2 shellWindow =null;
IHTMLDocument2 actualDoc = null;
windows = new SHDocVw.ShellWindowsClass();
bool found = false;
for (int i = 0; i < windows.Count; i++)
{
try{
shellWindow = windows.Item(i) as SHDocVw.IWebBrowser2; //Exception here
if (shellWindow != null && (IntPtr)shellWindow.HWND == this.Handle)
{
I would also like to note that instead of a for loop I have tried a foreach loop that followed this syntax
foreach(IWebBrowser2 browser in windows)
and
foreach(InternetExplorer browser in windows)
In those instances, the loop skips over the IE window.
I have looked at IE's security settings. I have disabled Enhanced Protection Mode and allowed cross domain. There does not seem to be a lot of information on this issue, and every approach we try seems to always end up with an UnauthorizedAccessException.
Edit: In response to Hans answer, I do not have any anti malware running on this machine. It is a virtual machine with windows 7 that has the latest SP and updates (no microsoft security essentials). I tried running the app on a 32 bit machine with similar settings and it also failed. After testing it on IE 11, I uninstalled IE 11, rebooted, tried IE 10 (it failed, same error), uninstalled IE 10, rebooted, tried IE 9, and it worked without making any other changes to the system.
Here is the SSCCE as requested by Hans. This code actually works on my target machine. I will return to this post in the next day or two while I handle other tasks that require my attention.
I build this as a 32 bit console app, and ran it on a 64bit machine.
using System;
using SHDocVw;
using mshtml;
namespace GetBrowserSSCCE
{
class Program
{
static void Main(string[] args)
{
ShellWindows windows = null;
IWebBrowser2 shellWindow = null;
windows = new SHDocVw.ShellWindowsClass();
for (int i = 0; i < windows.Count; i++)
{
try
{
shellWindow = windows.Item(i) as SHDocVw.IWebBrowser2;
Console.WriteLine(string.Format("Window Found. HWND: {0}\nName: {1}", shellWindow.HWND, shellWindow.Name));
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("UnauthorizedAccessException caught. Exception Text: " +ex.Message);
}
}
Console.ReadLine();
}
}
}
That this fails in your C# program but not when you run it from the VBScript interpreter points strongly to an environmental problem. Both use the exact same shell interface. The specific exception (underlying error code is 0x8007005) has been reported before on the interwebs but never diagnosed.
First thing you should focus on whenever you have an environmental problem, particularly the kind associated with access rights, is the anti-malware installed on the machine. Disable it and try again.
Second one you should focus on is a quirk associated with ShellWindows, it doesn't just enumerate Internet Explorer windows but also Windows Explorer windows. You've been looking at having sufficient access to IE but that isn't enough, this code can also fail if you happen to have an Explorer window opened and there's an access problem with the explorer.exe process. Do note that your Activator.CreateInstance() method call is not equivalent to the VBScript code, Activator.GetObject() is. So your changes would actually make the problem worse if this is underlying problem.
Third detail that's worth checking is the bitness of your process. By default, your VBScript code will run in the 64-bit script interpreter on a machine that boots the 64-bit version of Windows. But the default setting for a C# project is to run in 32-bit mode. Right-click your EXE project, Properties, Build tab and tinker with the Platform target setting, the 'Prefer 32-bit' checkbox if you see it. This is not an explanation for the error code, it can however affect the effectiveness of anti-malware to intrude.

How to give IIS AppPool Desktop Rights

The action I need help about, is to execute a EXE file on own servers disk from a intranet-webpage, which IIS are on same server-installation. The webpage use a business layer to execute a ProcessStart together with given parameters.
When I perform the execution from web, the taskmanager show me that the application are starting up with the IIS AppPool of webpage as user. Few seconds later it's killed. In my database logs, I can see;
The Microsoft Jet database engine cannot open the file '\\computer\pathfile.ext'. It is already opened exclusively by another user, or you need permission to view its data.
That's correct. The EXE tool are, in turn, loading files from other computers. This is a special behavior which are well studied and well working while using the tool from desktop.
My goal/question,
I want this web-function-call behave with desktop rights. Is it possible at all?
The IIS AppPool have a regular setup with account ApplicationPoolIdentity. I appeared to be "lucky unwise", without knowledge about how much IIS 7.5 and Windows Server 2008 R2 raised the security model since <=IIS6.
I tried to change the app-pool user to NetworkService, Administrator.
I tried to set the application with app-pool as exec/read right
I even tried to let webapp to run a batch-file with a call to application inside..
Then I was begin to change the ProcessStart-behavior. And here, I
don't know much of what to do. I tried to add VERB runas. Force a
password prompt is not a solution here. I tried to simulate a
username/password. No luck there. I also tried to add runas /user:
blabla as parameters with ProcessStart, after used /savecred in a
desktop command window once. No luck there.
Maybe this should work but I just don't understand the correct setup of properties. I add the ProcessStart code snippet below, also added some commented code to let you see what I tried.
public string RunProcess(ApplicationType type, int param)
{
currentSelection = GetApplicationType(type);
ProcessStartInfo info = new ProcessStartInfo(currentSelection.Path);
info.CreateNoWindow = false;
info.UseShellExecute = true;
//info.UseShellExecute = false;
//info.ErrorDialog = false;
//info.UserName = "dummyUsEr";
//info.Password = this.SecurePwd("DummyPWd");
info.WindowStyle = ProcessWindowStyle.Normal;
info.Arguments = string.Format(" {0}", param.ToString());
using (Process exec = Process.Start(info))
{
try
{
exec.WaitForExit();
}
catch
{
}
}
return output;
}
EDIT
Just to be clear, and perhaps help some another guy/girl browsing to this question, I attach the snippet of Password-generation,
protected System.Security.SecureString SecurePwd(string pwd)
{
SecureString securePwd = new SecureString();
foreach (char ch in pwd.ToCharArray())
securePwd.AppendChar(ch);
return securePwd;
}
I see that you've tried putting in a specific username and password for the process start impersonation, but you say that the process accesses files on another computer and I don't see any mention of specifying a domain name which presumably you would need to access remote files?
So like this:
info.Domain = "domainname";
info.UserName = "dummyUsEr";
info.Password = "DummyPWd";
Also, what does this.SecurePwd() do and have you tried it with just the straight password string that you're passing into it?

How to set "interact with desktop" in windows service installer

I have a windows service which runs under system account and executes some programs from time to time (yeah,yeah, I know that's a bad practice, but that's not my decision). I need to set the "interact with desktop" check, to see the gui of that executed programs, after the service is installed. I've tried several ways, putting the code below in AfterInstall or OnCommited event handlers of my service installer:
ConnectionOptions coOptions = new ConnectionOptions();
coOptions.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope mgmtScope = new System.Management.ManagementScope(#"root\CIMV2", coOptions);
mgmtScope.Connect();
ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ServiceMonitorInstaller.ServiceName + "'");
ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
InParam["DesktopInteract"] = true;
ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
or
RegistryKey ckey = Registry.LocalMachine.OpenSubKey(
#"SYSTEM\CurrentControlSet\Services\WindowsService1", true);
if(ckey != null)
{
if(ckey.GetValue("Type") != null)
{
ckey.SetValue("Type", ((int)ckey.GetValue("Type") | 256));
}
}
both of these methods "work". They set the check, but after I start the service it launches the exe - and gui isn't shown! So, if I stop the service, recheck and start it again - bingo! everything starts and is shown. The second way to achieve the result is to reboot - after it the gui is also shown.
So the question is: Is there a correct way to set "interact with desktop" check, so it'll start working without rechecks and reboots?
OS: Windows XP (haven't tried Vista and 7 yet...)
private static void SetInterActWithDeskTop()
{
var service = new System.Management.ManagementObject(
String.Format("WIN32_Service.Name='{0}'", "YourServiceName"));
try
{
var paramList = new object[11];
paramList[5] = true;
service.InvokeMethod("Change", paramList);
}
finally
{
service.Dispose();
}
}
And finally after searching the internet for a week - I've found a great working solution:
http://asprosys.blogspot.com/2009/03/allow-service-to-interact-with-desktop.html
Find the desktop to launch into. This
may seem facetious but it isn't as
simple as it seems. With Terminal
Services and Fast User Switching there
can be multiple interactive users
logged on to the computer at the same
time. If you want the user that is
currently sitting at the physical
console then you're in luck, the
Terminal Services API call
WTSGetActiveConsoleSessionId will get
you the session ID you need. If your
needs are more complex (i.e. you need
to interact with a specific user on a
TS server or you need the name of the
window station in a non-interactive
session) you'll need to enumerate the
Terminal Server sessions with
WTSEnumerateSessions and check the
session for the information you need
with WTSGetSessionInformation.
Now you know what session you need to
interact with and you have its ID.
This is the key to the whole process,
using WTSQueryUserToken and the
session ID you can now retrieve the
token of the user logged on to the
target session. This completely
mitigates the security problem of the
'interact with the desktop' setting,
the launched process will not be
running with the LOCAL SYSTEM
credentials but with the same
credentials as the user that is
already logged on to that session! No
privilege elevation.
Using CreateProcessAsUser and the
token we have retrieved we can launch
the process in the normal way and it
will run in the target session with
the target user's credentials. There
are a couple of caveats, both
lpCurrentDirectory and lpEnvironment
must point to valid values - the
normal default resolution methods for
these parameters don't work for
cross-session launching. You can use
CreateEnvironmentBlock to create a
default environment block for the
target user.
There is source code of the working project attached.
Same as Heisa but with WMI. (code is Powershell, but can be easily ported to C#)
if ($svc = gwmi win32_service|?{$_.name -eq $svcname})
{
try {
$null = $svc.change($svc.displayname,$svc.pathname,16,1,`
"Manual",$false,$svc.startname,$null,$null,$null,$null)
write-host "Change made"
catch { throw "Error: $_" }
} else
{ throw "Service $svcname not installed" }
See MSDN: Service Change() method for param description.

Categories