473,395 Members | 1,631 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Interop Woes

If anyone can figure out how to implement the following C++ function in C#
using interop, I'd be very appreciative.

I have not been successful in getting it to work correctly using interop
(without using unsafe code) because of the pointer issues of the structure.

Thanks,
Chris

//------------------------------------------------------------

HANDLE __stdcall CreateAllAccessMutex(BOOL bInitialOwner, const wchar_t
*pszName)
{
HANDLE rc = NULL;
SECURITY_DESCRIPTOR sd;
SECURITY_ATTRIBUTES sa;

// A security descriptor with a NULL DACL must be used because this
function can be initially called
// by an application running as a service which will create the mutex with
a default security
// descriptor that does not allow user-mode applications to open the mutex
by name with CreateMutex.

if (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) //
initialize the security descriptor
{
if (SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE)) // add a NULL
DACL to the security descriptor
{
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = FALSE;

rc = CreateMutexW(&sa, bInitialOwner, pszName);
}
}

return rc;
}

Nov 16 '05 #1
1 4841
Better would be to derive from WaitHandle but following class could give you
a head start :

[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_DESCRIPTOR
{
public byte Revision;
public byte Sbz1;
public ushort Control;
public uint Owner;
public uint Group;
public uint Sacl;
public uint Dacl;
}

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
internal int nLength;
internal IntPtr pSecurityDescriptor;
internal bool bInheritHandle;
}

