473,769 Members | 6,926 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Marshal.AllocHG lobal failure after calling GetTokenInforma tion

I have been banging my head against the wall for a while now, and can't
seem to id the problem. I've been through a ton of posts and the code
doesn't seem any different. Can anybody see it?

When I call to GetTokenInforma tion I receive a buffer size (see
//HERE... comment in code), but when I let the code continue, asp.net
just sits there returning nothing, apparently on the
Marshal.AllocHG lobal call.

Here's the library function:

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~
using System;
using System.Collecti ons.Specialized ;
using System.Director yServices;
using System.Runtime. InteropServices ;
using System.Security .Principal;
using System.Text.Reg ularExpressions ;
namespace foobar.Library
{
public class AdFunctions
{
enum TOKEN_INFORMATI ON_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges ,
TokenOwner,
TokenPrimaryGro up,
TokenDefaultDac l,
TokenSource,
TokenType,
TokenImpersonat ionLevel,
TokenStatistics ,
TokenRestricted Sids,
TokenSessionId,
TokenGroupsAndP rivileges,
TokenSessionRef erence,
TokenSandBoxIne rt,
TokenAuditPolic y,
TokenOrigin
}

public struct TOKEN_USER
{
public SID_AND_ATTRIBU TES User; // a single SID_AND_ATTRIBU TES
struct
}

public struct TOKEN_GROUPS
{
public int GroupCount; // DWORD number of groups
public SID_AND_ATTRIBU TES[] Groups; // array of SID_AND_ATTRIBU TES
structs
}

public struct SID_AND_ATTRIBU TES
{
public IntPtr Sid; // pointer to a sid
public int Attributes; // DWORD attributes
}
//[DllImport("adva pi32.dll", CharSet=CharSet .Auto)]
//static extern bool ConvertSidToStr ingSid( IntPtr pSID,
[In,Out,MarshalA s(UnmanagedType .LPTStr)] ref string pStringSid);

// Using IntPtr for pSID insted of Byte[]
[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertSidToStr ingSid(IntPtr pSID, out IntPtr
pSid);

[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertStringSi dToSid( string sStringSid, out
IntPtr pSID );

[DllImport("adva pi32.dll", SetLastError=tr ue)]
static extern bool GetTokenInforma tion(
IntPtr TokenHandle,
TOKEN_INFORMATI ON_CLASS TokenInformatio nClass,
IntPtr TokenInformatio n,
int TokenInformatio nLength,
out int ReturnLength);

[DllImport("kern el32.dll")]
static extern IntPtr LocalFree(IntPt r hMem);

public int GetGroupSidsFro mToken(IntPtr pToken, ref string[] aSids)
{
int iTokenInfoLengt h = 0;
bool bResult = true;

// first call gets length of TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups, IntPtr.Zero, 0, out
iTokenInfoLengt h );

//HERE if I uncomment this, the call returns an integer rapidly
//return iTokenInfoLengt h;

// if we got a return, continue
if ( iTokenInfoLengt h > 0 )
{
// allocate a memory buffer for the TokenInformatio n
IntPtr pTokenInfo = Marshal.AllocHG lobal( iTokenInfoLengt h );

// get the TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups , pTokenInfo, iTokenInfoLengt h, out
iTokenInfoLengt h ) ;
if ( bResult == false ) { return 2; }

// convert the TokenInformatio n to a TOKEN_GROUPS struct
TOKEN_GROUPS TokenGroups = ( TOKEN_GROUPS )Marshal.PtrToS tructure(
pTokenInfo , typeof( TOKEN_GROUPS ) ) ;

// loop through the groups
for ( int i=0; i < TokenGroups.Gro upCount; i++ )
{
IntPtr pSid = IntPtr.Zero;

// get the string representation of the sid
bResult = ConvertSidToStr ingSid( TokenGroups.Gro ups[i].Sid, out
pSid );
if ( bResult == false ) { return 3; }

// put it into a c# string and free the memory
string sSid = Marshal.PtrToSt ringAuto( pSid );
LocalFree(pSid) ;

// add it to the array reference
aSids[i] = sSid;
}
}
else
{
// GetTokenInforma tion returned a 0 length
return 1;
}

// all set
return 0;
}


}
}

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

Here's the code behind file that calls it:

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Security .Principal;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

using foobar.Library;

namespace Users
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class Default : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Labe l lblStatusLine;

