Visualizzazione dei risultati da 1 a 7 su 7
  1. #1

    [3.5-C#] Consiglio identificazione utenti

    Salve a tutti, sono appena entrato nel mondo ASP .NET (circa 20 giorni) e vorrei proporvi un quesito che non riesco a risolvere.


    Devo fare un progetto universitario e mi è stato fornito un database Access contenente informazioni riguardante la struttura della didattica universitaria (tabella docenti, tabella corsi, tabella DocentiCorsi etc...)

    Ora devo fare in modo che i docenti possano loggarsi al sito che sto creando, vedano la loro didattica (Query di SELECT sulla tabella Corsi con delle clausole WHERE di corrispondenza docente-corso) e possano modificarla.


    Mi chiedevo, dato che di default tramite WAT è possibile fare in maniera rapida e indolore assegnazioni di ruoli, utenti e regole, in un database già bello che fatto in SQL, il famoso ASPNETDB.MDF cosa mi conviene fare.



    E' possibile salvare gli utenti in ASPNETDB.MDF e poi fare confronti tra elementi di 2 database diversi? (Questo e quello access). Mi chiedevo se fosse possibile trovare corrispondenze tra l'UserName di ASPNETDB.MDF e il campo chiave ID della tabella Docenti del database Access e se si come.

    Oppure devo fare il modo che gli utenti e i loro ruoli siano salvati nel database Access (cosi' pero' dovrei modificarlo di sana pianta, e non saprei come collegare i controlli precostruiti di .NET come Login, CreateUserWizard etc... col db access).

    Oppure esistono altre strade.
    Ogni consiglio è bene accetto, grazie

  2. #2
    Se il tuo obiettivo è sfruttare la tua base dati, puoi realizzare un "Custom Membership provider", consiste nella realizzazione di un tuo oggetto che eredita da MembershipProvider e va in override su tutti i metodi in esso presenti, tu teoricamente dovresti preoccuparti di implementare solo il metodo "ValidateUser" e di specificare nel IFormProvider.SetAuthCookie(...) le informazioni dell'utente, se connesso!
    Chi sbaglia, apprende meglio di chi non ha mai commesso errori.
    DOT.NET Addicted since 2006 (My Blog)

  3. #3
    Ciao, grazie per la risposta. Ho alcuni dubbi

    Per quanto riguarda il Database devo modificare la mia base di dati nel campo docenti inserendo tutti i campi ?

    codice:
      PKID Guid NOT NULL PRIMARY KEY,
      Username Text (255) NOT NULL,
      ApplicationName Text (255) NOT NULL,
      Email Text (128) NOT NULL,
      Comment Text (255),
      Password Text (128) NOT NULL,
      PasswordQuestion Text (255),
      PasswordAnswer Text (255),
      IsApproved YesNo, 
      LastActivityDate DateTime,
      LastLoginDate DateTime,
      LastPasswordChangedDate DateTime,
      CreationDate DateTime, 
      IsOnLine YesNo,
      IsLockedOut YesNo,
      LastLockedOutDate DateTime,
      FailedPasswordAttemptCount Integer,
      FailedPasswordAttemptWindowStart DateTime,
      FailedPasswordAnswerAttemptCount Integer,
      FailedPasswordAnswerAttemptWindowStart DateTime
    )
    E per i ruoli? Gli accessi e i divieti? Devo creare altre tabelle con gli stessi campi di quelle del db ASPNETDB.MDF?



    Come faccio a usare WAT col DatabaseAccess? Sarà possibile o dovrò configurare manualmente il file web.config?


    Sto cercando di capire cosa scrivere in questa classe CustomMembershipProvider, hai per caso del materiale che spieghi in italiano le classi Membership e MembershipProvider? L'msdn di microsoft non è molto chiaro per chi è alle prime armi.

    Grazie

  4. #4
    ci sto provando ma ho un errore che non capisco

    Questo è il web.config
    codice:
    <authentication mode="Forms"/>
    
        <membership defaultProvider="AccessMembershipProvider" >
          <providers>
            <add name="AccessMembershipProvider"
    					type="AccessMembershipProvider"
    					requiresQuestionAndAnswer="true"
    					connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Gege\Documenti\Visual Studio 2008\Projects\Progetto_prova3c\Progetto_prova3c\App_Data\Members.mdb;Persist Security Info=False"
    					/>
          </providers>
        </membership>
    Il file AccessMembershipProvider.cs inserito in App_Code invece è cosi'
    codice:
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.OleDb;
    using System.Diagnostics;
    using System.Web.Security;
    using System.Configuration;
    
    namespace Progetto_prova3c
    {
        public class AccessMembershipProvider : MembershipProvider
        {
            //---for database access use---
            private string connStr;
    
            private OleDbCommand comm;
        //    private bool _requiresQuestionAndAnswer;
        //    private int _minRequiredPasswordLength;
    
    
    
            public override string ApplicationName
            {
                get
                {
                    throw new NotImplementedException();
                }
                set
                {
                    throw new NotImplementedException();
                }
            }
    
            public override bool ChangePassword(string username, string oldPassword, string newPassword)
            {
                throw new NotImplementedException();
            }
    
            public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
            {
                throw new NotImplementedException();
            }
    
            public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
            {
                throw new NotImplementedException();
            }
    
            public override bool DeleteUser(string username, bool deleteAllRelatedData)
            {
                throw new NotImplementedException();
            }
    
            public override bool EnablePasswordReset
            {
                get { throw new NotImplementedException(); }
            }
    
            public override bool EnablePasswordRetrieval
            {
                get { throw new NotImplementedException(); }
            }
    
            public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }
    
            public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }
    
            public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }
    
            public override int GetNumberOfUsersOnline()
            {
                throw new NotImplementedException();
            }
    
            public override string GetPassword(string username, string answer)
            {
                throw new NotImplementedException();
            }
    
            public override MembershipUser GetUser(string username, bool userIsOnline)
            {
                throw new NotImplementedException();
            }
    
            public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
            {
                throw new NotImplementedException();
            }
    
            public override string GetUserNameByEmail(string email)
            {
                throw new NotImplementedException();
            }
    
            public override int MaxInvalidPasswordAttempts
            {
                get { throw new NotImplementedException(); }
            }
    
            public override int MinRequiredNonAlphanumericCharacters
            {
                get { throw new NotImplementedException(); }
            }
    
            public override int MinRequiredPasswordLength
            {
                get { throw new NotImplementedException(); }
            }
    
            public override int PasswordAttemptWindow
            {
                get { throw new NotImplementedException(); }
            }
    
            public override MembershipPasswordFormat PasswordFormat
            {
                get { throw new NotImplementedException(); }
            }
    
            public override string PasswordStrengthRegularExpression
            {
                get { throw new NotImplementedException(); }
            }
    
            public override bool RequiresQuestionAndAnswer
            {
                get { throw new NotImplementedException(); }
            }
    
            public override bool RequiresUniqueEmail
            {
                get { throw new NotImplementedException(); }
            }
    
            public override string ResetPassword(string username, string answer)
            {
                throw new NotImplementedException();
            }
    
            public override bool UnlockUser(string userName)
            {
                throw new NotImplementedException();
            }
    
            public override void UpdateUser(MembershipUser user)
            {
                throw new NotImplementedException();
            }
    
            public override bool ValidateUser(string username, string password)
            {
                connStr = ConfigurationManager.ConnectionStrings["AccessMembershipProvider"].ConnectionString;
                OleDbConnection conn = new OleDbConnection(connStr);
                try
                {
                    conn.Open();
                    string sql = "Select * From Membership WHERE " + "username=@username AND password=@password";
                    comm = new OleDbCommand(sql, conn);
                    comm.Parameters.AddWithValue("@username", username);
                    comm.Parameters.AddWithValue("@password", password);
                    OleDbDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
                    if (reader.HasRows)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
             //       conn.Close();
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine("error");
                    return false;
                }
            }
        }
    }
    L'errore che mi da dopo aver fatto un login con un semplice controllo Login è
    codice:
     Errore di configurazione.
    Descrizione: Si è verificato un errore durante l'elaborazione di un file di configurazione necessario per soddisfare la richiesta. Verificare i dettagli dell'errore specifico riportati di seguito e modificare il file di configurazione in modo appropriato.
    
    Messaggio di errore del parser: Impossibile caricare il tipo 'AccessMembershipProvider'.
    
    Errore nel codice sorgente:
    
    Riga 52:       <providers>
    Riga 53:         <add name="AccessMembershipProvider"
    Riga 54: 					type="AccessMembershipProvider"
    Riga 55: 					requiresQuestionAndAnswer="true"
    Riga 56: 					connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Gege\Documenti\Visual Studio 2008\Projects\Progetto_prova3c\Progetto_prova3c\App_Data\Members.mdb;Persist Security Info=False"
    
    
    File di origine: C:\Documents and Settings\Gege\Documenti\Visual Studio 2008\Projects\Progetto_prova3c\Progetto_prova3c\web.config    Riga: 54
    A me sembra corretto il type...

  5. #5
    Dovresti specificare l'intero namespace: Progetto_prova3c.AccessMembership....
    Chi sbaglia, apprende meglio di chi non ha mai commesso errori.
    DOT.NET Addicted since 2006 (My Blog)

  6. #6
    esatto, grazie

  7. #7
    Uff, ho un altro problema. Ho creato il file AccessRoleProvider per gestire i ruoli, nonostante cio' anche se vieto una cartella a un ruolo, posso accedere anche con utenti appartenenti a quel ruolo



    codice:
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.OleDb;
    using System.Data.Odbc;
    using System.Diagnostics;
    using System.Configuration;
    using System.Configuration.Provider;
    using System.Web.Security;
    
    
    namespace Progetto_Prova4c
    {
        public class AccessRoleProvider : RoleProvider
        {
    
            //---for database access use---
            private string connStr = @"ProviderMicrosoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Gege\Documenti\Visual Studio 2008\Projects\Progetto_Prova4c\Progetto_Prova4c\App_Data\Members.mdb;Persist Security Info=False";
    
            private OleDbCommand comm = new OleDbCommand();
            private bool _requiresQuestionAndAnswer;
    
            private int _minRequiredPasswordLength;
    
    
            private string pApplicationName;
    
    
            public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
            {
                //===retrives the attribute values set in 
                //web.config and assign to local variables===
    
                if (config["requiresQuestionAndAnswer"] == "true")
                    _requiresQuestionAndAnswer = true;
    
                    // connStr = config["connectionString"];
                base.Initialize(name, config);
            }
    
    
    
    
    
    
            public override void AddUsersToRoles(string[] usernames, string[] roleNames)
            {
                throw new NotImplementedException();
            }
    
    
    
            public override string ApplicationName
            {
                get { return pApplicationName; }
                set { pApplicationName = value; }
            }
    
            public override void CreateRole(string rolename)
            {
                if (rolename == null || rolename == "")
                    throw new ProviderException("Role name cannot be empty or null.");
                if (rolename.IndexOf(',') > 0)
                    throw new ArgumentException("Role names cannot contain commas.");
                if (RoleExists(rolename))
                    throw new ProviderException("Role name already exists.");
                if (rolename.Length > 255)
                    throw new ProviderException("Role name cannot exceed 255 characters.");
    
                OdbcConnection conn = new OdbcConnection(connStr);
    
                OdbcCommand id_max = new OdbcCommand("SELECT Max(ID) From Ruoli");
                conn.Open();
    
                OdbcDataReader reader = id_max.ExecuteReader();
                String max = reader.ToString();
                int max1 = Int32.Parse(max);
                max1 += 1;
    
                OdbcCommand cmd = new OdbcCommand("INSERT INTO [" + "Ruoli" + "]" +
                                                  " (ID, Nome_Ruolo) " +
                                                  " Values(max1, ?)", conn);
    
                cmd.Parameters.Add("@ID", OdbcType.Int).Value = max1;
                cmd.Parameters.Add("@rolename", OdbcType.VarChar, 255).Value = rolename;
    
    
                try
                {
                    conn.Open();
    
                    cmd.ExecuteNonQuery();
                }
                catch (OdbcException)
                {
                    // Handle exception.
                }
                finally
                {
                    conn.Close();
                }
            }
    
            public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
            {
                throw new NotImplementedException();
            }
    
            public override string[] FindUsersInRole(string roleName, string usernameToMatch)
            {
                throw new NotImplementedException();
            }
    
            public override string[] GetAllRoles()
            {
                throw new NotImplementedException();
            }
    
            public override string[] GetRolesForUser(string username)
            {
                if (username == null || username == "")
                    throw new ProviderException("User name cannot be empty or null.");
    
                string tmpRoleNames = "";
    
                OdbcConnection conn = new OdbcConnection(connStr);
                OdbcCommand cmd = new OdbcCommand("SELECT Ruoli.Nome_Ruolo FROM ((Membership INNER JOIN" +
                        "RuoliMembri ON Membership.username = RuoliMembri.Id_Membership) INNER JOIN" +
                        "Ruoli ON RuoliMembri.Id_Ruolo = Ruoli.ID)" +
                        "WHERE username=@username", conn);
    
                cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;
    
                OdbcDataReader reader = null;
    
                try
                {
                    conn.Open();
    
                    reader = cmd.ExecuteReader();
    
                    while (reader.Read())
                    {
                        tmpRoleNames += reader.GetString(0) + ",";
                    }
                }
                catch (OdbcException)
                {
                    // Handle exception.
                }
                finally
                {
                    if (reader != null) { reader.Close(); }
                    conn.Close();
                }
    
                if (tmpRoleNames.Length > 0)
                {
                    // Remove trailing comma.
                    tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
                    return tmpRoleNames.Split(',');
                }
    
    
                Console.WriteLine(tmpRoleNames);
                return new string[0];
            }
    
    
    
    
            public override string[] GetUsersInRole(string roleName)
            {
                throw new NotImplementedException();
            }
    
    
            public override bool IsUserInRole(string username, string rolename)
            {
                if (username == null || username == "")
                    throw new ProviderException("User name cannot be empty or null.");
                if (rolename == null || rolename == "")
                    throw new ProviderException("Role name cannot be empty or null.");
    
                bool userIsInRole = false;
    
                OdbcConnection conn = new OdbcConnection(connStr);
                OdbcCommand cmd = new OdbcCommand("SELECT Ruoli.Nome_Ruolo, Membership.username FROM ((Membership INNER JOIN" +
                                    "RuoliMembri ON Membership.username = RuoliMembri.Id_Membership) INNER JOIN" +
                                    "Ruoli ON RuoliMembri.Id_Ruolo = Ruoli.ID)" +
                                    "WHERE username=@username AND Nome_Ruolo=@roleName", conn);
    
                cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                cmd.Parameters.Add("@Rolename", OdbcType.VarChar, 255).Value = rolename;
                cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;
    
                try
                {
                    conn.Open();
    
                    int numRecs = (int)cmd.ExecuteScalar();
    
                    if (numRecs > 0)
                    {
                        userIsInRole = true;
                    }
                }
                catch (OdbcException)
                {
                    // Handle exception.
                }
                finally
                {
                    conn.Close();
                }
    
                return userIsInRole;
            }
    
            public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
            {
                throw new NotImplementedException();
            }
    
            public override bool RoleExists(string roleName)
            {
                throw new NotImplementedException();
            }
        }
    }
    Poi ho 2 web config, uno in una cartella da vietare l'accesso
    codice:
    <configuration>
        <appSettings/>
        <connectionStrings/>
        <system.web>
          <authorization>
            <allow roles="admin"/>
            <deny roles="docente"/>   
          </authorization>
        </system.web>
    </configuration>
    L'altro classico
    codice:
        
        <membership defaultProvider="AccessMembershipProvider" >
          <providers>
            <add name="AccessMembershipProvider"
              type="Progetto_Prova4c.AccessMembershipProvider"
              requiresQuestionAndAnswer="true"
    					connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Gege\Documenti\Visual Studio 2008\Projects\Progetto_Prova4c\Progetto_Prova4c\App_Data\Members.mdb;Persist Security Info=False"
    					/>
          </providers>
        </membership>
    
         
        <roleManager enabled="true" defaultProvider="AccessRoleProvider">
          <providers>
            <clear/>
            <add name="AccessRoleProvider"
                 type="Progetto_Prova4c.AccessRoleProvider"
                 connectionStringName="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Gege\Documenti\Visual Studio 2008\Projects\Progetto_Prova4c\Progetto_Prova4c\App_Data\Members.mdb;Persist Security Info=False"/>
          </providers>
        </roleManager>
    Grazie in anticipo

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.