class Win32NamedMutex : IDisposable
{
[DllImport("kernel32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern IntPtr CreateMutex(
ref SECURITY_ATTRIBUTES pSecurityAttributes, // pointer to sa
bool bInitialOwner,
string lpName
);
[DllImport("kernel32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool ReleaseMutex(
IntPtr handle
);

[DllImport("advapi32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool InitializeSecurityDescriptor(
IntPtr pSecurityDescriptor, // pointer to sd
int dwRevision // revision must be SECURITY_DESCRIPTOR_REVISION (1)
);
[DllImport("advapi32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool SetSecurityDescriptorDacl(
IntPtr pSecurityDescriptor, // pointer to sd
bool bDaclPresent,
IntPtr pDacl,
bool bDaclDefaulted
);
[DllImport("advapi32", SetLastError=true),
SuppressUnmanagedCodeSecurityAttribute]
static extern bool IsValidSecurityDescriptor(IntPtr pSecurityDescriptor);
// pointer to sd
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
IntPtr pSd;
IntPtr handle;
private bool disposed = false;

public IntPtr CreateNamedMutex(string name, ref bool initialOwner)
{
handle = IntPtr.Zero;
if (CreateSaWithNullDaclSd())
{
handle = CreateMutex(ref sa, initialOwner, name);
if (handle == IntPtr.Zero)
{
Console.WriteLine("{0}", Marshal.GetLastWin32Error());
}
else {
if(Marshal.GetLastWin32Error() == 183) //ERROR_ALREADY_EXISTS
initialOwner = false;
}
}
return handle;
}
private bool CreateSdWithNullDacl()
{
bool ret = false;
sd = new SECURITY_DESCRIPTOR();
pSd = Marshal.AllocHGlobal( Marshal.SizeOf(sd) );
Marshal.StructureToPtr(sd, pSd, true);
// Initialize SD with revision level 1 (mandatory)
if(InitializeSecurityDescriptor(pSd, 1))
{
// set NULL DACL in SD, this sets "everyone" access privileges
if (SetSecurityDescriptorDacl(pSd, true, IntPtr.Zero, true))
{
ret = IsValidSecurityDescriptor(pSd); // set ret = true if valid SD
}
else {ret = false;}
}
return ret;
}
private bool CreateSaWithNullDaclSd()
{
if (CreateSdWithNullDacl())
{
sa = new SECURITY_ATTRIBUTES();
sa.pSecurityDescriptor = pSd;
sa.bInheritHandle = false;
sa.nLength = Marshal.SizeOf(sa);
return true;
}
return false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
// Release unmanaged Mutex.
ReleaseMutex(this.handle);
handle = IntPtr.Zero;
}
disposed = true;
}
~Win32NamedMutex()
{
Dispose(false);
// BUG BUG, finalizer should never be called. Object should be Disposed
by client.
// Failed to call dispose, will throw in debug build
#if DEBUG
throw new Exception("Finalizer called on disposable object");
#endif
}
}

Use case:

IntPtr handle;
bool owner = true;
using(Win32NamedMutex ws = new Win32NamedMutex())
{
handle = ws.CreateNamedMutex("Global\\myMutex", ref owner);
if (owner != true)
{
// already owned wait until handle signaled
AutoResetEvent wh = new AutoResetEvent(false);
wh.Handle = handle;
wh.WaitOne();
}
else
{
.....// Do some work while owning Mutex

}
} // release mutex resources
.....
Willy.

"Chris B." <ch********@hotmail.com> wrote in message
news:uM*************@TK2MSFTNGP12.phx.gbl...
If anyone can figure out how to implement the following C++ function in C#
using interop, I'd be very appreciative.

I have not been successful in getting it to work correctly using interop
(without using unsafe code) because of the pointer issues of the
structure.

Thanks,
Chris

//------------------------------------------------------------

HANDLE __stdcall CreateAllAccessMutex(BOOL bInitialOwner, const wchar_t
*pszName)
{
HANDLE rc = NULL;
SECURITY_DESCRIPTOR sd;
SECURITY_ATTRIBUTES sa;

// A security descriptor with a NULL DACL must be used because this
function can be initially called
// by an application running as a service which will create the mutex
with
a default security
// descriptor that does not allow user-mode applications to open the
mutex
by name with CreateMutex.

if (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) //
initialize the security descriptor
{
if (SetSecurityDescriptorDacl(&sd, TRUE, NULL, FALSE)) // add a NULL
DACL to the security descriptor
{
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = &sd;
sa.bInheritHandle = FALSE;

rc = CreateMutexW(&sa, bInitialOwner, pszName);
}
}

return rc;
}

Nov 16 '05 #2

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

Similar topics

7
by: Mark | last post by:
O, woe is me, to have seen what I have seen, see what I see! (That's Shakespeare for those who were wondering what I'm on about) I am "having fun" with cookies. And I wonder if I have...
0
by: Cedric | last post by:
This is a 3 weeks old problem, but having found a solution (and having looked for one here, finding only this message), I'm replying now. From: Jive (someone@microsoft.com) Subject: Upgrade...
0
by: keefah | last post by:
Hi, I'm writing a C# web app that uses Outlook to send email. I use a reference to the Microsoft Outlook 11.0 Object Library, but it's giving me problems. I tracked down some stuff on the Net...
0
by: lacour | last post by:
I can't seem to figure out the difference between adding a COM dll reference in VS2003 and by using TLBIMP. I have a COM dll that references another COM dll, and I want the syntax of my...
8
by: Rob Edwards | last post by:
When trying to add the Microsoft CDO for Exchange Management Library (aka CDOEXM.dll) I receive the following message: "A reference to 'Microsoft CDO for Exchange Management Library' could not be...
7
by: R Reyes | last post by:
Can someone please explain to me why I can't get the MS Word Interop assembly to work in my VS2005 project? I'm trying to manipulate MS Word from my Web Form application and I can't get passed...
2
by: JC | last post by:
Anybody knows what problem has this code? I think, in the Garbage Collector? You know the Solution? The program in the test's case, whit 350 contacts, run OK before number 86. The error is a...
1
by: allbelonging | last post by:
C#.Net Outlook 2003 automation (programmatically) with Office.Interop.Outlook Problem: I have my outlook 2003 configured with multiple mailbox on my local machine. I want to specify the mailbox...
0
by: Tina | last post by:
I've gotten this before where it says there is a problem with Interop.MSDASC but I can't remember what causes this. This is a 1.1 app I'm trying to debug in vs2005. It was running yesterday just...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...

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.