|
Project Information
Featured
|
NHProfile - ASP.NET NHibernate Profile ProviderОписание на русском см. ниже. Quick overviewNHProfile manages storage of profile information for an ASP.NET application using NHibernate. NHProfile can be useful if you need to store profile information in a data source that is not supported by the profile providers included with the .NET Framework (PostgreSQL, Oracle databases or others). NHProfile can be used in conjunction with Manuel Abadia's ASP.NET Custom Membership and Role Providers. Setup and configurationAfter downloading NHProfile, you will have to add a reference to the assembly NHibernate.Profile.dll in your project. It is assumed that NHibernate already configured in your project (see sources for example). NHibernate version 2.0.1 is currently used. Also, you will have to register the provider in your web.config file. Add the following XML code somewhere in the <system.web> section: <profile defaultProvider="NHProfileProvider">
<providers>
<clear/>
<add name="NHProfileProvider" type="NHibernate.Profile.NHProfileProvider, NHibernate.Profile"
TableName="Profile"
UserNameColumn="UserName" UserNameType="String" UserNameLength="200"/>
</providers>
<properties>
<add name="TimeZone" type="string" /> <!-- User property example -->
</properties>
</profile>This code allows you to configure provider according to your data schema. The following table describes all parameters that can be configured. | Attribute | Default value | Description | | TableName | Profile | Profile table name | | UserNameColumn | UserName | User name | table column name | | UserNameType | String | NHibernate data type | | UserNameLength | 200 | max. data string length | | PropertyNamesColumn | PropertyNames | Profile properties list | table column name | | PropertyNamesType | String | NHibernate data type | | PropertyNamesLength | | max. data string length | | PropertyValuesStringColumn | PropertyValuesString | Profile string values | table column name | | PropertyValuesStringType | String | NHibernate data type | | PropertyValuesStringLength | | max. data string length | | PropertyValuesBinaryColumn | PropertyValuesBinary | Profile binary values | table column name | | PropertyValuesBinaryType | BinaryBlob | NHibernate data type | | PropertyValuesBinaryLength | | max. data string length | | LastActivityDateColumn | LastActivityDate | Last date and time when the profile was read or updated | table column name | | LastActivityDateType | DateTime | NHibernate data type | | LastActivityDateLength | | max. data string length | | LastUpdateDateColumn | LastUpdateDate | Last date and time when the profile was updated | table column name | | LastUpdateDateType | DateTime | NHibernate data type | | LastUpdateDateLength | | max. data string length | The last thing you have to do is to create table in your database. By default provider uses the table with the following schema: CREATE TABLE [Profile](
[UserName] [nvarchar](200) NOT NULL,
[PropertyNames] [ntext] NULL,
[PropertyValuesString] [ntext] NULL,
[PropertyValuesBinary] [image] NULL,
[LastActivityDate] [datetime] NOT NULL,
[LastUpdateDate] [datetime] NOT NULL,
CONSTRAINT [PK_Profile] PRIMARY KEY
(
[UserName] ASC
)
)Now everything is prepared and you can use NHProfile in your project. Code exampleYou can use NHProfile in an ASP.NET application in the usual way. To get the value of a profile property: object timeZone = HttpContext.Profile.GetPropertyValue("TimeZone");To set the value of a profile property: HttpContext.Profile.SetPropertyValue("TimeZone", TimeZone);
Краткое описаниеNHProfile реализует хранение пользовательских профилей ASP.NET, используя NHibernate для доступа к данным. NHProfile может пригодиться, если необходимо хранить профиль пользователя в источнике данных, не поддерживаемом стандартным поставщиком профилей .NET Framework (база данных PostgreSQL, Oracle и другие). NHProfile может быть испльзован вместе с пользовательскими поставщиками участия и ролей Manuel Abadia. Подготовка к использованиюПосле того, как вы скачали NHProfile, в ваш проект необходимо добавить сборку NHibernate.Profile.dll. Т.к. для работы NHProfile требует NHibernate, далее в описании подразумевается, что все необходимые для него сборки уже добавлены в проект, NHibernate настроен и работает (см. пример в исходных кодах). В настоящее время используется NHibernate версии 2.0.1 Затем нужно зарегистрировать провайдер в файле web.config. Добавьте приведенный ниже фрагмент xml кода в раздел <system.web>. <profile defaultProvider="NHProfileProvider">
<providers>
<clear/>
<add name="NHProfileProvider" type="NHibernate.Profile.NHProfileProvider, NHibernate.Profile"
TableName="Profile"
UserNameColumn="UserName" UserNameType="String" UserNameLength="200"/>
</providers>
<properties>
<add name="TimeZone" type="string" /> <!-- Пример пользовательского свойства -->
</properties>
</profile>Здесь же вы можете настроить провайдер на нужную вам схему данных. В следующей таблице перечислены все параметры, доступные для настройки. | Атрибут | Значение по умолчанию | Описание | | TableName | Profile | Таблица для хранения профилей | | UserNameColumn | UserName | Имя пользователя | наименование столбца в БД | | UserNameType | String | тип данных NHibernate | | UserNameLength | 200 | максимальная длина строки данных | | PropertyNamesColumn | PropertyNames | Список всех свойств профиля | наименование столбца в БД | | PropertyNamesType | String | тип данных NHibernate | | PropertyNamesLength | | максимальная длина строки данных | | PropertyValuesStringColumn | PropertyValuesString | Текстовые занчения свойств профиля | наименование столбца в БД | | PropertyValuesStringType | String | тип данных NHibernate | | PropertyValuesStringLength | | максимальная длина строки данных | | PropertyValuesBinaryColumn | PropertyValuesBinary | Двоичные занчения свойств профиля | наименование столбца в БД | | PropertyValuesBinaryType | BinaryBlob | тип данных NHibernate | | PropertyValuesBinaryLength | | максимальная длина строки данных | | LastActivityDateColumn | LastActivityDate | Дата последнего обращения к профилю | наименование столбца в БД | | LastActivityDateType | DateTime | тип данных NHibernate | | LastActivityDateLength | | максимальная длина строки данных | | LastUpdateDateColumn | LastUpdateDate | Дата последнего изменения профиля | наименование столбца в БД | | LastUpdateDateType | DateTime | тип данных NHibernate | | LastUpdateDateLength | | максимальная длина строки данных | Все, что осталось сделать, это создать таблицу в базе данных. По-умолчанию для хранения данных провайдер использует одну таблицу, схема которой представлена ниже. CREATE TABLE [Profile](
[UserName] [nvarchar](200) NOT NULL,
[PropertyNames] [ntext] NULL,
[PropertyValuesString] [ntext] NULL,
[PropertyValuesBinary] [image] NULL,
[LastActivityDate] [datetime] NOT NULL,
[LastUpdateDate] [datetime] NOT NULL,
CONSTRAINT [PK_Profile] PRIMARY KEY
(
[UserName] ASC
)
)Теперь провайдер готов к работе. Пример использованияВ ASP.NET приложении NHProfile используется стандартным образом. Чтение из профиля: object timeZone = HttpContext.Profile.GetPropertyValue("TimeZone");Запись в профиль: HttpContext.Profile.SetPropertyValue("TimeZone", TimeZone);БлагодарностиNHProfile создан и развивается при поддержке ЗАО «Электронные и компьютерные технологии».
|