Click here to Skip to main content
12,949,083 members (61,722 online)
Rate this:
 
Please Sign up or sign in to vote.
See more:
I have this code:

public class Credenciales : IDisposable
    {
        [DllImport("advapi32.dll", SetLastError=true)]
        private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
 
        [DllImport( "kernel32", SetLastError = true )]
        private static extern bool CloseHandle(IntPtr hObject);
 
        private IntPtr userHandle = IntPtr.Zero;
        private WindowsImpersonationContext impersonationContext;
 
        public Credenciales( string user, string domain, string password )
        {
                if ( ! string.IsNullOrEmpty( user ) )
                {
                        // Call LogonUser to get a token for the user
                        bool loggedOn = LogonUser( user, domain, password,
                                9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
                                3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
                                out userHandle );
                        if ( !loggedOn )
                                throw new Win32Exception( Marshal.GetLastWin32Error() );
 
                        // Begin impersonating the user
                        impersonationContext = WindowsIdentity.Impersonate( userHandle );
                }
        }
 
        public void Dispose()
        {
                if ( userHandle != IntPtr.Zero )
                        CloseHandle( userHandle );
                if ( impersonationContext != null )
                        impersonationContext.Undo();
        }
    }


And also I have installed BDE Administrator for Paradox Data Bases.

[Using the same PC] My problem is that when a user without administrator privileges account want to connect to DB, it's not working and I think it is because the user can't load DLLs and the administrator yes.

Is any solution for my problem? any different LogonUser maybe?

These is my other code:

public int RZb()
        {
            xml = new XML();
 
            try
            {
                string myConnectionString = "Driver={Microsoft Paradox Driver (*.db )};" + "fil=Paradox 7.x;" + "driverid=538;" + "collatingsequence=ASCII;" + "dbq=" + xml.Recuperar("RelojBBDD") + ";" + "defaultdir=" + xml.Recuperar("RelojBBDD") + ";" + "paradoxnetpath=" + xml.Recuperar("RelojBBDDNetFiles") + ";" + "paradoxnetstyle=4.x;" + "paradoxusername=admin;" + "safetransactions=0;" + "threads=3;" + "uid=admin;" + "usercommitsync=Yes";
                OdbcConnection myConnection = new OdbcConnection();
                myConnection.ConnectionString = myConnectionString;
                myConnection.Open();
 
                //execute queries, etc
                OdbcCommand DbCommand = myConnection.CreateCommand();
                DbCommand.CommandText = "SELECT codigo, Nombre, DNI FROM Personal WHERE Baja=0 AND DNI LIKE '%" + ((Main)(this.Parent.Parent)).lblDNI.Text.Substring(0,8) + "%';";
                OdbcDataReader DbReader = DbCommand.ExecuteReader();
                OdbcDataAdapter da = new OdbcDataAdapter(DbCommand);
                DataSet dsRetrievedData = new DataSet();
                myConnection.Close();
                da.Fill(dsRetrievedData);
                DataRowCollection dra = dsRetrievedData.Tables["Table"].Rows;
                if (dra.Count == 0)
                {
                    myConnectionString = "Driver={Microsoft Paradox Driver (*.db )};" + "fil=Paradox 7.x;" + "driverid=538;" + "collatingsequence=ASCII;" + "dbq=" + xml.Recuperar("RelojUdaltzaingoBBDD") + ";" + "defaultdir=" + xml.Recuperar("RelojUdaltzaingoBBDD") + ";" + "paradoxnetpath=" + xml.Recuperar("RelojUdaltzaingoBBDDNetFiles") + ";" + "paradoxnetstyle=4.x;" + "paradoxusername=admin;" + "safetransactions=0;" + "threads=3;" + "uid=admin;" + "usercommitsync=Yes";
                    myConnection = new OdbcConnection();
                    myConnection.ConnectionString = myConnectionString;
                    myConnection.Open();
 
                    //execute queries, etc
                    DbCommand = myConnection.CreateCommand();
                    DbCommand.CommandText = "SELECT codigo, Nombre, DNI FROM Personal WHERE Baja=0 AND DNI LIKE '%" + ((Main)(this.Parent.Parent)).lblDNI.Text.Substring(0, 8) + "%';";
                    //DbCommand.CommandText = "SELECT codigo FROM Personal WHERE Nombre LIKE " + textBox4.Text + ";";
                    DbReader = DbCommand.ExecuteReader();
                    da = new OdbcDataAdapter(DbCommand);
                    dsRetrievedData = new DataSet();
                    myConnection.Close();
                    da.Fill(dsRetrievedData);
                    dra = dsRetrievedData.Tables["Table"].Rows;
                }
                foreach (DataRow dr in dra)
                {
                    RelojZb = int.Parse(dr["codigo"].ToString());
                }
                return RelojZb;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erroreak egon dira markajeekin edota beste erabiltzaile bat dago koltsulta egiten");
                return 0;
            }
        }
