MOSS


Si tienen instalado Windows Sharepoint Services, Sharepoint Office Server o Project Server 2007 deben instalar el Infrastruture Update el cual agrega estabilidad y rendimiento a estos productos, está disponible en esta dirección

http://www.microsoft.com/downloads/details.aspx?FamilyId=3811C371-0E83-47C8-976B-0B7F26A3B3C4&displaylang=en

 

Slds

 

Eduardo Castro

Comunidad Windows – http://comunidadwindows.org

 

Technorati Tags: ,
 
El siguiente es un ejemplo de código de Microsoft sobre cómo implementar un Membership Provider personalizado.
 
using System.Web.Security;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System;
using System.Data;
using System.Data.Odbc;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Web.Configuration;

/*

This provider works with the following schema for the table of user data.

CREATE TABLE Users
(
  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
)

*/


namespace Samples.AspNet.Membership
{

    public sealed class OdbcMembershipProvider : MembershipProvider
    {

        //
        // Global connection string, generated password length, generic exception message, event log info.
        //

        private int newPasswordLength = 8;
        private string eventSource = "OdbcMembershipProvider";
        private string eventLog = "Application";
        private string exceptionMessage = "An exception occurred. Please check the Event Log.";
        private string connectionString;

        //
        // Used when determining encryption key values.
        //

        private MachineKeySection machineKey;

        //
        // If false, exceptions are thrown to the caller. If true,
        // exceptions are written to the event log.
        //

        private bool pWriteExceptionsToEventLog;

        public bool WriteExceptionsToEventLog
        {
            get { return pWriteExceptionsToEventLog; }
            set { pWriteExceptionsToEventLog = value; }
        }


        //
        // System.Configuration.Provider.ProviderBase.Initialize Method
        //

        public override void Initialize(string name, NameValueCollection config)
        {
            //
            // Initialize values from web.config.
            //

            if (config == null)
                throw new ArgumentNullException("config");

            if (name == null || name.Length == 0)
                name = "OdbcMembershipProvider";

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "Sample ODBC Membership provider");
            }

            // Initialize the abstract base class.
            base.Initialize(name, config);