private void Page_Load(objec t sender, System.EventArg s e)
{
Trace.Write("de bug", "Page_Load: entered function");
Trace.Write("de bug", "Page_Load: user id is " +
System.Web.Http Context.Current .User.Identity. Name.ToString() );
Trace.Write("de bug", "Page_Load: process id is " +
WindowsIdentity .GetCurrent().N ame.ToString() );

string[] aSids = new string[200];
Trace.Write("de bug", "Page_Load: created array" );

AdFunctions oAdFunctions = new AdFunctions();
Trace.Write("de bug", "Page_Load: created AdFunctions object" );

int iReturn =
oAdFunctions.Ge tGroupSidsFromT oken(WindowsIde ntity.GetCurren t().Token,
ref aSids);
Trace.Write("de bug", "Page_Load: AdFunctions.Get GroupSidsFromTo ken
returned " + iReturn.ToStrin g() );

if ( iReturn == 0 )
{
// TODO color the output
lblStatusLine.T ext = "ok...";
}
else
{
lblStatusLine.T ext = Application["ProductNam e"] + " could not
retrive your logon groups. Please contact your administrator
(GetGroupSidsFr omToken:" + iReturn.ToStrin g() + ").";
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion
}
}

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

and finally the aspx page:

// ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~

<%@ Page language="c#" Codebehind="Def ault.aspx.cs"
AutoEventWireup ="false" Inherits="Users .Default" Trace="True"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1 </title>
<meta name="GENERATOR " Content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" Content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema"
content="http://schemas.microso ft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<asp:Label id="lblStatusLi ne" style="Z-INDEX: 101; LEFT: 160px;
POSITION: absolute; TOP: 760px"
runat="server" Width="872px"></asp:Label>
</form>
</body>
</HTML>

Nov 17 '05 #1
1 4217
I managed to fix this, the fixed code is below:

thanks to Mattias from the post "How to call Win32 Native API
GetTokenInforma tion() using C#?"

public class Misc
{

public Array redim(Array arrToResize, int length)
{
// from http://www.code101.com/Code101/Displ...le.aspx?cid=54
Type t= arrToResize.Get Type().GetEleme ntType();
Array newArray=Array. CreateInstance( t,length);
Array.Copy(arrT oResize,0,newAr ray,0,Math.Min( arrToResize.Len gth,length));
return newArray;
}
}

public class AdFunctions
{
enum TOKEN_INFORMATI ON_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges ,
TokenOwner,
TokenPrimaryGro up,
TokenDefaultDac l,
TokenSource,
TokenType,
TokenImpersonat ionLevel,
TokenStatistics ,
TokenRestricted Sids,
TokenSessionId,
TokenGroupsAndP rivileges,
TokenSessionRef erence,
TokenSandBoxIne rt,
TokenAuditPolic y,
TokenOrigin
}

public struct TOKEN_USER
{
public SID_AND_ATTRIBU TES User; // a single SID_AND_ATTRIBU TES
struct
}

[StructLayout(La youtKind.Sequen tial)]
public struct TOKEN_GROUPS
{
public int GroupCount; // DWORD number of groups
public SID_AND_ATTRIBU TES[] Groups; // array of SID_AND_ATTRIBU TES
structs
}

[StructLayout(La youtKind.Sequen tial)]
public struct SID_AND_ATTRIBU TES
{
public IntPtr Sid; // pointer to a sid
public int Attributes; // DWORD attributes
}
//[DllImport("adva pi32.dll", CharSet=CharSet .Auto)]
//static extern bool ConvertSidToStr ingSid( IntPtr pSID,
[In,Out,MarshalA s(UnmanagedType .LPTStr)] ref string pStringSid);