Posted 11-Aug-11 1:45am

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Is it for local Users or in a Windows-Domain?

May you just use the administrator for executing some methods?

private bool doSomeThingWithAdministrativePrivilegs()
        {
            IntPtr token;
 
            if (!NativeMethods.LogonUser(
                <$user>, //Administrator or User with administrativ privilegs
                <$domain>, //if no domain avalible set computername System.Environment.MachineName it was i think .ToString()...
                <$password>,
                NativeMethods.LogonType.NewCredentials,
                NativeMethods.LogonProvider.Default,
                out token))
            {
                throw new Win32Exception();
            }
 
            try
            {
                IntPtr tokenDuplicate;
 
                if (!NativeMethods.DuplicateToken(
                    token,
                    NativeMethods.SecurityImpersonationLevel.Impersonation,
                    out tokenDuplicate))
                {
                    throw new Win32Exception();
                }
 
                try
                {
                    using (WindowsImpersonationContext impersonationContext =
                        new WindowsIdentity(tokenDuplicate).Impersonate())
                    {
                        // DO the stuff privilegs needed in here...
                    }
                }
                finally
                {
                    if (tokenDuplicate != IntPtr.Zero)
                    {
                        if (!NativeMethods.CloseHandle(tokenDuplicate))
                        {
                            return false;
                            //throw new Win32Exception();
                        }
                    }
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    if (!NativeMethods.CloseHandle(token))
                    {
                        return false;
                        //throw new Win32Exception();
                    }
                }
            }
            return true;
        }


uncomment the win32exceptions and you can have a look if its really the privilegs that deny the access...
  Permalink  
v2
Comments
kaiserssosse 12-Aug-11 3:31am
   
Hi first of all thank you for your collaboration.

It's in Windows-Domain and it's installed BDE Administrator for Paradox Data Bases and this is the situation:

I have a folder in the server and It's only accessible with the user "Intranet" that has administrator privileges.

When the application is run for a user without administrator privileges, I impersonate a Intranet user to have access to that folder and everything run ok.

When I want to access to Paradox Data Base with a administrator user, there is no problem but with the normal user I have a error, and I think it's because with administrator account it's possible to load DLLs (I think it's IDAPI32.dll) dinamically and with normal user maybe don't.

So I want to activate the option for load DLLs with normal user with LogonUser method.

I hope everything is clear in my explanation.

Thank you very much.

P.D: I don't know what are you meaning with "NativeMethods", sorry.

P.D2: How can I call the method? with like I do before, with using?

P.D3: For more information about IDAPI32.dll. http://dll.paretologic.com/detail.php/idapi32
diialer 12-Aug-11 8:15am
   
P.D: http://msdn.microsoft.com/en-us/library/system.security.principal.aspx
P.D2: Right-Click the dll. For testing add the User Everyone with full privilegs (better with the whole folder)

if this does not help use the method i postet before
export this to a method

if ( ! string.IsNullOrEmpty( user ) )
{
// Call LogonUser to get a token for the user
bool loggedOn = LogonUser( user, domain, password,
9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
out userHandle );
if ( !loggedOn )
throw new Win32Exception( Marshal.GetLastWin32Error() );

// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate( userHandle );
}

use method in doSomeThingWithAdministrativePrivilegs()
...
// DO the stuff privilegs needed in here...

put the method doSomeThingWithAdministrativePrivilegs() where your if ( ! string.IsNullOrEmpty( user ) ) ... was
you also can pass the user, password....
doSomeThingWithAdministrativePrivilegs(string user, string domain, string password)

you have to change the following lines in the method:
<$user>, //Administrator or User with administrativ privilegs
<$domain>, //if no domain avalible set computername System.Environment.MachineName it was i think .ToString()...
<$password>,
this is for example the domain administrator or a user who has administrativ privilegs in domain...

AND to use local administrator if possible:
Create manifest file for main application and add
<?xml version="1.0" encoding="utf-8" ?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0"
processorArchitecture="X86"
name="someExecName"
type="win32" />
<description>Your Program Description
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security>
<requestedprivileges>
<requestedExecutionLevel level="requireAdministrator" />


</trustInfo>
kaiserssosse 22-Aug-11 3:03am
   
Thanks for the reply.

I think the problem is the computer and the accounts, because with an old account it doesn't work but if we copy the privileges of the account to a new account it works fine, so I don't know which is the problem with all of this.

It can be because the accounts are old and when it was created it was done with a winNT version and not with the winXP SP3, or is a problem of cache files in the computer...

In some computers works perfectly, in others only works with some users, normally old accounts. This is a mysterious.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 5,489
CHill60 3,330
Maciej Los 2,913
Jochen Arndt 1,935
ppolymorphe 1,820


Advertise | Privacy | Mobile
Web02 | 2.8.170524.1 | Last Updated 12 Aug 2011
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100