473,857 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SetLocalTime/SetSystemTime P/Invoke call fails under Vista (even witha requireAdminist rator manifest)


I am posting at the end of this post some code that P/Invoke's
SetSystemTime to set the local system time. This call fails -- i.e
the time is not set and the API returns false. However calling
Marshal.GetLast Win32Error immediately afterwards returns an errorcode
of 0 indicating that the operation somehow executed successfully.

This is a plain vanilla console app written in C#. It runs on vista
and has a manifest embedded in it that has 'requireAdminis trator'
privilege level on it. The logged on user belongs to the
administrator group and the UAC is set at "prompt for consent".

What am I missing? (FWIW, I didn't write the P/Invoke signatures
myself. I just lifted them out of various postings on the internet --
is there a mistake in that somewhere)?

It seems similar to what was reported here:
http://forums.microsoft.com/MSDN/Sho...07068&SiteID=1

/********** CODE *************** *****/
using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Runtime. InteropServices ;
using System.Componen tModel;

namespace VistaUACTest
{
class Program
{
[StructLayoutAtt ribute(LayoutKi nd.Sequential)]
public struct SystemTime
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}

[DllImport("kern el32.dll")]
private static extern bool SetLocalTime(re f SystemTime
systime);

[DllImport("kern el32.dll")]
private static extern bool SetSystemTime(r ef SystemTime
systime);

private const int ANYSIZE_ARRAY = 1;
private const string SE_SYSTEMTIME_N AME =
"SeSystemtimePr ivilege";
private const int SE_PRIVILEGE_EN ABLED = 0x00000002;
private const int TOKEN_QUERY = 0x0008;
private const int TOKEN_ADJUST_PR IVILEGES = 0x0020;

[StructLayout(La youtKind.Sequen tial)]
public struct LUID
{
public int LowPart;
public int HighPart;
}

[StructLayout(La youtKind.Sequen tial)]
public struct LUID_AND_ATTRIB UTES
{
public LUID Luid;
public int Attributes;
}

[StructLayout(La youtKind.Sequen tial)]
public struct TOKEN_PRIVILEGE S
{
public int PrivilegeCount;
[MarshalAs(Unman agedType.ByValA rray, SizeConst =
ANYSIZE_ARRAY)]
public LUID_AND_ATTRIB UTES[] Privileges;
}

[DllImport("adva pi32.dll", CharSet = CharSet.Auto)]
public static extern bool OpenProcessToke n(int ProcessHandle,
int DesiredAccess, ref int TokenHandle);

[DllImport("kern el32.dll", CharSet = CharSet.Auto)]
public static extern int GetCurrentProce ss();

[DllImport("adva pi32.dll", CharSet = CharSet.Auto)]
public static extern bool LookupPrivilege Value(string
lpSystemName, string lpName,

[MarshalAs(Unman agedType.Struct )] ref LUID lpLuid);

[DllImport("adva pi32.dll", CharSet = CharSet.Auto)]
public static extern bool AdjustTokenPriv ileges(int
TokenHandle,
int
DisableAllPrivi leges,

[MarshalAs(Unman agedType.Struct )] ref TOKEN_PRIVILEGE S NewState,
int
BufferLength,

[MarshalAs(Unman agedType.Struct )] ref TOKEN_PRIVILEGE S PreviousState,
ref
int ReturnLength);

static void Main(string[] args)
{
try
{
// because the docs for SetSystemTime says that the
SE_SYSTEMTIME_N AME privilege is disabled by default
// this call doesn't really help though
AdjustPrivilege s();
SystemTime st = new SystemTime();
st.hour = 10;
if (!SetSystemTime (ref st))
{
// the return value says the call failed, however
Marshal.GetLast Win32Error() says the previous P/Invoke operation
// completed successfully (the default ctor of
Win32Exception calls GetLastWin32Err or)
throw new Win32Exception( );
}
}
catch (Exception ex)
{
Console.WriteLi ne(ex);
}
Console.Read();
}

public static bool AdjustPrivilege s()
{
TOKEN_PRIVILEGE S tkNew = new TOKEN_PRIVILEGE S();
tkNew.Privilege s = new LUID_AND_ATTRIB UTES[ANYSIZE_ARRAY];
TOKEN_PRIVILEGE S tkOld = new TOKEN_PRIVILEGE S();
tkOld.Privilege s = new LUID_AND_ATTRIB UTES[ANYSIZE_ARRAY];

LUID luid = new LUID();
int token = -1;
int oldluidSize = 0;

if (LookupPrivileg eValue(null, SE_SYSTEMTIME_N AME, ref
luid))
{
if (OpenProcessTok en(GetCurrentPr ocess(),
TOKEN_ADJUST_PR IVILEGES | TOKEN_QUERY, ref token))
{
tkNew.Privilege Count = 1;
tkNew.Privilege s[0].Attributes =
SE_PRIVILEGE_EN ABLED;
tkNew.Privilege s[0].Luid = luid;
int luidSize =
Marshal.SizeOf( typeof(TOKEN_PR IVILEGES));
if (AdjustTokenPri vileges(token, 0, ref tkNew,
luidSize, ref tkOld, ref oldluidSize))
{
return true;
}
}
}
return false;
}
}
}
/************ CODE *************** *********/
Jun 27 '08 #1
2 8428
Well, the signatures for the time APIs are correct (mostly) along with your
SystemTime struct. Win32 BOOL is actually an int. Yes I know the marshalling
will happen automatically, I'm just picky. Might want to turn off the UAC
and try it again to see if that's causing the problem, I had no problem on
my machine with UAC off. If so, there's a problem with how you're elevating
the privileges of the current user.
<rd*****@gmail. comwrote in message
news:d5******** *************** ***********@l42 g2000hsc.google groups.com...
>
I am posting at the end of this post some code that P/Invoke's
SetSystemTime to set the local system time. This call fails -- i.e
the time is not set and the API returns false. However calling
Marshal.GetLast Win32Error immediately afterwards returns an errorcode
of 0 indicating that the operation somehow executed successfully.