            pApplicationName = GetConfigValue(config["applicationName"],
                                            System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
            pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
            pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1"));
            pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7"));
            pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));
            pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
            pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true"));
            pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false"));
            pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true"));
            pWriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "true"));

            string temp_format = config["passwordFormat"];
            if (temp_format == null)
            {
                temp_format = "Hashed";
            }

            switch (temp_format)
            {
                case "Hashed":
                    pPasswordFormat = MembershipPasswordFormat.Hashed;
                    break;
                case "Encrypted":
                    pPasswordFormat = MembershipPasswordFormat.Encrypted;
                    break;
                case "Clear":
                    pPasswordFormat = MembershipPasswordFormat.Clear;
                    break;
                default:
                    throw new ProviderException("Password format not supported.");
            }

            //
            // Initialize OdbcConnection.
            //

            ConnectionStringSettings ConnectionStringSettings =
              ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

            if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "")
            {
                throw new ProviderException("Connection string cannot be blank.");
            }

            connectionString = ConnectionStringSettings.ConnectionString;


            // Get encryption and decryption key information from the configuration.
            Configuration cfg =
              WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");

            if (machineKey.ValidationKey.Contains("AutoGenerate"))
                if (PasswordFormat != MembershipPasswordFormat.Clear)
                    throw new ProviderException("Hashed or Encrypted passwords " +
                                                "are not supported with auto-generated keys.");
        }


        //
        // A helper function to retrieve config values from the configuration file.
        //

        private string GetConfigValue(string configValue, string defaultValue)
        {
            if (String.IsNullOrEmpty(configValue))
                return defaultValue;

            return configValue;
        }


        //
        // System.Web.Security.MembershipProvider properties.
        //


        private string pApplicationName;
        private bool pEnablePasswordReset;
        private bool pEnablePasswordRetrieval;
        private bool pRequiresQuestionAndAnswer;
        private bool pRequiresUniqueEmail;
        private int pMaxInvalidPasswordAttempts;
        private int pPasswordAttemptWindow;
        private MembershipPasswordFormat pPasswordFormat;

        public override string ApplicationName
        {
            get { return pApplicationName; }
            set { pApplicationName = value; }
        }

        public override bool EnablePasswordReset
        {
            get { return pEnablePasswordReset; }
        }


        public override bool EnablePasswordRetrieval
        {
            get { return pEnablePasswordRetrieval; }
        }


        public override bool RequiresQuestionAndAnswer
        {
            get { return pRequiresQuestionAndAnswer; }
        }


        public override bool RequiresUniqueEmail
        {
            get { return pRequiresUniqueEmail; }
        }


        public override int MaxInvalidPasswordAttempts
        {
            get { return pMaxInvalidPasswordAttempts; }
        }


        public override int PasswordAttemptWindow
        {
            get { return pPasswordAttemptWindow; }
        }


        public override MembershipPasswordFormat PasswordFormat
        {
            get { return pPasswordFormat; }
        }

        private int pMinRequiredNonAlphanumericCharacters;

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return pMinRequiredNonAlphanumericCharacters; }
        }

        private int pMinRequiredPasswordLength;

        public override int MinRequiredPasswordLength
        {
            get { return pMinRequiredPasswordLength; }
        }

        private string pPasswordStrengthRegularExpression;

        public override string PasswordStrengthRegularExpression
        {
            get { return pPasswordStrengthRegularExpression; }
        }

        //
        // System.Web.Security.MembershipProvider methods.
        //

        //
        // MembershipProvider.ChangePassword
        //

        public override bool ChangePassword(string username, string oldPwd, string newPwd)
        {
            if (!ValidateUser(username, oldPwd))
                return false;


            ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(username, newPwd, true);

            OnValidatingPassword(args);

            if (args.Cancel)
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Change password canceled due to new password validation failure.");


            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
                    " SET Password = ?, LastPasswordChangedDate = ? " +
                    " WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(newPwd);
            cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now;
            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;


            int rowsAffected = 0;

            try
            {
                conn.Open();

                rowsAffected = cmd.ExecuteNonQuery();
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "ChangePassword");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                conn.Close();
            }

            if (rowsAffected > 0)
            {
                return true;
            }

            return false;
        }



        //
        // MembershipProvider.ChangePasswordQuestionAndAnswer
        //

        public override bool ChangePasswordQuestionAndAnswer(string username,
                      string password,
                      string newPwdQuestion,
                      string newPwdAnswer)
        {
            if (!ValidateUser(username, password))
                return false;

            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
                    " SET PasswordQuestion = ?, PasswordAnswer = ?" +
                    " WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Question", OdbcType.VarChar, 255).Value = newPwdQuestion;
            cmd.Parameters.Add("@Answer", OdbcType.VarChar, 255).Value = EncodePassword(newPwdAnswer);
            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;


            int rowsAffected = 0;

            try
            {
                conn.Open();

                rowsAffected = cmd.ExecuteNonQuery();
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "ChangePasswordQuestionAndAnswer");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                conn.Close();
            }

            if (rowsAffected > 0)
            {
                return true;
            }

            return false;
        }



        //
        // MembershipProvider.CreateUser
        //

        public override MembershipUser CreateUser(string username,
                 string password,
                 string email,
                 string passwordQuestion,
                 string passwordAnswer,
                 bool isApproved,
                 object providerUserKey,
                 out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(username, password, true);

            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }



            if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            MembershipUser u = GetUser(username, false);

            if (u == null)
            {
                DateTime createDate = DateTime.Now;

                if (providerUserKey == null)
                {
                    providerUserKey = Guid.NewGuid();
                }
                else
                {
                    if (!(providerUserKey is Guid))
                    {
                        status = MembershipCreateStatus.InvalidProviderUserKey;
                        return null;
                    }
                }

                OdbcConnection conn = new OdbcConnection(connectionString);
                OdbcCommand cmd = new OdbcCommand("INSERT INTO Users " +
                      " (PKID, Username, Password, Email, PasswordQuestion, " +
                      " PasswordAnswer, IsApproved," +
                      " Comment, CreationDate, LastPasswordChangedDate, LastActivityDate," +
                      " ApplicationName, IsLockedOut, LastLockedOutDate," +
                      " FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, " +
                      " FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart)" +
                      " Values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", conn);

                cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey;
                cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                cmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(password);
                cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email;
                cmd.Parameters.Add("@PasswordQuestion", OdbcType.VarChar, 255).Value = passwordQuestion;
                cmd.Parameters.Add("@PasswordAnswer", OdbcType.VarChar, 255).Value = EncodePassword(passwordAnswer);
                cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = isApproved;
                cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = "";
                cmd.Parameters.Add("@CreationDate", OdbcType.DateTime).Value = createDate;
                cmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = createDate;
                cmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = createDate;
                cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;
                cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = false;
                cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = createDate;
                cmd.Parameters.Add("@FailedPasswordAttemptCount", OdbcType.Int).Value = 0;
                cmd.Parameters.Add("@FailedPasswordAttemptWindowStart", OdbcType.DateTime).Value = createDate;
                cmd.Parameters.Add("@FailedPasswordAnswerAttemptCount", OdbcType.Int).Value = 0;
                cmd.Parameters.Add("@FailedPasswordAnswerAttemptWindowStart", OdbcType.DateTime).Value = createDate;

                try
                {
                    conn.Open();

                    int recAdded = cmd.ExecuteNonQuery();

                    if (recAdded > 0)
                    {
                        status = MembershipCreateStatus.Success;
                    }
                    else
                    {
                        status = MembershipCreateStatus.UserRejected;
                    }
                }
                catch (OdbcException e)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(e, "CreateUser");
                    }

                    status = MembershipCreateStatus.ProviderError;
                }
                finally
                {
                    conn.Close();
                }


                return GetUser(username, false);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }


            return null;
        }



        //
        // MembershipProvider.DeleteUser
        //

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("DELETE FROM Users " +
                    " WHERE Username = ? AND Applicationname = ?", conn);

            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            int rowsAffected = 0;

            try
            {
                conn.Open();

                rowsAffected = cmd.ExecuteNonQuery();

                if (deleteAllRelatedData)
                {
                    // Process commands to delete all data for the user in the database.
                }
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "DeleteUser");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                conn.Close();
            }

            if (rowsAffected > 0)
                return true;

            return false;
        }



        //
        // MembershipProvider.GetAllUsers
        //

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " +
                                              "WHERE ApplicationName = ?", conn);
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

            MembershipUserCollection users = new MembershipUserCollection();

            OdbcDataReader reader = null;
            totalRecords = 0;

            try
            {
                conn.Open();
                totalRecords = (int)cmd.ExecuteScalar();

                if (totalRecords <= 0) { return users; }

                cmd.CommandText = "SELECT PKID, Username, Email, PasswordQuestion," +
                         " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                         " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate " +
                         " FROM Users " +
                         " WHERE ApplicationName = ? " +
                         " ORDER BY Username Asc";

                reader = cmd.ExecuteReader();

                int counter = 0;
                int startIndex = pageSize * pageIndex;
                int endIndex = startIndex + pageSize - 1;

                while (reader.Read())
                {
                    if (counter >= startIndex)
                    {
                        MembershipUser u = GetUserFromReader(reader);
                        users.Add(u);
                    }

                    if (counter >= endIndex) { cmd.Cancel(); }

                    counter++;
                }
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "GetAllUsers ");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }
                conn.Close();
            }

            return users;
        }


        //
        // MembershipProvider.GetNumberOfUsersOnline
        //

        public override int GetNumberOfUsersOnline()
        {

            TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0);
            DateTime compareTime = DateTime.Now.Subtract(onlineSpan);

            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " +
                    " WHERE LastActivityDate > ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@CompareDate", OdbcType.DateTime).Value = compareTime;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            int numOnline = 0;

            try
            {
                conn.Open();

                numOnline = (int)cmd.ExecuteScalar();
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "GetNumberOfUsersOnline");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                conn.Close();
            }

            return numOnline;
        }



        //
        // MembershipProvider.GetPassword
        //

        public override string GetPassword(string username, string answer)
        {
            if (!EnablePasswordRetrieval)
            {
                throw new ProviderException("Password Retrieval Not Enabled.");
            }

            if (PasswordFormat == MembershipPasswordFormat.Hashed)
            {
                throw new ProviderException("Cannot retrieve Hashed passwords.");
            }

            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT Password, PasswordAnswer, IsLockedOut FROM Users " +
                  " WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            string password = "";
            string passwordAnswer = "";
            OdbcDataReader reader = null;

            try
            {
                conn.Open();

                reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                if (reader.HasRows)
                {
                    reader.Read();

                    if (reader.GetBoolean(2))
                        throw new MembershipPasswordException("The supplied user is locked out.");

                    password = reader.GetString(0);
                    passwordAnswer = reader.GetString(1);
                }
                else
                {
                    throw new MembershipPasswordException("The supplied user name is not found.");
                }
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "GetPassword");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }
                conn.Close();
            }


            if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
            {
                UpdateFailureCount(username, "passwordAnswer");

                throw new MembershipPasswordException("Incorrect password answer.");
            }


            if (PasswordFormat == MembershipPasswordFormat.Encrypted)
            {
                password = UnEncodePassword(password);
            }

            return password;
        }



        //
        // MembershipProvider.GetUser(string, bool)
        //

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," +
                 " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                 " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" +
                 " FROM Users WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            MembershipUser u = null;
            OdbcDataReader reader = null;

            try
            {
                conn.Open();

                reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();
                    u = GetUserFromReader(reader);

                    if (userIsOnline)
                    {
                        OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " +
                                  "SET LastActivityDate = ? " +
                                  "WHERE Username = ? AND Applicationname = ?", conn);

                        updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now;
                        updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                        updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                        updateCmd.ExecuteNonQuery();
                    }
                }

            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "GetUser(String, Boolean)");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }

                conn.Close();
            }

            return u;
        }


        //
        // MembershipProvider.GetUser(object, bool)
        //

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," +
                  " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                  " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" +
                  " FROM Users WHERE PKID = ?", conn);

            cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey;

            MembershipUser u = null;
            OdbcDataReader reader = null;

            try
            {
                conn.Open();

                reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();
                    u = GetUserFromReader(reader);

                    if (userIsOnline)
                    {
                        OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " +
                                  "SET LastActivityDate = ? " +
                                  "WHERE PKID = ?", conn);

                        updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now;
                        updateCmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey;

                        updateCmd.ExecuteNonQuery();
                    }
                }

            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "GetUser(Object, Boolean)");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }

                conn.Close();
            }

            return u;
        }


        //
        // GetUserFromReader
        //    A helper function that takes the current row from the OdbcDataReader
        // and hydrates a MembershiUser from the values. Called by the 
        // MembershipUser.GetUser implementation.
        //

        private MembershipUser GetUserFromReader(OdbcDataReader reader)
        {
            object providerUserKey = reader.GetValue(0);
            string username = reader.GetString(1);
            string email = reader.GetString(2);

            string passwordQuestion = "";
            if (reader.GetValue(3) != DBNull.Value)
                passwordQuestion = reader.GetString(3);

            string comment = "";
            if (reader.GetValue(4) != DBNull.Value)
                comment = reader.GetString(4);

            bool isApproved = reader.GetBoolean(5);
            bool isLockedOut = reader.GetBoolean(6);
            DateTime creationDate = reader.GetDateTime(7);

            DateTime lastLoginDate = new DateTime();
            if (reader.GetValue(8) != DBNull.Value)
                lastLoginDate = reader.GetDateTime(8);

            DateTime lastActivityDate = reader.GetDateTime(9);
            DateTime lastPasswordChangedDate = reader.GetDateTime(10);

            DateTime lastLockedOutDate = new DateTime();
            if (reader.GetValue(11) != DBNull.Value)
                lastLockedOutDate = reader.GetDateTime(11);

            MembershipUser u = new MembershipUser(this.Name,
                                                  username,
                                                  providerUserKey,
                                                  email,
                                                  passwordQuestion,
                                                  comment,
                                                  isApproved,
                                                  isLockedOut,
                                                  creationDate,
                                                  lastLoginDate,
                                                  lastActivityDate,
                                                  lastPasswordChangedDate,
                                                  lastLockedOutDate);

            return u;
        }


        //
        // MembershipProvider.UnlockUser
        //

        public override bool UnlockUser(string username)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
                                              " SET IsLockedOut = False, LastLockedOutDate = ? " +
                                              " WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now;
            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            int rowsAffected = 0;

            try
            {
                conn.Open();

                rowsAffected = cmd.ExecuteNonQuery();
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "UnlockUser");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                conn.Close();
            }

            if (rowsAffected > 0)
                return true;

            return false;
        }


        //
        // MembershipProvider.GetUserNameByEmail
        //

        public override string GetUserNameByEmail(string email)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT Username" +
                  " FROM Users WHERE Email = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            string username = "";

            try
            {
                conn.Open();

                username = (string)cmd.ExecuteScalar();
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "GetUserNameByEmail");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                conn.Close();
            }

            if (username == null)
                username = "";

            return username;
        }




        //
        // MembershipProvider.ResetPassword
        //

        public override string ResetPassword(string username, string answer)
        {
            if (!EnablePasswordReset)
            {
                throw new NotSupportedException("Password reset is not enabled.");
            }

            if (answer == null && RequiresQuestionAndAnswer)
            {
                UpdateFailureCount(username, "passwordAnswer");

                throw new ProviderException("Password answer required for password reset.");
            }

            string newPassword =
              System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters);


            ValidatePasswordEventArgs args =
              new ValidatePasswordEventArgs(username, newPassword, true);

            OnValidatingPassword(args);

            if (args.Cancel)
                if (args.FailureInformation != null)
                    throw args.FailureInformation;
                else
                    throw new MembershipPasswordException("Reset password canceled due to password validation failure.");


            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT PasswordAnswer, IsLockedOut FROM Users " +
                  " WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            int rowsAffected = 0;
            string passwordAnswer = "";
            OdbcDataReader reader = null;

            try
            {
                conn.Open();

                reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                if (reader.HasRows)
                {
                    reader.Read();

                    if (reader.GetBoolean(1))
                        throw new MembershipPasswordException("The supplied user is locked out.");

                    passwordAnswer = reader.GetString(0);
                }
                else
                {
                    throw new MembershipPasswordException("The supplied user name is not found.");
                }

                if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
                {
                    UpdateFailureCount(username, "passwordAnswer");

                    throw new MembershipPasswordException("Incorrect password answer.");
                }

                OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " +
                    " SET Password = ?, LastPasswordChangedDate = ?" +
                    " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn);

                updateCmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(newPassword);
                updateCmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now;
                updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                rowsAffected = updateCmd.ExecuteNonQuery();
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "ResetPassword");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }
                conn.Close();
            }

            if (rowsAffected > 0)
            {
                return newPassword;
            }
            else
            {
                throw new MembershipPasswordException("User not found, or user is locked out. Password not Reset.");
            }
        }


        //
        // MembershipProvider.UpdateUser
        //

        public override void UpdateUser(MembershipUser user)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
                    " SET Email = ?, Comment = ?," +
                    " IsApproved = ?" +
                    " WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = user.Email;
            cmd.Parameters.Add("@Comment", OdbcType.VarChar, 255).Value = user.Comment;
            cmd.Parameters.Add("@IsApproved", OdbcType.Bit).Value = user.IsApproved;
            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = user.UserName;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;


            try
            {
                conn.Open();

                cmd.ExecuteNonQuery();
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "UpdateUser");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                conn.Close();
            }
        }


        //
        // MembershipProvider.ValidateUser
        //

        public override bool ValidateUser(string username, string password)
        {
            bool isValid = false;

            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT Password, IsApproved FROM Users " +
                    " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn);

            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            OdbcDataReader reader = null;
            bool isApproved = false;
            string pwd = "";

            try
            {
                conn.Open();

                reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                if (reader.HasRows)
                {
                    reader.Read();
                    pwd = reader.GetString(0);
                    isApproved = reader.GetBoolean(1);
                }
                else
                {
                    return false;
                }

                reader.Close();

                if (CheckPassword(password, pwd))
                {
                    if (isApproved)
                    {
                        isValid = true;

                        OdbcCommand updateCmd = new OdbcCommand("UPDATE Users SET LastLoginDate = ?" +
                                                                " WHERE Username = ? AND ApplicationName = ?", conn);

                        updateCmd.Parameters.Add("@LastLoginDate", OdbcType.DateTime).Value = DateTime.Now;
                        updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                        updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                        updateCmd.ExecuteNonQuery();
                    }
                }
                else
                {
                    conn.Close();

                    UpdateFailureCount(username, "password");
                }
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "ValidateUser");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }
                conn.Close();
            }

            return isValid;
        }


        //
        // UpdateFailureCount
        //   A helper method that performs the checks and updates associated with
        // password failure tracking.
        //

        private void UpdateFailureCount(string username, string failureType)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT FailedPasswordAttemptCount, " +
                                              "  FailedPasswordAttemptWindowStart, " +
                                              "  FailedPasswordAnswerAttemptCount, " +
                                              "  FailedPasswordAnswerAttemptWindowStart " +
                                              "  FROM Users " +
                                              "  WHERE Username = ? AND ApplicationName = ?", conn);

            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            OdbcDataReader reader = null;
            DateTime windowStart = new DateTime();
            int failureCount = 0;

            try
            {
                conn.Open();

                reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                if (reader.HasRows)
                {
                    reader.Read();

                    if (failureType == "password")
                    {
                        failureCount = reader.GetInt32(0);
                        windowStart = reader.GetDateTime(1);
                    }

                    if (failureType == "passwordAnswer")
                    {
                        failureCount = reader.GetInt32(2);
                        windowStart = reader.GetDateTime(3);
                    }
                }

                reader.Close();

                DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);

                if (failureCount == 0 || DateTime.Now > windowEnd)
                {
                    // First password failure or outside of PasswordAttemptWindow. 
                    // Start a new password failure count from 1 and a new window starting now.

                    if (failureType == "password")
                        cmd.CommandText = "UPDATE Users " +
                                          "  SET FailedPasswordAttemptCount = ?, " +
                                          "      FailedPasswordAttemptWindowStart = ? " +
                                          "  WHERE Username = ? AND ApplicationName = ?";

                    if (failureType == "passwordAnswer")
                        cmd.CommandText = "UPDATE Users " +
                                          "  SET FailedPasswordAnswerAttemptCount = ?, " +
                                          "      FailedPasswordAnswerAttemptWindowStart = ? " +
                                          "  WHERE Username = ? AND ApplicationName = ?";

                    cmd.Parameters.Clear();

                    cmd.Parameters.Add("@Count", OdbcType.Int).Value = 1;
                    cmd.Parameters.Add("@WindowStart", OdbcType.DateTime).Value = DateTime.Now;
                    cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                    cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                    if (cmd.ExecuteNonQuery() < 0)
                        throw new ProviderException("Unable to update failure count and window start.");
                }
                else
                {
                    if (failureCount++ >= MaxInvalidPasswordAttempts)
                    {
                        // Password attempts have exceeded the failure threshold. Lock out
                        // the user.

                        cmd.CommandText = "UPDATE Users " +
                                          "  SET IsLockedOut = ?, LastLockedOutDate = ? " +
                                          "  WHERE Username = ? AND ApplicationName = ?";

                        cmd.Parameters.Clear();

                        cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = true;
                        cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now;
                        cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                        cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                        if (cmd.ExecuteNonQuery() < 0)
                            throw new ProviderException("Unable to lock out user.");
                    }
                    else
                    {
                        // Password attempts have not exceeded the failure threshold. Update
                        // the failure counts. Leave the window the same.

                        if (failureType == "password")
                            cmd.CommandText = "UPDATE Users " +
                                              "  SET FailedPasswordAttemptCount = ?" +
                                              "  WHERE Username = ? AND ApplicationName = ?";

                        if (failureType == "passwordAnswer")
                            cmd.CommandText = "UPDATE Users " +
                                              "  SET FailedPasswordAnswerAttemptCount = ?" +
                                              "  WHERE Username = ? AND ApplicationName = ?";

                        cmd.Parameters.Clear();

                        cmd.Parameters.Add("@Count", OdbcType.Int).Value = failureCount;
                        cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                        cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                        if (cmd.ExecuteNonQuery() < 0)
                            throw new ProviderException("Unable to update failure count.");
                    }
                }
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "UpdateFailureCount");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }
                conn.Close();
            }
        }


        //
        // CheckPassword
        //   Compares password values based on the MembershipPasswordFormat.
        //

        private bool CheckPassword(string password, string dbpassword)
        {
            string pass1 = password;
            string pass2 = dbpassword;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Encrypted:
                    pass2 = UnEncodePassword(dbpassword);
                    break;
                case MembershipPasswordFormat.Hashed:
                    pass1 = EncodePassword(password);
                    break;
                default:
                    break;
            }

            if (pass1 == pass2)
            {
                return true;
            }

            return false;
        }


        //
        // EncodePassword
        //   Encrypts, Hashes, or leaves the password clear based on the PasswordFormat.
        //

        private string EncodePassword(string password)
        {
            string encodedPassword = password;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    break;
                case MembershipPasswordFormat.Encrypted:
                    encodedPassword =
                      Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
                    break;
                case MembershipPasswordFormat.Hashed:
                    HMACSHA1 hash = new HMACSHA1();
                    hash.Key = HexToByte(machineKey.ValidationKey);
                    encodedPassword =
                      Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
                    break;
                default:
                    throw new ProviderException("Unsupported password format.");
            }

            return encodedPassword;
        }


        //
        // UnEncodePassword
        //   Decrypts or leaves the password clear based on the PasswordFormat.
        //

        private string UnEncodePassword(string encodedPassword)
        {
            string password = encodedPassword;

            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    break;
                case MembershipPasswordFormat.Encrypted:
                    password =
                      Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
                    break;
                case MembershipPasswordFormat.Hashed:
                    throw new ProviderException("Cannot unencode a hashed password.");
                default:
                    throw new ProviderException("Unsupported password format.");
            }

            return password;
        }

        //
        // HexToByte
        //   Converts a hexadecimal string to a byte array. Used to convert encryption
        // key values from the configuration.
        //

        private byte[] HexToByte(string hexString)
        {
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }


        //
        // MembershipProvider.FindUsersByName
        //

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {

            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " +
                      "WHERE Username LIKE ? AND ApplicationName = ?", conn);
            cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

            MembershipUserCollection users = new MembershipUserCollection();

            OdbcDataReader reader = null;

            try
            {
                conn.Open();
                totalRecords = (int)cmd.ExecuteScalar();

                if (totalRecords <= 0) { return users; }

                cmd.CommandText = "SELECT PKID, Username, Email, PasswordQuestion," +
                  " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                  " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate " +
                  " FROM Users " +
                  " WHERE Username LIKE ? AND ApplicationName = ? " +
                  " ORDER BY Username Asc";

                reader = cmd.ExecuteReader();

                int counter = 0;
                int startIndex = pageSize * pageIndex;
                int endIndex = startIndex + pageSize - 1;

                while (reader.Read())
                {
                    if (counter >= startIndex)
                    {
                        MembershipUser u = GetUserFromReader(reader);
                        users.Add(u);
                    }

                    if (counter >= endIndex) { cmd.Cancel(); }

                    counter++;
                }
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "FindUsersByName");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }

                conn.Close();
            }

            return users;
        }

        //
        // MembershipProvider.FindUsersByEmail
        //

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            OdbcConnection conn = new OdbcConnection(connectionString);
            OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " +
                                              "WHERE Email LIKE ? AND ApplicationName = ?", conn);
            cmd.Parameters.Add("@EmailSearch", OdbcType.VarChar, 255).Value = emailToMatch;
            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

            MembershipUserCollection users = new MembershipUserCollection();

            OdbcDataReader reader = null;
            totalRecords = 0;

            try
            {
                conn.Open();
                totalRecords = (int)cmd.ExecuteScalar();

                if (totalRecords <= 0) { return users; }

                cmd.CommandText = "SELECT PKID, Username, Email, PasswordQuestion," +
                         " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                         " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate " +
                         " FROM Users " +
                         " WHERE Email LIKE ? AND ApplicationName = ? " +
                         " ORDER BY Username Asc";

                reader = cmd.ExecuteReader();

                int counter = 0;
                int startIndex = pageSize * pageIndex;
                int endIndex = startIndex + pageSize - 1;

                while (reader.Read())
                {
                    if (counter >= startIndex)
                    {
                        MembershipUser u = GetUserFromReader(reader);
                        users.Add(u);
                    }

                    if (counter >= endIndex) { cmd.Cancel(); }

                    counter++;
                }
            }
            catch (OdbcException e)
            {
                if (WriteExceptionsToEventLog)
                {
                    WriteToEventLog(e, "FindUsersByEmail");

                    throw new ProviderException(exceptionMessage);
                }
                else
                {
                    throw e;
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }

                conn.Close();
            }

            return users;
        }


        //
        // WriteToEventLog
        //   A helper function that writes exception detail to the event log. Exceptions
        // are written to the event log as a security measure to avoid private database
        // details from being returned to the browser. If a method does not return a status
        // or boolean indicating the action succeeded or failed, a generic exception is also 
        // thrown by the caller.
        //

        private void WriteToEventLog(Exception e, string action)
        {
            EventLog log = new EventLog();
            log.Source = eventSource;
            log.Log = eventLog;

            string message = "An exception occurred communicating with the data source.\n\n";
            message += "Action: " + action + "\n\n";
            message += "Exception: " + e.ToString();

            log.WriteEntry(message);
        }

    }
}

