Replacement for CultureInfo.GetCultures in .NET Windows Store apps - c#

CultureInfo.GetCultures does not exist in the .NET API for Windows Store apps. How could we read all available cultures instead?
I know about the Languages list and the primary application language. I could read all languages that are available for the app that way. But I need to read all cultures (languages) that are available on the system. Previously it was easy using CultureInfo.GetCultures.

James' comment pointed me in the right direction. Here is the code I developed. I checked the code using a unit test to ensure that the returned neutral, specific and all cultures are identical with the cultures CultureInfo.GetCultures returns (and they indeed are :-)).
public class LocalesRetrievalException : Exception
{
public LocalesRetrievalException(string message)
: base(message)
{
}
}
public static class CultureHelper
{
#region Windows API
private delegate bool EnumLocalesProcExDelegate(
[MarshalAs(UnmanagedType.LPWStr)]String lpLocaleString,
LocaleType dwFlags, int lParam);
[DllImport(#"kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool EnumSystemLocalesEx(EnumLocalesProcExDelegate pEnumProcEx,
LocaleType dwFlags, int lParam, IntPtr lpReserved);
private enum LocaleType : uint
{
LocaleAll = 0x00000000, // Enumerate all named based locales
LocaleWindows = 0x00000001, // Shipped locales and/or replacements for them
LocaleSupplemental = 0x00000002, // Supplemental locales only
LocaleAlternateSorts = 0x00000004, // Alternate sort locales
LocaleNeutralData = 0x00000010, // Locales that are "neutral" (language only, region data is default)
LocaleSpecificData = 0x00000020, // Locales that contain language and region data
}
#endregion
public enum CultureTypes : uint
{
SpecificCultures = LocaleType.LocaleSpecificData,
NeutralCultures = LocaleType.LocaleNeutralData,
AllCultures = LocaleType.LocaleWindows
}
public static IReadOnlyCollection<CultureInfo> GetCultures(
CultureTypes cultureTypes)
{
List<CultureInfo> cultures = new List<CultureInfo>();
EnumLocalesProcExDelegate enumCallback = (locale, flags, lParam) =>
{
try
{
cultures.Add(new CultureInfo(locale));
}
catch (CultureNotFoundException)
{
// This culture is not supported by .NET (not happened so far)
// Must be ignored.
}
return true;
};
if (EnumSystemLocalesEx(enumCallback, (LocaleType)cultureTypes, 0,
(IntPtr)0) == false)
{
int errorCode = Marshal.GetLastWin32Error();
throw new LocalesRetrievalException("Win32 error " + errorCode +
" while trying to get the Windows locales");
}
// Add the two neutral cultures that Windows misses
// (CultureInfo.GetCultures adds them also):
if (cultureTypes == CultureTypes.NeutralCultures ||
cultureTypes == CultureTypes.AllCultures)
{
cultures.Add(new CultureInfo("zh-CHS"));
cultures.Add(new CultureInfo("zh-CHT"));
}
return new ReadOnlyCollection<CultureInfo>(cultures);
}
}

Related

Authenticating Microsoft Dynamics CRM with Code

We have a scenario in which we are trying to open CRM in Winform WebBrowser control and every time we open it, it asks for authentication in pop up window.
Also from that when we are trying to open a new form (which opens in IE) it asks for authentication again.
The catch here is that users are logged in into machines (Windows 7, IE 9) through local credentials and we can’t use integrated authentication.
We have captured user credentials in application i.e. we know user name and password, Is there a way through which we can pass the credentials to Webbrowser control and IE so that it does not ask user for credentials.
Appreciate You Help.
Thanks.
Abhinav
If you log in from the browser and authenticate yourself, you will see the following cookies being stored:
Theoretically, retaining these cookies across requests should prevent crm from asking for authentication each time you open a new instance of the WebBrowser Control.
You can set Cookies for the control using the WebBrowser.Document.Cookie property.
To retrieve the cookie after authenticating the first time, you will need to use the following code:
[SecurityCritical]
public static string GetCookieInternal(Uri uri, bool throwIfNoCookie)
{
uint pchCookieData = 0;
string url = UriToString(uri);
uint flag = (uint)NativeMethods.InternetFlags.INTERNET_COOKIE_HTTPONLY;
//Gets the size of the string builder
if (NativeMethods.InternetGetCookieEx(url, null, null, ref pchCookieData, flag, IntPtr.Zero))
{
pchCookieData++;
StringBuilder cookieData = new StringBuilder((int)pchCookieData);
//Read the cookie
if (NativeMethods.InternetGetCookieEx(url, null, cookieData, ref pchCookieData, flag, IntPtr.Zero))
{
DemandWebPermission(uri);
return cookieData.ToString();
}
}
int lastErrorCode = Marshal.GetLastWin32Error();
if (throwIfNoCookie || (lastErrorCode != (int)NativeMethods.ErrorFlags.ERROR_NO_MORE_ITEMS))
{
throw new Win32Exception(lastErrorCode);
}
return null;
}
private static void DemandWebPermission(Uri uri)
{
string uriString = UriToString(uri);
if (uri.IsFile)
{
string localPath = uri.LocalPath;
new FileIOPermission(FileIOPermissionAccess.Read, localPath).Demand();
}
else
{
new WebPermission(NetworkAccess.Connect, uriString).Demand();
}
}
private static string UriToString(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
UriComponents components = (uri.IsAbsoluteUri ? UriComponents.AbsoluteUri : UriComponents.SerializationInfoString);
return new StringBuilder(uri.GetComponents(components, UriFormat.SafeUnescaped), 2083).ToString();
}
internal sealed class NativeMethods
{
#region enums
public enum ErrorFlags
{
ERROR_INSUFFICIENT_BUFFER = 122,
ERROR_INVALID_PARAMETER = 87,
ERROR_NO_MORE_ITEMS = 259
}
public enum InternetFlags
{
INTERNET_COOKIE_HTTPONLY = 8192, //Requires IE 8 or higher
INTERNET_COOKIE_THIRD_PARTY = 131072,
INTERNET_FLAG_RESTRICTED_ZONE = 16
}
#endregion
#region DLL Imports
[SuppressUnmanagedCodeSecurity, SecurityCritical, DllImport("wininet.dll", EntryPoint = "InternetGetCookieExW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]internal static extern bool InternetGetCookieEx([In] string Url, [In] string cookieName, [Out] StringBuilder cookieData, [In, Out] ref uint pchCookieData, uint flags, IntPtr reserved);
#endregion
}
I usually refrain from posting code I haven't tried out myself but I don't have access to an On-Prem environment at the moment. I would love to know if this works so let me know if you try it out.

Can't figure out how to check if Biometric is present

At work we make our own tablets. Some of the tablets have fingerprint biometrics, some don't. Sometimes a tech forgets to plug it in. I have yet to find a way to check if that device (or any for that matter) is present.
My first approach was to use the GUID for a biometric which is {53D29EF7-377C-4D14-864B-EB3A85769359}. I would search in the registry at hklm\system\currontcontrolset\control\class and check to see if that key is present.
That doesn't work because it seems that Windows 7 has that key present even if you've never had a biometric installed. It worked in XP, but I just tried again on a unit that used to have a biometric but I took it out and that key is still present.
The hardest part about this problem is that I have to work with Windows 7, 7 embedded, xp, and xp embedded.
Next idea was to use WMI, but I couldn't find the correct class to call to check if it is present.
I then found a biometric.dll but that only works in Windows 7.
Sometimes finding a common solution to a problem is not always easy. I'm doing this project in C# but iI'm willing to convert it to any language.
Any ideas on were I should start looking?
With the help of Joshua Drake who gave me an awesome link on how to solve my problem, those are my results:
The code that I am fixing to post is kind of specialized in that it looks for a specific GUID and only looks for the first one. I adapted it from the article about how to disable a device, although this code does not disable anything it merely checks for presence.
public static bool IsDevicePresent(string guid)
{
var info = IntPtr.Zero;
var NullGuid = new Guid(guid);
try
{
info = SetupDiGetClassDevsW(ref NullGuid,null,IntPtr.Zero,DIGCF_PRESENT);
CheckError("SetupDiGetClassDevs");
var devdata = new SP_DEVINFO_DATA();
devdata.cbSize = (UInt32)Marshal.SizeOf(devdata);
// Get first device matching device criterion.
SetupDiEnumDeviceInfo(info,0,out devdata);
// if no items match filter, throw
if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
CheckError("No device found matching filter.", 0xcffff);
CheckError("SetupDiEnumDeviceInfo");
}
catch
{
return false;
}
finally
{
if (info != IntPtr.Zero)
SetupDiDestroyDeviceInfoList(info);
}
return true;
}
private static void CheckError(string message, int lasterror = -1)
{
int code = lasterror == -1 ? Marshal.GetLastWin32Error() : lasterror;
if (code != 0)
throw new ApplicationException(String.Format("Error disabling hardware device (Code {0}): {1}",code, message));
}
[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevsW([In] ref Guid ClassGuid,[MarshalAs(UnmanagedType.LPWStr)]string Enumerator,IntPtr parent,UInt32 flags);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiDestroyDeviceInfoList(IntPtr handle);
[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr deviceInfoSet,UInt32 memberIndex,[Out] out SP_DEVINFO_DATA deviceInfoData);
//used to find device info from device manager
[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
public UInt32 cbSize;
public Guid classGuid;
public UInt32 devInst;
public IntPtr reserved;
}
private const uint DIGCF_PRESENT = 2;
private const uint ERROR_INVALID_DATA = 13;
private const uint ERROR_NO_MORE_ITEMS = 259;
private const uint ERROR_ELEMENT_NOT_FOUND = 1168;
And here is a simple unit test to prove it works for first device
[Test]
public void TestDevicePresent()
{
var bluetoothClassGuid = "e0cbf06c-cd8b-4647-bb8a-263b43f0f974";
var biometricClassGuid = "53D29EF7-377C-4D14-864B-EB3A85769359";
var cdromdrivClassGiud = "4d36e965-e325-11ce-bfc1-08002be10318";
Assert.False(Native.IsDevicePresent(bluetoothClassGuid));
Assert.False(Native.IsDevicePresent(biometricClassGuid));
Assert.True(Native.IsDevicePresent(cdromdrivClassGiud));
}

32 bit or 64 bit using c# [duplicate]

In a .NET 2.0 C# application I use the following code to detect the operating system platform:
string os_platform = System.Environment.OSVersion.Platform.ToString();
This returns "Win32NT". The problem is that it returns "Win32NT" even when running on Windows Vista 64-bit.
Is there any other method to know the correct platform (32 or 64 bit)?
Note that it should also detect 64 bit when run as a 32 bit application on Windows 64 bit.
.NET 4 has two new properties in the Environment class, Is64BitProcess and Is64BitOperatingSystem. Interestingly, if you use Reflector you can see they are implemented differently in the 32-bit & 64-bit versions of mscorlib. The 32-bit version returns false for Is64BitProcess and calls IsWow64Process via P/Invoke for Is64BitOperatingSystem. The 64-bit version just returns true for both.
UPDATE: As Joel Coehoorn and others suggest, starting at .NET Framework 4.0, you can just check Environment.Is64BitOperatingSystem.
IntPtr.Size won't return the correct value if running in 32-bit .NET Framework 2.0 on 64-bit Windows (it would return 32-bit).
As Microsoft's Raymond Chen describes, you have to first check if running in a 64-bit process (I think in .NET you can do so by checking IntPtr.Size), and if you are running in a 32-bit process, you still have to call the Win API function IsWow64Process. If this returns true, you are running in a 32-bit process on 64-bit Windows.
Microsoft's Raymond Chen:
How to detect programmatically whether you are running on 64-bit Windows
My solution:
static bool is64BitProcess = (IntPtr.Size == 8);
static bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64();
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process(
[In] IntPtr hProcess,
[Out] out bool wow64Process
);
public static bool InternalCheckIsWow64()
{
if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) ||
Environment.OSVersion.Version.Major >= 6)
{
using (Process p = Process.GetCurrentProcess())
{
bool retVal;
if (!IsWow64Process(p.Handle, out retVal))
{
return false;
}
return retVal;
}
}
else
{
return false;
}
}
If you're using .NET Framework 4.0, it's easy:
Environment.Is64BitOperatingSystem
See Environment.Is64BitOperatingSystem Property (MSDN).
This is just an implementation of what's suggested above by Bruno Lopez, but works on Win2k + all WinXP service packs. Just figured I'd post it so other people didn't have roll it by hand. (would have posted as a comment, but I'm a new user!)
[DllImport("kernel32", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
public extern static IntPtr LoadLibrary(string libraryName);
[DllImport("kernel32", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
public extern static IntPtr GetProcAddress(IntPtr hwnd, string procedureName);
private delegate bool IsWow64ProcessDelegate([In] IntPtr handle, [Out] out bool isWow64Process);
public static bool IsOS64Bit()
{
if (IntPtr.Size == 8 || (IntPtr.Size == 4 && Is32BitProcessOn64BitProcessor()))
{
return true;
}
else
{
return false;
}
}
private static IsWow64ProcessDelegate GetIsWow64ProcessDelegate()
{
IntPtr handle = LoadLibrary("kernel32");
if ( handle != IntPtr.Zero)
{
IntPtr fnPtr = GetProcAddress(handle, "IsWow64Process");
if (fnPtr != IntPtr.Zero)
{
return (IsWow64ProcessDelegate)Marshal.GetDelegateForFunctionPointer((IntPtr)fnPtr, typeof(IsWow64ProcessDelegate));
}
}
return null;
}
private static bool Is32BitProcessOn64BitProcessor()
{
IsWow64ProcessDelegate fnDelegate = GetIsWow64ProcessDelegate();
if (fnDelegate == null)
{
return false;
}
bool isWow64;
bool retVal = fnDelegate.Invoke(Process.GetCurrentProcess().Handle, out isWow64);
if (retVal == false)
{
return false;
}
return isWow64;
}
The full answer is this (taken from both stefan-mg, ripper234 and BobbyShaftoe's answer):
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo);
private bool Is64Bit()
{
if (IntPtr.Size == 8 || (IntPtr.Size == 4 && Is32BitProcessOn64BitProcessor()))
{
return true;
}
else
{
return false;
}
}
private bool Is32BitProcessOn64BitProcessor()
{
bool retVal;
IsWow64Process(Process.GetCurrentProcess().Handle, out retVal);
return retVal;
}
First check if you're in a 64 bit process. If you're not, check if the 32 bit process is a Wow64Process.
Microsoft has put a code sample for this:
http://1code.codeplex.com/SourceControl/changeset/view/39074#842775
It looks like this:
/// <summary>
/// The function determines whether the current operating system is a
/// 64-bit operating system.
/// </summary>
/// <returns>
/// The function returns true if the operating system is 64-bit;
/// otherwise, it returns false.
/// </returns>
public static bool Is64BitOperatingSystem()
{
if (IntPtr.Size == 8) // 64-bit programs run only on Win64
{
return true;
}
else // 32-bit programs run on both 32-bit and 64-bit Windows
{
// Detect whether the current process is a 32-bit process
// running on a 64-bit system.
bool flag;
return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
IsWow64Process(GetCurrentProcess(), out flag)) && flag);
}
}
/// <summary>
/// The function determins whether a method exists in the export
/// table of a certain module.
/// </summary>
/// <param name="moduleName">The name of the module</param>
/// <param name="methodName">The name of the method</param>
/// <returns>
/// The function returns true if the method specified by methodName
/// exists in the export table of the module specified by moduleName.
/// </returns>
static bool DoesWin32MethodExist(string moduleName, string methodName)
{
IntPtr moduleHandle = GetModuleHandle(moduleName);
if (moduleHandle == IntPtr.Zero)
{
return false;
}
return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
}
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule,
[MarshalAs(UnmanagedType.LPStr)]string procName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
There is a WMI version available as well (for testing remote machines).
You can also check for the PROCESSOR_ARCHITECTURE environment variable.
It either doesn't exist or is set to "x86" on 32-bit Windows.
private int GetOSArchitecture()
{
string pa =
Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
return ((String.IsNullOrEmpty(pa) ||
String.Compare(pa, 0, "x86", 0, 3, true) == 0) ? 32 : 64);
}
From Chriz Yuen blog
C# .Net 4.0 Introduced two new environment property
Environment.Is64BitOperatingSystem;
Environment.Is64BitProcess;
Please be careful when you use these both property.
Test on Windows 7 64bits Machine
//Workspace: Target Platform x86
Environment.Is64BitOperatingSystem True
Environment.Is64BitProcess False
//Workspace: Target Platform x64
Environment.Is64BitOperatingSystem True
Environment.Is64BitProcess True
//Workspace: Target Platform Any
Environment.Is64BitOperatingSystem True
Environment.Is64BitProcess True
Quickest way:
if(IntPtr.Size == 8) {
// 64 bit machine
} else if(IntPtr.Size == 4) {
// 32 bit machine
}
Note: this is very direct and works correctly on 64-bit only if the program does not force execution as a 32-bit process (e.g. through <Prefer32Bit>true</Prefer32Bit> in the project settings).
Try this:
Environment.Is64BitOperatingSystem
Environment.Is64BitProcess
#foobar: You are right, it is too easy ;)
In 99% of the cases, developers with weak system administrator backgrounds ultimately fail to realize the power Microsoft has always provided for anyone to enumerate Windows.
System administrators will always write better and simpler code when it comes to such a point.
Nevertheless, one thing to note, build configuration must be AnyCPU for this environment variable to return the correct values on the correct systems:
System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")
This will return "X86" on 32-bit Windows, and "AMD64" on 64-bit Windows.
Using dotPeek helps to see how the framework actually does it. With that in mind, here's what I've come up with:
public static class EnvironmentHelper
{
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
public static bool Is64BitOperatingSystem()
{
// Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.
if (IntPtr.Size == 8)
return true;
// Check if this process is an x86 process running on an x64 environment.
IntPtr moduleHandle = GetModuleHandle("kernel32");
if (moduleHandle != IntPtr.Zero)
{
IntPtr processAddress = GetProcAddress(moduleHandle, "IsWow64Process");
if (processAddress != IntPtr.Zero)
{
bool result;
if (IsWow64Process(GetCurrentProcess(), out result) && result)
return true;
}
}
// The environment must be an x86 environment.
return false;
}
}
Example usage:
EnvironmentHelper.Is64BitOperatingSystem();
Use these two environment variables (pseudo code):
if (PROCESSOR_ARCHITECTURE = x86 &&
isDefined(PROCESSOR_ARCHITEW6432) &&
PROCESSOR_ARCHITEW6432 = AMD64) {
//64 bit OS
}
else
if (PROCESSOR_ARCHITECTURE = AMD64) {
//64 bit OS
}
else
if (PROCESSOR_ARCHITECTURE = x86) {
//32 bit OS
}
Refer to the blog post HOWTO: Detect Process Bitness.
I used this check with success on many operating systems:
private bool Is64BitSystem
{
get
{
return Directory.Exists(Environment.ExpandEnvironmentVariables(#"%windir%\SysWOW64"));
}
}
This folder is always named "SysWOW64", no matter of the language of the operating system. This works for .NET Framework 1.1 or above.
I need to do this, but I also need to be able as an admin do it remotely, either case this seems to work quite nicely for me:
public static bool is64bit(String host)
{
using (var reg = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, host))
using (var key = reg.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\"))
{
return key.GetValue("ProgramFilesDir (x86)") !=null;
}
}
This is a solution based on Microsoft's code at http://1code.codeplex.com/SourceControl/changeset/view/39074#842775. It uses extension methods for easy code reuse.
Some possible usage is shown below:
bool bIs64BitOS = System.Environment.OSVersion.IsWin64BitOS();
bool bIs64BitProc = System.Diagnostics.Process.GetCurrentProcess().Is64BitProc();
//Hosts the extension methods
public static class OSHelperTools
{
/// <summary>
/// The function determines whether the current operating system is a
/// 64-bit operating system.
/// </summary>
/// <returns>
/// The function returns true if the operating system is 64-bit;
/// otherwise, it returns false.
/// </returns>
public static bool IsWin64BitOS(this OperatingSystem os)
{
if (IntPtr.Size == 8)
// 64-bit programs run only on Win64
return true;
else// 32-bit programs run on both 32-bit and 64-bit Windows
{ // Detect whether the current process is a 32-bit process
// running on a 64-bit system.
return Process.GetCurrentProcess().Is64BitProc();
}
}
/// <summary>
/// Checks if the process is 64 bit
/// </summary>
/// <param name="os"></param>
/// <returns>
/// The function returns true if the process is 64-bit;
/// otherwise, it returns false.
/// </returns>
public static bool Is64BitProc(this System.Diagnostics.Process p)
{
// 32-bit programs run on both 32-bit and 64-bit Windows
// Detect whether the current process is a 32-bit process
// running on a 64-bit system.
bool result;
return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") && IsWow64Process(p.Handle, out result)) && result);
}
/// <summary>
/// The function determins whether a method exists in the export
/// table of a certain module.
/// </summary>
/// <param name="moduleName">The name of the module</param>
/// <param name="methodName">The name of the method</param>
/// <returns>
/// The function returns true if the method specified by methodName
/// exists in the export table of the module specified by moduleName.
/// </returns>
static bool DoesWin32MethodExist(string moduleName, string methodName)
{
IntPtr moduleHandle = GetModuleHandle(moduleName);
if (moduleHandle == IntPtr.Zero)
return false;
return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
}
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)]string procName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
}
Here is the direct approach in C# using DllImport from this page.
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo);
public static bool Is64Bit()
{
bool retVal;
IsWow64Process(Process.GetCurrentProcess().Handle, out retVal);
return retVal;
}
I'm using the followin code. Note: It's made for an AnyCPU project.
public static bool Is32bitProcess(Process proc) {
if (!IsThis64bitProcess()) return true; // We're in 32-bit mode, so all are 32-bit.
foreach (ProcessModule module in proc.Modules) {
try {
string fname = Path.GetFileName(module.FileName).ToLowerInvariant();
if (fname.Contains("wow64")) {
return true;
}
} catch {
// What on earth is going on here?
}
}
return false;
}
public static bool Is64bitProcess(Process proc) {
return !Is32bitProcess(proc);
}
public static bool IsThis64bitProcess() {
return (IntPtr.Size == 8);
}
I found this to be the best way to check for the platform of the system and the process:
bool 64BitSystem = Environment.Is64BitOperatingSystem;
bool 64BitProcess = Environment.Is64BitProcess;
The first property returns true for 64-bit system, and false for 32-bit.
The second property returns true for 64-bit process, and false for 32-bit.
The need for these two properties is because you can run 32-bit processes on 64-bit system, so you will need to check for both the system and the process.
All fine, but this should also work from env:
PROCESSOR_ARCHITECTURE=x86
..
PROCESSOR_ARCHITECTURE=AMD64
Too easy, maybe ;-)
Here's a Windows Management Instrumentation (WMI) approach:
string _osVersion = "";
string _osServicePack = "";
string _osArchitecture = "";
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_OperatingSystem");
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject mbo in collection)
{
_osVersion = mbo.GetPropertyValue("Caption").ToString();
_osServicePack = string.Format("{0}.{1}", mbo.GetPropertyValue("ServicePackMajorVersion").ToString(), mbo.GetPropertyValue("ServicePackMinorVersion").ToString());
try
{
_osArchitecture = mbo.GetPropertyValue("OSArchitecture").ToString();
}
catch
{
// OSArchitecture only supported on Windows 7/Windows Server 2008
}
}
Console.WriteLine("osVersion : " + _osVersion);
Console.WriteLine("osServicePack : " + _osServicePack);
Console.WriteLine("osArchitecture: " + _osArchitecture);
/////////////////////////////////////////
// Test on Windows 7 64-bit
//
// osVersion : Microsoft Windows 7 Professional
// osservicePack : 1.0
// osArchitecture: 64-bit
/////////////////////////////////////////
// Test on Windows Server 2008 64-bit
// --The extra r's come from the registered trademark
//
// osVersion : Microsoftr Windows Serverr 2008 Standard
// osServicePack : 1.0
// osArchitecture: 64-bit
/////////////////////////////////////////
// Test on Windows Server 2003 32-bit
// --OSArchitecture property not supported on W2K3
//
// osVersion : Microsoft(R) Windows(R) Server 2003, Standard Edition
// osServicePack : 2.0
// osArchitecture:
OSInfo.Bits
using System;
namespace CSharp411
{
class Program
{
static void Main( string[] args )
{
Console.WriteLine( "Operation System Information" );
Console.WriteLine( "----------------------------" );
Console.WriteLine( "Name = {0}", OSInfo.Name );
Console.WriteLine( "Edition = {0}", OSInfo.Edition );
Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
Console.WriteLine( "Version = {0}", OSInfo.VersionString );
Console.WriteLine( "Bits = {0}", OSInfo.Bits );
Console.ReadLine();
}
}
}
Include the following code into a class in your project:
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool wow64Process);
public static int GetBit()
{
int MethodResult = "";
try
{
int Architecture = 32;
if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) || Environment.OSVersion.Version.Major >= 6)
{
using (Process p = Process.GetCurrentProcess())
{
bool Is64Bit;
if (IsWow64Process(p.Handle, out Is64Bit))
{
if (Is64Bit)
{
Architecture = 64;
}
}
}
}
MethodResult = Architecture;
}
catch //(Exception ex)
{
//ex.HandleException();
}
return MethodResult;
}
Use it like so:
string Architecture = "This is a " + GetBit() + "bit machine";
Use this to get the installed Windows architecture:
string getOSArchitecture()
{
string architectureStr;
if (Directory.Exists(Environment.GetFolderPath(
Environment.SpecialFolder.ProgramFilesX86))) {
architectureStr ="64-bit";
}
else {
architectureStr = "32-bit";
}
return architectureStr;
}
Given that the accepted answer is very complex. There are simpler ways. Mine is a variation of alexandrudicu's anaswer.
Given that 64-bit windows install 32-bit applications in Program Files (x86) you can check if that folder exists, using environment variables (to make up for different localizations)
e.g.
private bool Is64BitSystem
{
get
{
return Directory.Exists(Environment.ExpandEnvironmentVariables(#"%PROGRAMFILES(X86)%"));
}
}
This for me is faster and simpler. Given that I also wish to access a specific path under that folder based on OS version.
This question is for .NET 2.0 but still comes up in a google search, and nobody here mentionned that since .NET standard 1.1 / .NET core 1.0, there is now a better way to know the CPU architecture:
System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture
This should theoretically be able to differenciate between x64 and Arm64, though I didn't test it myself.
See the documentation.
Sorry for code of VB.NET, but it easy to port to C#.
It works ok on Win7, x64 with .Net Framework 4.8:
Dim r As String = ""
Using searcher As ManagementObjectSearcher = New System.Management.ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem")
Dim Information As ManagementObjectCollection = searcher.Get()
If Information IsNot Nothing Then
For Each obj As ManagementObject In Information
r = obj("Caption").ToString() & _
" - " & _
obj("OSArchitecture").ToString() ' <--- !!! "64-bit" shown here
Next
End If
MessageBox.Show(r)
End Using
Enjoy ;-)
Function Is64Bit() As Boolean
Return My.Computer.FileSystem.SpecialDirectories.ProgramFiles.Contains("Program Files (x86)")
End Function
Just see if the "C:\Program Files (x86)" exists. If not, then you are on a 32 bit OS. If it does, then the OS is 64 bit (Windows Vista or Windows 7). It seems simple enough...
I use:
Dim drivelet As String = Application.StartupPath.ToString
If Directory.Exists(drivelet(0) & ":\Program Files (x86)") Then
MsgBox("64bit")
Else
MsgBox("32bit")
End if
This gets the path where your application is launched in case you have it installed in various places on the computer. Also, you could just do the general C:\ path since 99.9% of computers out there have Windows installed in C:\.

How to get a Unique ID for the current user's logon session in windows - c#

I need to get a value that uniquely identifies the current windows user's logon session. This is for a winforms app, not ASP.NET. I'll be retrieving this from within multiple processes so it needs to return the same value when retrieved within the same logon session. It only needs to be unique on the current machine for the duration of all user sessions - e.g. until the machine is next restarted.
I think the Windows Logon Id is the right thing, but seems a bit of a pain to retrieve. Is there anything else or any easier way to get this?
I'll be using the ID to include in an address of a named pipes service to communicate between two processes running on the machine. I want to include the Logon Id to avoid conflicts when there are multiple users logged in, including perhaps multiple sessions of the same user.
The easiest way to get Session Id is to look at Process.SessionId property:
System.Diagnostics.Process.GetCurrentProcess().SessionId
The value is the same as returned by GetTokenInformation(...,TokenSessionId,...).
Note: One thing you should keep in mind is that Session Id is not a Logon Id.
For example, on Win7 elevated process launched under the same user in the same session will have different LogonId (copmaring to non-elevated one), but will have the same SessionId.
Even runniung non-elevated process with RunAs explicitly specifying credentials of the same user will create new Logon Sesison Id.
Such behavior has meaning, for example, when you map network drives. Since Vista, a process with one token LogonId will not see network dirves mapped with another LogonId, even if processes are running in the same session and under same user.
Below is the sample app that you can launch on different sessions/creds to see the difference:
using System;
using System.Runtime.InteropServices;
namespace GetCurrentSessionId
{
class Program
{
enum TokenInformationClass
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin
}
enum TokenType
{
TokenPrimary = 1,
TokenImpersonation
}
enum SecurityImpersonationLevel
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
[StructLayout(LayoutKind.Sequential)]
struct TokenStatistics
{
public Int64 TokenId;
public Int64 AuthenticationId;
public Int64 ExpirationTime;
public TokenType TokenType;
public SecurityImpersonationLevel ImpersonationLevel;
public Int32 DynamicCharged;
public Int32 DynamicAvailable;
public Int32 GroupCount;
public Int32 PrivilegeCount;
public Int64 ModifiedId;
}
struct TokenOrigin
{
public Int64 OriginatingLogonSession;
}
[DllImport("advapi32.dll", EntryPoint = "GetTokenInformation", SetLastError = true)]
static extern bool GetTokenInformation(
IntPtr tokenHandle,
TokenInformationClass tokenInformationClass,
IntPtr tokenInformation,
int tokenInformationLength,
out int ReturnLength);
public const int ERROR_INSUFFICIENT_BUFFER = 0x7a;
static void Main(string[] args)
{
try
{
Console.WriteLine("Session Id: {0}", System.Diagnostics.Process.GetCurrentProcess().SessionId);
IntPtr tokenInfo;
bool result;
int infoSize;
IntPtr hToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token;
result = GetTokenInformation(hToken, TokenInformationClass.TokenStatistics, IntPtr.Zero, 0, out infoSize);
if (!result && Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
{
tokenInfo = Marshal.AllocHGlobal(infoSize);
result = GetTokenInformation(hToken, TokenInformationClass.TokenStatistics, tokenInfo, infoSize, out infoSize);
if (result)
{
TokenStatistics tokenStats = (TokenStatistics)Marshal.PtrToStructure(tokenInfo, typeof(TokenStatistics));
Console.WriteLine("LogonId: 0x{0:X16}", tokenStats.AuthenticationId);
}
else
{
Console.Error.WriteLine("LogonId: FAILED with 0x{0:X08}", Marshal.GetLastWin32Error());
}
Marshal.FreeHGlobal(tokenInfo);
}
else
{
Console.Error.WriteLine("LogonId: FAILED with 0x{0:X08}", Marshal.GetLastWin32Error());
}
tokenInfo = Marshal.AllocHGlobal(sizeof (Int32));
result = GetTokenInformation(hToken, TokenInformationClass.TokenSessionId, tokenInfo, sizeof (Int32), out infoSize);
if (result)
{
int tokenSessionId = Marshal.ReadInt32(tokenInfo);
Console.WriteLine("TokenSessionId: {0}", tokenSessionId);
}
else
{
Console.Error.WriteLine("TokenSessionId: FAILED with 0x{0:X08}", Marshal.GetLastWin32Error());
}
Marshal.FreeHGlobal(tokenInfo);
result = GetTokenInformation(hToken, TokenInformationClass.TokenOrigin, IntPtr.Zero, 0, out infoSize);
if (!result && Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
{
tokenInfo = Marshal.AllocHGlobal(infoSize);
result = GetTokenInformation(hToken, TokenInformationClass.TokenOrigin, tokenInfo, infoSize, out infoSize);
if (result)
{
TokenOrigin tokenOrigin = (TokenOrigin) Marshal.PtrToStructure(tokenInfo, typeof (TokenOrigin));
Console.WriteLine("OriginatingSessionId: 0x{0:X16}", tokenOrigin.OriginatingLogonSession);
}
else
{
Console.WriteLine("OriginatingSessionId: FAILED with 0x{0:X08}", Marshal.GetLastWin32Error());
}
Marshal.FreeHGlobal(tokenInfo);
}
else
{
Console.WriteLine("OriginatingSessionId: FAILED with 0x{0:X08}", Marshal.GetLastWin32Error());
}
Console.WriteLine("Press any key...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.Error.WriteLine("Unexpected error: {0}", ex);
Console.ReadKey();
}
}
}
}
As I understand, what you need is this:
SID: S-1-5-5-X-Y
Name: Logon Session
Description: A logon session. The X and Y values for these SIDs are different for each session.
Well-known security identifiers in Windows operating systems
http://support.microsoft.com/kb/243330
Somebody asked for something similar here:
How to get the logon SID in C#
They have a good answer there, but I want to add my own
This is my solution:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TestLogonSid
{
public partial class Form1 : Form
{
private delegate bool EnumDesktopProc(string lpszDesktop, IntPtr lParam);
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
this.textBox1.Text = GetLogonSid.getLogonSid();
}
}
public class GetLogonSid
{
//The SID structure that identifies the user that is currently associated with the specified object.
//If no user is associated with the object, the value returned in the buffer pointed to by lpnLengthNeeded is zero.
//Note that SID is a variable length structure.
//You will usually make a call to GetUserObjectInformation to determine the length of the SID before retrieving its value.
private const int UOI_USER_SID = 4;
//GetUserObjectInformation function
//Retrieves information about the specified window station or desktop object.
[DllImport("user32.dll")]
static extern bool GetUserObjectInformation(IntPtr hObj, int nIndex, [MarshalAs(UnmanagedType.LPArray)] byte[] pvInfo, int nLength, out uint lpnLengthNeeded);
//GetThreadDesktop function
//Retrieves a handle to the desktop assigned to the specified thread.
[DllImport("user32.dll")]
private static extern IntPtr GetThreadDesktop(int dwThreadId);
//GetCurrentThreadId function
//Retrieves the thread identifier of the calling thread.
[DllImport("kernel32.dll")]
public static extern int GetCurrentThreadId();
//ConvertSidToStringSid function
//The ConvertSidToStringSid function converts a security identifier (SID) to a string format suitable for display, storage, or transmission.
//To convert the string-format SID back to a valid, functional SID, call the ConvertStringSidToSid function.
[DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool ConvertSidToStringSid(
[MarshalAs(UnmanagedType.LPArray)] byte[] pSID,
out IntPtr ptrSid);
/// <summary>
/// The getLogonSid function returns the Logon Session string
/// </summary>
/// <returns></returns>
public static string getLogonSid()
{
string sidString = "";
IntPtr hdesk = GetThreadDesktop(GetCurrentThreadId());
byte[] buf = new byte[100];
uint lengthNeeded;
GetUserObjectInformation(hdesk, UOI_USER_SID, buf, 100, out lengthNeeded);
IntPtr ptrSid;
if (!ConvertSidToStringSid(buf, out ptrSid))
throw new System.ComponentModel.Win32Exception();
try
{
sidString = Marshal.PtrToStringAuto(ptrSid);
}
catch
{
}
return sidString;
}
}
}
You can try Environment.UserDomainName & Environment.UserName
To ensure a unique id for each user session I guess you'll have to use the painful method you mentioned - How to get the logon SID in C#.
If I understand you correctly you can generate a GUID

P/Invoke for shell32.dll's SHMultiFileProperties

I'm not very good with P/Invoke. Can anyone tell me how to declare and use the following shell32.dll function in .NET?
From http://msdn.microsoft.com/en-us/library/bb762230%28VS.85%29.aspx:
HRESULT SHMultiFileProperties(
IDataObject *pdtobj,
DWORD dwFlags
);
It is for displaying the Windows Shell Properties dialog for multiple file system objects.
I already figured out how to use SHObjectProperties for one file or folder:
[DllImport("shell32.dll", SetLastError = true)]
static extern bool SHObjectProperties(uint hwnd, uint shopObjectType, [MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [MarshalAs(UnmanagedType.LPWStr)] string pszPropertyPage);
public static void ShowDialog(Form parent, FileSystemInfo selected)
{
SHObjectProperties((uint)parent.Handle, (uint)ObjectType.File, selected.FullName, null));
}
enum ObjectType
{
Printer = 0x01,
File = 0x02,
VoumeGuid = 0x04,
}
Can anyone help?
There's an IDataObject interface and a DataObject class in the .NET Framework.
[DllImport("shell32.dll", SetLastError = true)]
static extern int SHMultiFileProperties(IDataObject pdtobj, int flags);
public static void Foo()
{
var pdtobj = new DataObject();
pdtobj.SetFileDropList(new StringCollection { #"C:\Users", #"C:\Windows" });
if (SHMultiFileProperties(pdtobj, 0) != 0 /*S_OK*/)
{
throw new Win32Exception();
}
}
EDIT: I've just compiled and tested this and it works (pops up some dialog with folder appearance settings).
I maybe reading you question incorrectly, but I think you are looking for the extended file properties for files. i.e. opening windows explorer and viewing columns like attributes, owner, copyright, size, date created etc?
There is an API in Shell32 called GetDetailsOf that will provide this information. A starting article on codeproject
Cheers,
John

Categories

Resources