This is a plain vanilla console app written in C#. It runs on vista
and has a manifest embedded in it that has 'requireAdminis trator'
privilege level on it. The logged on user belongs to the
administrator group and the UAC is set at "prompt for consent".

What am I missing? (FWIW, I didn't write the P/Invoke signatures
myself. I just lifted them out of various postings on the internet --
is there a mistake in that somewhere)?

It seems similar to what was reported here:
http://forums.microsoft.com/MSDN/Sho...07068&SiteID=1

/********** CODE *************** *****/
using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Runtime. InteropServices ;
using System.Componen tModel;

namespace VistaUACTest
{
class Program
{
[StructLayoutAtt ribute(LayoutKi nd.Sequential)]
public struct SystemTime
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}

[DllImport("kern el32.dll")]
private static extern bool SetLocalTime(re f SystemTime
systime);

[DllImport("kern el32.dll")]
private static extern bool SetSystemTime(r ef SystemTime
systime);

private const int ANYSIZE_ARRAY = 1;
private const string SE_SYSTEMTIME_N AME =
"SeSystemtimePr ivilege";
private const int SE_PRIVILEGE_EN ABLED = 0x00000002;
private const int TOKEN_QUERY = 0x0008;
private const int TOKEN_ADJUST_PR IVILEGES = 0x0020;

[StructLayout(La youtKind.Sequen tial)]
public struct LUID
{
public int LowPart;
public int HighPart;
}

[StructLayout(La youtKind.Sequen tial)]
public struct LUID_AND_ATTRIB UTES
{
public LUID Luid;
public int Attributes;
}

[StructLayout(La youtKind.Sequen tial)]
public struct TOKEN_PRIVILEGE S
{
public int PrivilegeCount;
[MarshalAs(Unman agedType.ByValA rray, SizeConst =
ANYSIZE_ARRAY)]
public LUID_AND_ATTRIB UTES[] Privileges;
}

[DllImport("adva pi32.dll", CharSet = CharSet.Auto)]
public static extern bool OpenProcessToke n(int ProcessHandle,
int DesiredAccess, ref int TokenHandle);

[DllImport("kern el32.dll", CharSet = CharSet.Auto)]
public static extern int GetCurrentProce ss();

[DllImport("adva pi32.dll", CharSet = CharSet.Auto)]
public static extern bool LookupPrivilege Value(string
lpSystemName, string lpName,

[MarshalAs(Unman agedType.Struct )] ref LUID lpLuid);

[DllImport("adva pi32.dll", CharSet = CharSet.Auto)]
public static extern bool AdjustTokenPriv ileges(int
TokenHandle,
int
DisableAllPrivi leges,

[MarshalAs(Unman agedType.Struct )] ref TOKEN_PRIVILEGE S NewState,
int
BufferLength,

[MarshalAs(Unman agedType.Struct )] ref TOKEN_PRIVILEGE S PreviousState,
ref
int ReturnLength);

static void Main(string[] args)
{
try
{
// because the docs for SetSystemTime says that the
SE_SYSTEMTIME_N AME privilege is disabled by default
// this call doesn't really help though
AdjustPrivilege s();
SystemTime st = new SystemTime();
st.hour = 10;
if (!SetSystemTime (ref st))
{
// the return value says the call failed, however
Marshal.GetLast Win32Error() says the previous P/Invoke operation
// completed successfully (the default ctor of
Win32Exception calls GetLastWin32Err or)
throw new Win32Exception( );
}
}
catch (Exception ex)
{
Console.WriteLi ne(ex);
}
Console.Read();
}