Microsoft ha confirmado que existen ocasiones en las cuales no se puede editar el master page en SharePoint, específicamente cuando ese master page está asociado a un layout determinado, más información en http://support.microsoft.com/kb/953450

 

Slds

Eduardo Castro – http://comunidadwindows.org

Costa Rica

En los casos en los cuales hay que cambiarle el nombre al servidor de MOSS es necesario seguir los siguiente pasos.

 

1. Opcionalmente desconecte el servidor de la red.

2. Ingrese como un usuario administrador al equipo.

3. Cambie los alternate access mapping de MOSS/WSS:

  • Vaya a Central Administration, “Operations” Tab, “Alternate access mappings”.
  • Modique cada mapping para que sea el nuevo nombre del servidor, no modifique los puertos.


4. Ejecute stsadm para cambiarle el nombre al servidor

  • Vaya a
    cd “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN”
  • stsadm -o renameserver -newservername “nuevo_nombre” -oldservername “nombre_viejo”

5. Cambie el nombre del servidor en Windows: Start Menu Control Panel System, “Computer Name” , “Change”. Cambie el nombre del servidor, si el servidor pertenece a un dominio, cambie la máquina a un workgroup por el momento.

6. Reinicie el servidor, conéctese a red e ingrese como administrador.

7. Si es necesario ingrese la máquina nuevamente al dominio.