// Using IntPtr for pSID insted of Byte[]
[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertSidToStr ingSid(IntPtr pSID, out IntPtr
pSid);

[DllImport("adva pi32.dll", CharSet=CharSet .Auto, SetLastError=tr ue)]
static extern bool ConvertStringSi dToSid( string sStringSid, out
IntPtr pSID );

[DllImport("adva pi32.dll", SetLastError=tr ue)]
static extern bool GetTokenInforma tion(
IntPtr TokenHandle,
TOKEN_INFORMATI ON_CLASS TokenInformatio nClass,
IntPtr TokenInformatio n,
int TokenInformatio nLength,
out int ReturnLength);

[DllImport("kern el32.dll")]
static extern IntPtr LocalFree(IntPt r hMem);

public int GetGroupSidsFro mToken(IntPtr pToken, ref string[] aSids)
{
int iTokenInfoLengt h = 0;
bool bResult = true;

// first call gets length of TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups, IntPtr.Zero, 0, out
iTokenInfoLengt h );
// if I uncomment this, the call returns an integer rapidly
//return iTokenInfoLengt h;

// if we got a return, continue
if ( iTokenInfoLengt h > 0 )
{
// allocate a memory buffer for the TokenInformatio n
IntPtr pTokenInfo = Marshal.AllocHG lobal( iTokenInfoLengt h );

// get the TokenInformatio n
bResult = GetTokenInforma tion( pToken,
TOKEN_INFORMATI ON_CLASS.TokenG roups , pTokenInfo, iTokenInfoLengt h, out
iTokenInfoLengt h ) ;
if ( bResult == false ) { return 2; }

// why would this be here and not after Marshal.PtrToSt ructure?
like TokenGroups.Gro upCount?
int groupCount = Marshal.ReadInt 32( pTokenInfo );

// convert the TokenInformatio n to a TOKEN_GROUPS struct
// BREAKING HERE
//TOKEN_GROUPS TokenGroups = ( TOKEN_GROUPS
)Marshal.PtrToS tructure( pTokenInfo , typeof( TOKEN_GROUPS ) ) ;

// get a pointer to the first group
int pSidAndAttibute s = (int)pTokenInfo + 4;

// loop through the groups
for ( int i=0; i < groupCount; i++ )
{
// marshall the struct out of the pointer
SID_AND_ATTRIBU TES SidAndAttibutes =
(SID_AND_ATTRIB UTES)Marshal.Pt rToStructure( (IntPtr)pSidAnd Attibutes ,
typeof(SID_AND_ ATTRIBUTES) ) ;

// initialize a pointer and get the sid converted
IntPtr pSid = IntPtr.Zero;
bResult = ConvertSidToStr ingSid( SidAndAttibutes .Sid, out pSid );
if ( bResult == false ) { return 3; }

// place it into a c# string and free up the memory
string sSid = Marshal.PtrToSt ringAuto( pSid );
LocalFree(pSid) ;

// add it to the array reference
aSids[i] = sSid;

// move to the next pointer
pSidAndAttibute s += Marshal.SizeOf( typeof(SID_AND_ ATTRIBUTES) );
}
// redim the array
Misc oMisc = new Misc();
aSids = (string[])oMisc.redim(aS ids, groupCount);
}
else
{
// GetTokenInforma tion returned a 0 length
return 1;
}

// all set
return 0;
}

Nov 17 '05 #2

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

Similar topics

2
10238
by: Stefan | last post by:
I have the following question The Marshal class contains a function to allocate a block of memory 1. Marshal.AllocHGlobal ( int cb 2. Marshal.AllocHGlobal ( IntPtr cb The first version I can understand, because the integer indicates the size of the memory block that is required But the second version I do not understand. If I want a memoryblock of 20 bytes could I use IntPtr p = Marshal.AllocHGlobal ( new IntPtr ( 20 ) )
2
4590
by: Hypnotron | last post by:
Hello, Regarding Marshal.AllocHGlobal versus Marshal.AllocCoTaskMem Does anyone know the circumstances in which one should use one over the other? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/ frlrfsystemruntimeinteropservicesmarshalclassalloccotaskmemtopic.asp http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/bas e/overlapped_str.asp
0
1365
by: Hypnotron | last post by:
>Hello, >Regarding Marshal.AllocHGlobal versus Marshal.AllocCoTaskMem Does anyone >know the circumstances in which one should use one over the other? > >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html / frlrfsystemruntimeinteropservicesmarshalclassalloccotaskmemtopic.asp > >http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/ba s
13
2168
by: Just Me | last post by:
The following almost works. The problem is Marshal.PtrToStringAuto seems to terminate at the first null so I don't get the full string. Any suggestions on how to fix this? Or how to improve the code? Thanks PS I added the +1 because as I understand the GetLogicalDriveStrings doc
2
8143
by: scottt | last post by:
I need to call into a C++ DLL from my C# code. The function is expecting a void pointer to an unsigned short. Which would be more correct? UInt16 wRegData; IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(wRegData)); Marshal.StructureToPtr(wRegData, p, false);
2
7317
by: runner | last post by:
I'm trying to call some functions from OpenSSL library but I'm a bit confused when I have to use pinvoke. first function should create key from some input data, it's declared : void BF_set_key(BF_KEY *key, int len, const unsigned char *data); I've translated it as public static extern IntPtr BF_set_key (IntPtr key, int len, byte data) and I try to call it this way:
2
7207
by: O.B. | last post by:
When using Marshal to copy data from a byte array to the structure below, only the first byte of the "other" array is getting copied from the original byte array. What do I need to specify to get Marshal.PtrToStructure to copy the all the data into the "other" array? unsafe public struct DeadReckoning {
0
2134
by: Charming12 | last post by:
Hi All, I have a strange problem and due to my inefficiency with IntPtr i am unable to figure it out. I have an structure something like: public struct Detail { public int age; public Detail(int _age)
2
15944
by: O.B. | last post by:
I have operation within a class that marshals the data into a byte array. Below are three different ways that work. Are there any downsides to using one over the the other? public virtual byte ToRaw1() { byte byteArray = new byte; IntPtr pointer = Marshal.AllocHGlobal(Size); Marshal.StructureToPtr(this, pointer, false); Marshal.Copy(pointer, byteArray, 0, Size);
0
9589
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
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10048
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...
1
9996
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
9865
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...
1
7410
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
6674
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();...
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
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.