public static bool AdjustPrivilege s()
{
TOKEN_PRIVILEGE S tkNew = new TOKEN_PRIVILEGE S();
tkNew.Privilege s = new LUID_AND_ATTRIB UTES[ANYSIZE_ARRAY];
TOKEN_PRIVILEGE S tkOld = new TOKEN_PRIVILEGE S();
tkOld.Privilege s = new LUID_AND_ATTRIB UTES[ANYSIZE_ARRAY];

LUID luid = new LUID();
int token = -1;
int oldluidSize = 0;

if (LookupPrivileg eValue(null, SE_SYSTEMTIME_N AME, ref
luid))
{
if (OpenProcessTok en(GetCurrentPr ocess(),
TOKEN_ADJUST_PR IVILEGES | TOKEN_QUERY, ref token))
{
tkNew.Privilege Count = 1;
tkNew.Privilege s[0].Attributes =
SE_PRIVILEGE_EN ABLED;
tkNew.Privilege s[0].Luid = luid;
int luidSize =
Marshal.SizeOf( typeof(TOKEN_PR IVILEGES));
if (AdjustTokenPri vileges(token, 0, ref tkNew,
luidSize, ref tkOld, ref oldluidSize))
{
return true;
}
}
}
return false;
}
}
}
/************ CODE *************** *********/
Jun 27 '08 #2
On May 16, 8:30 pm, "Jeff Winn" <jw...@nospam.c omwrote:
Well, the signatures for the time APIs are correct (mostly) along with your
SystemTime struct. Win32 BOOL is actually an int. Yes I know the marshalling
will happen automatically, I'm just picky. Might want to turn off the UAC
and try it again to see if that's causing the problem, I had no problem on
my machine with UAC off. If so, there's a problem with how you're elevating
the privileges of the current user.
Jeff
Thanks for responding. The privilege adjusting code is there for no
particular reason. I believe the admin privileges already include
SE_SYSTEMTIME_N AME (which is enabled).

In any case, the funny thing is I can't get it to work even:

* if I run this application from a elevated command prompt
* if I mark the manifest as 'requireAdminis trator' and grant consent
to the UAC dialog that pops up.

I thought the latter option was at least morally the same as turning
off UAC? I will turn off UAC and see how that goes.

There is another weird thing going on here. SetSystemTime seems to
return false indicating the call failed (and the time obviously isn't
set), however if I call Marshal.GetLast Win32Error() immediately after,
it returns 0 saying "the operation completed successfully".

Does that make sense to you?
Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
1560
by: smerf | last post by:
I haven't delved into the beast that is Vista from a programming standpoint yet. But, if the blog at http://west-wind.com/WebLog/posts/4983.aspx is any indication of what we're in for.....I say we all refuse to deploy this monstrosity and make Redmond get it right. There is NO WAY people are going to go for a system this locked down. Never....ever........ever!
4
3677
by: Podi | last post by:
I am trying to set the system time on my Windows computer, but avoid using the DOS command (date, time). Does anyone know what parameter to pass to function SetLocalTime? CSharp ref http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/813b4ef504f77a43/24fc37c6c9148961?lnk=gst&q=SetLocalTime&rnum=2#24fc37c6c9148961 Thanks a bunch, P
11
8002
by: =?Utf-8?B?Um9iS2lubmV5MQ==?= | last post by:
Hello, We are testing and tweaking some of our software to run on Vista, but it turns out that we are having problems with one of our programs. Here is our code: // attempt an experiment to register an OCX object in silient mode try {
3
2862
by: =?Utf-8?B?Um9iS2lubmV5MQ==?= | last post by:
Hello, This is a continuation of a question I was working with Willy and Kevin last week (both provided excellent information). I am still having troubles in final stages. I am trying to get an OCX to register on Vista with my ClickOnce app. Willy instructed how to embed a manifest into the exe to request admin privilages (requireAdministrator) upon launch (so the UAC window would confirm to the user they want to run the program).
3
4004
by: gourmet | last post by:
Hello! I need to restart the "Windows Audio Service" (audiosrv) via C#. I'm using the ServiceController Class to do this. It is no problem under XP and no problem under vista if UAC is disabled. But with enabled UAC i'm getting a "access refused" exception. I also tried to do it via console with "net start ..." but the same error appears. Three questions:
9
2662
by: Bruce | last post by:
Under Vista, the Dev Studio program installer adds a desktop shortcut to the Desktop. (.Net application.) The shortcut does not have a context menu item to run as administrator. However, if you create a shortcut manually from the exe file it does have a context menu item to run as administrator. Why are they different? The big question is, why does the program only run if you run as admin???
13
9095
by: Mark Rae | last post by:
Hi, I have used the code below to return the default printer in 32-bit WinXP Pro, but now that I am running 64-bit Vista Business I'm getting an error: using System.Drawing.Printing; using (PrintDocument objPrintDocument = new PrintDocument()) { string strDefaultPrinter =
2
1731
by: 13Rockes | last post by:
I am in the process of writing programs using VB6 in XP Pro. However, I am thinking about starting over using VB2005 as my company is migrating to Vista. Two questions... What kinds of problems will I have installing and running my VB6 app under Vista? If I develop VB2005 apps under XP, what kinds of problems will I have
1
2009
by: rufusking | last post by:
My requirement is to change the IP Address of local system programatically using .net. IP Address should change to 10.1.2.100, subnet mask = 255.255.255.0, default gateway=10.1.2.1 I have created a small C# Console application in Visual Studio 2005 which change the IP address of the local system. I execute the following batch file using Process.Start("ipchange1.bat"); Content of batch file is: set path=c:\Windows\System32 netsh...
0
11083
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10808
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10394
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9549
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7940
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7104
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5774
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5971
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.