8. Reinicie IIS: “iisreset /noforce”

9. Revise las identidades de los application pool.

 

Slds

Eduardo Castro – http://comunidadwindows.org

Costa Rica

Technorati Tags: ,,
 

Si alguna vez has necesitado agregar código a un formulario InfoPath desplegado en el browser revisa el siguiente documento:

http://www.microsoft.com/downloads/details.aspx?familyid=db1d99d9-0a31-45de-8efb-16c75e194dc3&displaylang=en

Estos son los pasos generales :

  • Cambie la seguridad del formulario a full trust

Tools -> Form Options -> Security and Trust -> Full Trust

  • Publique el Infopath Form en un Network Share
  • Suba el formulario al servidor

Central Administration > Application Management > Manage Form Templates

  • Active el formulario en la colección deseada
  • Accese el URL del formulario utilizando la siguiente sintaxis:

http://”nombre_servidor”/_layouts/formserver.aspx?xsnlocation=”url_site_collection”/formservertemplates/”nombre_formulario”.xsn&openin=browser&QueryParametername=”value”

 

Slds

Eduardo Castro – http://comunidadwindows.org

Para publicar un MOSS con ISA 2007 se tiene que crear el Alternate Access Mapping en la configuración de MOSS, luego tienen que ir al ISA Server y crear un regla de publicación de sitio web, después de que ha creado esta regla tienen que editarla e incluir dentro de los links publicados los siguientes:

 

