473,799 Members | 3,026 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 CreateAllAccess Mutex(BOOL bInitialOwner, const wchar_t
*pszName)
{
HANDLE rc = NULL;
SECURITY_DESCRI PTOR sd;
SECURITY_ATTRIB UTES 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 (InitializeSecu rityDescriptor( &sd, SECURITY_DESCRI PTOR_REVISION)) //
initialize the security descriptor
{
if (SetSecurityDes criptorDacl(&sd , TRUE, NULL, FALSE)) // add a NULL
DACL to the security descriptor
{
sa.nLength = sizeof(sa);
sa.lpSecurityDe scriptor = &sd;
sa.bInheritHand le = FALSE;

rc = CreateMutexW(&s a, bInitialOwner, pszName);
}
}

return rc;
}

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

[StructLayout(La youtKind.Sequen tial)]
internal struct SECURITY_DESCRI PTOR
{
public byte Revision;
public byte Sbz1;
public ushort Control;
public uint Owner;
public uint Group;
public uint Sacl;
public uint Dacl;
}

[StructLayout(La youtKind.Sequen tial)]
public struct SECURITY_ATTRIB UTES
{
internal int nLength;
internal IntPtr pSecurityDescri ptor;
internal bool bInheritHandle;
}

class Win32NamedMutex : IDisposable
{
[DllImport("kern el32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern IntPtr CreateMutex(
ref SECURITY_ATTRIB UTES pSecurityAttrib utes, // pointer to sa
bool bInitialOwner,
string lpName
);
[DllImport("kern el32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern bool ReleaseMutex(
IntPtr handle
);

[DllImport("adva pi32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern bool InitializeSecur ityDescriptor(
IntPtr pSecurityDescri ptor, // pointer to sd
int dwRevision // revision must be SECURITY_DESCRI PTOR_REVISION (1)
);
[DllImport("adva pi32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern bool SetSecurityDesc riptorDacl(
IntPtr pSecurityDescri ptor, // pointer to sd
bool bDaclPresent,
IntPtr pDacl,
bool bDaclDefaulted
);
[DllImport("adva pi32", SetLastError=tr ue),
SuppressUnmanag edCodeSecurityA ttribute]
static extern bool IsValidSecurity Descriptor(IntP tr pSecurityDescri ptor);
// pointer to sd
SECURITY_ATTRIB UTES sa;
SECURITY_DESCRI PTOR sd;
IntPtr pSd;
IntPtr handle;
private bool disposed = false;

public IntPtr CreateNamedMute x(string name, ref bool initialOwner)
{
handle = IntPtr.Zero;
if (CreateSaWithNu llDaclSd())
{
handle = CreateMutex(ref sa, initialOwner, name);
if (handle == IntPtr.Zero)
{
Console.WriteLi ne("{0}", Marshal.GetLast Win32Error());
}
else {
if(Marshal.GetL astWin32Error() == 183) //ERROR_ALREADY_E XISTS
initialOwner = false;
}
}
return handle;
}
private bool CreateSdWithNul lDacl()
{
bool ret = false;
sd = new SECURITY_DESCRI PTOR();
pSd = Marshal.AllocHG lobal( Marshal.SizeOf( sd) );
Marshal.Structu reToPtr(sd, pSd, true);
// Initialize SD with revision level 1 (mandatory)
if(InitializeSe curityDescripto r(pSd, 1))
{
// set NULL DACL in SD, this sets "everyone" access privileges
if (SetSecurityDes criptorDacl(pSd , true, IntPtr.Zero, true))
{
ret = IsValidSecurity Descriptor(pSd) ; // set ret = true if valid SD
}
else {ret = false;}
}
return ret;
}
private bool CreateSaWithNul lDaclSd()
{
if (CreateSdWithNu llDacl())
{
sa = new SECURITY_ATTRIB UTES();
sa.pSecurityDes criptor = pSd;
sa.bInheritHand le = false;
sa.nLength = Marshal.SizeOf( sa);
return true;
}
return false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFina lize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.dispos ed)
{
// Release unmanaged Mutex.
ReleaseMutex(th is.handle);
handle = IntPtr.Zero;
}
disposed = true;
}
~Win32NamedMute x()
{
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("Fina lizer called on disposable object");
#endif
}
}

Use case:

IntPtr handle;
bool owner = true;
using(Win32Name dMutex ws = new Win32NamedMutex ())
{
handle = ws.CreateNamedM utex("Global\\m yMutex", 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********@hot mail.com> wrote in message
news:uM******** *****@TK2MSFTNG P12.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 CreateAllAccess Mutex(BOOL bInitialOwner, const wchar_t
*pszName)
{
HANDLE rc = NULL;
SECURITY_DESCRI PTOR sd;
SECURITY_ATTRIB UTES 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 (InitializeSecu rityDescriptor( &sd, SECURITY_DESCRI PTOR_REVISION)) //
initialize the security descriptor
{
if (SetSecurityDes criptorDacl(&sd , TRUE, NULL, FALSE)) // add a NULL
DACL to the security descriptor
{
sa.nLength = sizeof(sa);
sa.lpSecurityDe scriptor = &sd;
sa.bInheritHand le = FALSE;

rc = CreateMutexW(&s a, 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
1721
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 missed something obvious.
0
1529
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 woes: Numeric, gnuplot, and Python 2.4 Date: 2004-12-11 18:45:10 PST > Here's my sitch: > > I use gnuplot.py at work, platform Win32. > I want to upgrade to Python 2.4.
0
2292
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 about the global assembly cache (GAC) and primary interop assemblies (PIA) and so forth, and did all the recommendations, in terms of tweeking Office, installing the .NET Office stuff for framework 1.1, etc. I got it to the point where it compiles ok,...
0
2794
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 interop-filenames to be interop.<NameOfCOMDLL>.dll I now make the first interop file tlbimp COM1.dll /out:interop.COM1.dll /namespace:COM1
8
3426
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 added. Converting the type library to a .Net assembly failed. A depended type library 'CDO' could not be converted to a .NET assembly. A dependent type library 'ADODB' could not be converted to a .NET assembly. Item has already been added." ...
7
10964
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 this screen below. Please help, thanks in advance... Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify...
2
7305
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 "Array index out of bounds". Microsoft.Office.Interop.Outlook._Application olApp = new Microsoft.Office.Interop.Outlook.ApplicationClass(); Microsoft.Office.Interop.Outlook._NameSpace olNs = olApp.GetNamespace("MAPI");
1
2872
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 and server (Exchange server mail box) to connect and then save the mailitems(from Inbox or any other folder) based on a filter to a*.msg file. I want to achieve this using only one Interop dll if this is possible. Tried so far:
0
2060
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 fine. Help! T Server Error in '/VT.Users' Application. -------------------------------------------------------------------------------- Configuration Error
0
9688
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10491
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...
0
10268
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9079
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
7571
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
5467
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
5593
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4146
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.