/_controltemplates/*
/_layouts/*
/_vti_bin/*
/_wpresources/*

 

Slds

Eduardo Castro

Comunidad Windows – http://mswindowscr.org

 

Technorati Tags: ,,

Este artículo da un guía de cómo configurar WSS con ADAM https://blogs.pointbridge.com/Blogs/morse_matt/Pages/Post.aspx?_ID=2

By: Matthew Morse

If you’re looking for options to authenticate against ADAM and you don’t have a MOSS license, see this post on that topic.

Introduction

Note: If all you care about is the technical detail of how to set it up, skip this section. :-)

One of the powerful new features of Windows SharePoint Services v3 (and MOSS, as by extension) is its ability to use authentication providers other than Active Directory. Because it’s built on .NET 2.0, it can take advantage of the provider model for membership.

So who cares? Well, a common scenario for is that a company may want to give access to certain portions of their SharePoint site to their clients or business partners. It certainly makes sense to have their internal employees authenticate using their existing Active Directory structure, but it can be a management hassle (not to mention a procedural and regulatory one!) to create AD accounts for all of the external users.

WSS takes care of this situation by allowing for multiple authentication providers based on zone. It’s possible, then, to authenticate Intranet users against an existing Active Directory using NTLM, while using ASP.NET 2.0 forms-based authentication against a different membership database for the Extranet.

One possible membership database is Active Directory Application Mode (ADAM). ADAM allows for an application to take advantage of the user-management features of AD without all of its overhead (no DC required, etc.). It exposes its information via LDAP, and runs as a service on Windows Server 2003 or Windows XP.

This post describes the process of setting up an ADAM instance and configuring WSS to use it for Extranet user authentication.

Installing and Configuring ADAM

  1. The first step is to install and configure ADAM. You can download it free from here.
  2. Run the installation. At the end of the install, you’ll have an application group on your Start Menu called “ADAM.” Choose the “Create an ADAM Instance” option. (Note that ADAM allows you to run multiple instances on the same server, provided they’re listening on different ports.)
  3. On the first step of the ADAM wizard, choose to create a unique instance. (Screenshot)
  4. Next, give your ADAM instance a name. Tapping my creative juices, I used “ADAMTest.” (Screenshot)
  5. Set up the ports that the ADAM instance will use. Note that these must be ports that are not currently in use on your computer. The standard LDAP port is 389, and the SSL-enabled one is 636. I ran my install on a machine that was also a domain controller, so the LDAP ports were already in use. In that case, the wizard defaults them to 50000 and 50001. (Screenshot)
  6. The next step is setting up an application directory partition. You can do this after the wizard runs, but it’s easier to do it here. Give your partition a name in LDAP form. (Screenshot)
  7. In the next step, choose where you you’d like the data files for the directory to reside. Personally, the default location is nearly always my favorite. :-) (Screenshot)
  8. Choose the account in whose context you’d like the ADAM service to run. In this example, I used a domain account, though the Network Service account is fine, too. If you choose to connect to ADAM via SSL (something I’ll deal with in a later post), the SSL certificate you use needs to be made a part of the personal certificate store of the account under whose identity the ADAM service is running. (Screenshot)
  9. Select the account or group that will have administrative privileges within ADAM. In my case, you can see I’ve made this available to my computer’s administrators. (Screenshot)
  10. On the next screen, you’ll have the opportunity to import LDIF files. These files contain the schema information for specific entities within the directory. For the purposes of user authentication within MOSS, I’ve only needed the “MS-User.LDF” file. (Screenshot)
  11. That’s it for the install. The wizard will run, and assuming all goes well, it will complete and start up the new ADAM instance. The next step is to connect to the instance and do a little initial configuration.
    To connect to the instance, start the “ADAM ADSI Edit” utility from the ADAM folder on your Start Menu. Right-click on the top node of the tree view in the MMC console and select “Connect to.”
    Enter the connection information in the “Connection Settings” dialog. Choose to connect to a Distinguished name (DN), and enter the same value that you used for your application partition in step 6. (Screenshot)
    Your ADSI ADAM console should now look something like this.
  12. The next step I took is optional. You can put your user entries directly into the application partition itself. However, since there are other containers already there (e.g. Roles), I like to create a new container to hold the user information. To do this, right-click on the partition folder in the tree view, select “New” and “object” from the context menu.
    In the “Create Object” wizard, select “container” from the list of classes. (Screenshot)
    The next step will prompt you for the container name. I chose “Users.” (Screenshot)

That’s it! Just 12 short steps (grin) and your ADAM directory is ready to provide authentication services for WSS.

Configuring Multiple Authentication Providers in SharePoint 2007
This post assumes that you have an existing intranet site within WSS and that it is authenticating against Active Directory.

The first step in allowing WSS to connect to the ADAM instance is to make the provider available for use.

Edit the web.config for your SharePoint Central Administration site. Add the following block inside the <system.web> tags.

Note that you will need to modify the sections highlighted in red to fit your installation.

<membership defaultProvider=”ADAMMembership”>
  <providers>
    <add name=”ADAMMembership”
type=”Microsoft.Office.Server.Security.LDAPMembershipProvider, Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C”
    server=”myserver
    port=”50000
    useSSL=”false”
    userDNAttribute=”distinguishedName”
    userNameAttribute=”cn”
    userContainer=”CN=Users,OU=ADAMTest,O=ADAM,C=US
    userObjectClass=”user”
    userFilter=”(ObjectClass=user)”
    scope=”Subtree”
    otherRequiredUserAttributes=”sn,givenname,cn” />
  </providers>
</membership>

Note that the “userContainer” attribute is the distinguished name of the container I created in step 12 above.

Next, you’re ready to configure WSS to use the ADAM directory. Within the SharePoint admin site under “Application Management,” choose to “Create or extend web application” and click the “Extend an existing Web Application” link. (Screenshot)

When specifying the settings for the new IIS web site, you can specify a host header if this is how you want to segregate traffic from the extranet. Most, importantly, set the zone at the bottom of the page to “Extranet.” This differentiates this web site from the default site in the application, and will allow us to choose a different authentication provider. (Screenshot)

The next step is to specify that we want to use ADAM to authenticate the users coming from the Extranet zone. This is done using the “Authentication providers” link within Application Management. When you click the link, you should see two zones, Default and Extranet, configured to use Windows authentication. (Screenshot)

Click on the “Extranet” zone to modify the authentication provider for this zone. To use the provider we’ve configured, change the “Authentication Type” to be “Forms,” and set the “Membership provider name” to be the same as we specified in the web.config above. In this case, I called it “ADAMMembership.” (Screenshot)

Save that information. Your Authentication Providers list should now look like this.

Still with me? Just a few more steps!

So far, we’ve told the SharePoint administration site about the ADAM membership provider and told it to use that for authentication on a new IIS site that extends an existing application. Now we have to configure the web application to make sure that it’s aware of the ADAM provider.

To do this, open the web.config for the new IIS web site that you just created. Mine was found in “C:\Inetpub\wwwroot\wss\VirtualDirectories\extranet.myserver.local3072″; yours will be different, depending on how you set up your site.

Paste EXACTLY the same XML as above into the site’s web.config within the <system.web> section and save the file. Once you’ve completed that, try hitting the site you’ve set up; you should see the forms authentication screen.

Paste the same XML into the web.config for the intranet site. This is needed so that the PeoplePicker running on the intranet can search the ADAM directory.

As usual, save yourself any lurking questions and do a preventative iisreset. :-)

One final step: the account under which WSS is running needs to have “Read” permissions within the ADAM directory. To do this, go back to your “ADAM ADSI Edit” utility. Navigate to the “Roles” container within your application partition. The default install will place a group here called “Readers.” Right-click and select “Properties.” Scroll down to the “members” property and click the “Edit” button. On the member screen, click “Add Windows Account” and add the account under which your WSS instance is running. (Screenshot)

Next Steps
That’s all there is from a configuration standpoint. Your next steps will be to add users to the ADAM directory and configure permissions within WSS.

To add a user within ADAM, right-click on the “Users” container within “ADAM ADSI Edit” and select “New–>Object.” Choose “user” as the class, and enter the desired username as the “cn” of the new user.

Once you’ve created the new user, you can set the password by right-clicking the user in the right panel and selecting “Reset Password” from the context menu.

It’s also worth noting that when ADAM is installed, any existing password policy on a Windows Server 2003 instance is enforced (see this link for details). In my case, this causes any accounts that I create to be disabled until after I set a complex password. To enable the account, you need to set the “msDS-UserAccountDisabled” property of the user to false.

Now that you’ve created ADAM users, you must add them as users to SharePoint before they’ll be able to access the WSS site. You can do this using the standard user administration functions within SharePoint. You’ll notice from the intranet site that the PeoplePicker now validates and searches against both the Active Directory and against the ADAM directory.

Aquí encontrarán un excelente artículo sobre content deployment con SharePoint (MOSS 2007) http://masteringsharepoint.com/blogs/beagle/archive/2008/06/12/moss-2007-content-deployment-4-of-4.aspx

 

Saludos,

Eduardo Castro

Comunidad Windows Costa Rica – http://mswindowscr.org

Chris Johnson, ha creado un excelente post sobre las distintas formas de incluir aplicaciones desarrolladas en ASP.NET dentro de MOSS, pueden leerlo en la siguiente dirección http://blogs.msdn.com/cjohnson/archive/2006/09/05/740498.aspx

 

Technorati Tags: ,

 

I have been fortunate enough to have been involved deeply with one of our early Office TAP customer’s projects. TAP customers are given access to early builds and betas, along with support from Microsoft, to build a project on. The idea here is that they will be in a position to deploy early on the latest technology and at the same time have a positive impact on Microsoft delivering a quality product to market. TAP customers are key to us taking feedback as we build the product.

In the particular project I am involved with we are building quite an elaborate solution that is built using many of the new features in the 2007 Microsoft Office System. This ranges from the InfoPath embedded in a Win Forms control and on to Microsoft Office SharePoint Server 2007.

Here is a brief list of some of the things we are doing:

  • Building a .Net Win Forms application and embedding InfoPath to do rich offline forms capture in a custom application
  • Custom Visual Studio based Workflows build on Windows Workflow foundation
  • Custom Site Definitions, List Definitions, Timer Jobs deployed as Features via the Solution deployment framework

But what I really wanted to concentrate on in this post was talking about what options we considered for building some custom UI that is delivered inside MOSS and the pros and cons of each.

The options we looked at were:

  • Custom built Web Parts
  • A “_layouts” application (see below for what this is)
  • App built using User Controls & Son of SmartPart

The particular component of the application that I want to look at is the UI presentation “engine” i.e. what mechanisms deliver the UI.

Option 1: Custom built Web Parts

With this option you build all your UI using the Web Part framework. Logic etc… can be off in other .Net assemblies or a web service etc… just as you would with any other .Net Application.

Pros:

  • Built using ASP.Net Web Part framework
  • Deployed via Web Part install package or the new Feature/Solution Deployment mechanism
  • SharePoint application provides hosting framework for “putting” these Web Parts on Web Part pages
  • Communications framework for talking with other Web Parts
  • Designed to be highly re-usable across many sites with little effort

Cons:

  • No drag and drop UI for laying out your UI i.e. no design time surface
  • A framework that developers must learn to work within

Summary: A good use of web parts would be where you want to build a widget/mini-application that you can put on many web part pages across many sites.

Option 2: _layouts application

An _layouts application is when you develop an ASP.Net Web Application and deploy it to the c:\program files\common files\microsoft shared\web server extensions\12\template\layouts (what a mouthful!) directory. This is a special directory that gets “virtualized” in each sharepoint site i.e. in each sharepoint site you will have an /_layouts path from the root of the web. E.g. http://servername/sites/sitename/_layouts.

This means you can make your application available under each SharePoint site e.g. http://servername/sites/sitename/_layouts/MyApp/SomePage.aspx

In fact this is how all the SharePoint administration pages are delivered in each site.

Pros:

  • Great way to make your functionality available in every site
  • Easy to develop. It is just like developing a regular ASP.Net web site
  • Context sensitive access to the SharePoint object model. Great for doing work on the site that the user happens to be working in at the time.

Cons:

  • Deployment not managed via Solution deployment mechanism
  • Cant use the ASP.Net master page of the site context as the _layouts application is a separate ASP.Net application

Summary: It is best to use an _layouts based application when you want to extend every site with some functionality such as additional administration pages.

Option 3: User Controls and the Son of SmartPart

The last option is to build your applications UI in ASP.Net User Controls as you would with any other ASP.Net Web Application and then use the Son of SmartPart to deliver those User Controls via a web part.

The Son of SmartPart is a Web Part that is able to “host” an ASP.Net 2.0 User Control :) For more info on this see: http://www.smartpart.info/default.aspx
(if you are wondering who its father is … that is the SmartPart funnily enough … and is a Web Part for hosting ASP.Net 1.1 User Controls)

Pros:

  • Simple development experience.
  • You get a design surface to build you UI
  • Deployment reasonably straight forward
  • Can use Web Part connection framework if desired
  • Might be possible to develop these outside of SharePoint first (depending on if they have dependencies to SharePoint).

Cons:

  • Deployment not managed via Solution deployment mechanism Out of the Box (you could build a solution to deploy the Son of Smart Part)
  • Slightly different deployment of User Control files and assemblies (but nothing a .bat file can’t fix) during development.

Summary: I think this is a great option when you want to build a rich browser based UI that you only want to use in one (or a couple) of sites. I don’t think this is a good option if you want to build a mini-application that you want to include on many sites. A better option in that case might be a Web Part.

Option 4: ASPX pages added to SharePoint Site — ADDED 15-March-2007 UPDATED 16-November 2007

(Thanks to Michal Gwozdek for emailing me an updated set of steps that work for him)

This option actually was suggested in the comments by a reader.  I thought it was so good i tried it out … and it works great!  So here it is.

This option allows you to add your ASP.Net application pages into your SharePoint Site.  It also provides for compiling all using the code behind your pages into a DLL.

In a nutshell this option allows you to build your ASP.Net application outside of SharePoint, build it, test it & then add it to SharePoint.  Its great!

Here is how to do it:

1. Install the Visual Studio 2005 Web Application Projects extension.  This gives you the ‘old style’ web projects in Visual Studio … so you can compile down to a single DLL etc…

2. START – File – New Project – ASP.NET Web Application – Name it “ItDoesWork”

3. Add reference to Microsoft.Sharepoint

Leave only Microsoft.SharePoint, System, and System.Web

4. In the Solution Explorer create folder “~masterurl” and add masterpage “default.master” inside

5. Replace code behind for the masterpage with:

using System;
using Microsoft.SharePoint;
namespace ItDoesWork._masterurl
{

public partial class _default : System.Web.UI.MasterPage
{

protected void Page_Load(object sender, EventArgs e)
{
}

}

}

6. In the designer, rename ContentPlaceHolder’s ID to “PlaceHolderMain”

7. Delete Default.aspx, and add new page – SamplePage.aspx

8. Replace source content with the following:

<%@ Page Language=”C#” MasterPageFile=”~masterurl/default.master” CodeBehind=”SamplePage.aspx.cs” Inherits=”ItDoesWork.SamplePage” Title=”Untitled Page” meta:webpartpageexpansion=”full” meta:progid=”SharePoint.WebPartPage.Document” %>

<asp:Content ID=”Content5″ ContentPlaceHolderID=”PlaceHolderMain” runat=”server”>

Testing Page…

<asp:Label ID=”Label1″ runat=”server” Text=”Label”></asp:Label>

</asp:Content>

9. Replace code behind for the page with:

using System;
using Microsoft.SharePoint;

namespace ItDoesWork
{

public partial class SamplePage : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

Label1.Text = SPContext.Current.Site.Url;

}

}

}

10. Project properties – Build – Output path:

Point it to \BIN folder of our SharePoint Web application. E.g.

C:\Inetpub\wwwroot\wss\VirtualDirectories\moss.litwareinc.com80\bin

You can also manually copy your projects DLL into the \BIN folder each time.

11. Compile your project.

12. Open the web.config file for the SharePoint Web Applicaiton E.g.

C:\Inetpub\wwwroot\wss\VirtualDirectories\moss.litwareinc.com80\web.config

13. Add the following line to the SafeControls section (change to suit your assembly and namespace etc…)

<SafeControl Assembly=”ItDoesWork” Namespace=”ItDoesWork” TypeName=”*” />

14. Change the <trust level=”WSS_Minimal” originUrl=”" /> line to <trust level=”WSS_Medium” originUrl=”" />

15. Open your site in SharePoint Designer and drag and drop your SamplePage.aspx page into a folder in your site.

16. Browse to your page E.g.

http://moss.litwareinc.com/TestApp/TestPages.aspx

17. Jackpot! (Hopefully) You should now have your aspx page running in SharePoint.

One of the great things about this option is that you could build your applicaiton outside of SharePoint with any old MasterPage, then deploy to SharePoint and swap out the masterpage string for the correct one.  Thus being able to develop and debug outside of SharePoint and then deploy and test inside SharePoint. 

I can see this option being a favorite for most ASP.Net developers who are used to the integrated/seemless code, build & debug experience.

A note on debugging:  If you want to debug your code once it is running inside SharePoint then all you need to do is attach the Visual Studio debugger to the correct w3wp.exe process (Debug -> Attach to process), set your break points and then hit your page in a browser.

Pros:

  • Simple development experience. Develop outside SharePoint first if desired.
  • You get a design surface to build you UI
  • Deployment reasonably straight forward

Cons:

  • Deployment not managed via Solution deployment mechanism Out of the Box. ( but this might be possible i have not tried it yet)
  • Slightly different deployment of User Control files and assemblies (but nothing a .bat file can’t fix) during development.

I really like this option … coming from an ASP.Net point of view i feel it is a simple option.

 

image

 

In the project that I mentioned at the beginning of the post the following was true:

  • We wanted to surface application UI in one place in SharePoint
  • There was only ever going to be one instance of the application i.e. surfaced via one SharePoint site
  • Lots of different screens in the UI

Can you guess what option we decided on?

Well, it basically boiled down to either building the UI in Web Parts or using the Smart Part method.

In the end it was built using User Controls and the Smart Part because the developers would be more productive building User Controls (they didn’t have any prior SharePoint development experience) and we didn’t need to re-use any of the application in multiple sites.

So in the end we ended up with a document library to house Web Part pages for each of the UI “Screens”. In each of the web part pages we are using the Son of Smart Part to deliver our User Control that delivers that portion of the application.

I am really keen to hear what other options people are using to develop their applications that are delivered inside SharePoint. Feel free to leave comments …

-Chris.

Updated:  Changed title to include WSS v3 as Patrick rightly points out this is equally as applicable in WSS v3 also.

Posted: Tuesday, September 05, 2006 5:08 PM by chjohn

Follow

Get every new post delivered to your Inbox.