Skip to content

Instantly share code, notes, and snippets.

@seraphy
Created October 31, 2013 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seraphy/7251779 to your computer and use it in GitHub Desktop.
Save seraphy/7251779 to your computer and use it in GitHub Desktop.
ASP.NETのプロファイルの使い方。匿名ユーザも識別する場合の実装例。 匿名ユーザから特定のユーザにログインされた場合に、 匿名ユーザの状態で設定されたプロファイルの内容をマージし、且つ、特定ユーザーのプロファイルとユーザ識別情報を削除する。 (ただし、この他に期限切れの匿名ユーザのガベージ処理が必要)
<?xml version="1.0" encoding="utf-8" ?>
<profile defaultProvider="DefaultProfileProvider" enabled="true" >
<providers>
<add name="DefaultProfileProvider"
type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection"
applicationName="/" />
</providers>
<properties>
<group name="HtmlEscape">
<!-- HtmlEscape -->
<add name="TabSize" type="System.Int32" defaultValue="8" allowAnonymous="true"/>
<add name="Mode" type="System.String" defaultValue="Simple" allowAnonymous="true"/>
</group>
<group name="SqlEnclosure">
<!-- SqlEnclosure -->
<add name="ReplaceChars" type="System.String" defaultValue="@@" allowAnonymous="true"/>
<add name="Pattern" type="System.String" defaultValue="strSQL = strSQL &amp; &quot;@@&quot; &amp; vbCrLf" allowAnonymous="true"/>
</group>
</properties>
</profile>
/// <summary>
/// 匿名ユーザから特定のユーザにログインされた場合に、
/// 匿名ユーザの状態で設定されたプロファイルの内容をマージし、
/// 且つ、特定ユーザーのプロファイルとユーザ識別情報を削除する.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void Profile_OnMigrateAnonymous(object sender, ProfileMigrateEventArgs args)
{
foreach (ProfileInfo profile in ProfileManager.FindProfilesByUserName(
ProfileAuthenticationOption.Anonymous, args.AnonymousID))
{
if (string.Equals(profile.UserName, args.AnonymousID))
{
// 匿名としてのプロファイルの登録内容をログインしたプロファイルに転記する
ProfileBase newProfile = HttpContext.Current.Profile;
ProfileBase oldProfile = ProfileBase.Create(args.AnonymousID, false);
foreach (SettingsProperty prop in ProfileBase.Properties)
{
// プロパティ定義一覧とデフォルト値の取得
string propertyName = prop.Name;
object defValue = prop.DefaultValue;
Type defValueType = prop.PropertyType;
if (defValue != null && defValueType != null)
{
// デフォルト値は型変換しておく
defValue = Convert.ChangeType(defValue, defValueType);
}
// 匿名プロファイルでの設定値
object value = oldProfile.GetPropertyValue(propertyName);
if (!object.Equals(defValue, value))
{
// 匿名プロファイルでデフォルト値から設定値を変えていた場合は
// 名前つきプロファイル側に更新内容を反映する.
// (デフォルト値のままであれば以前のものを優先する.)
newProfile.SetPropertyValue(propertyName, value);
}
}
// 匿名ユーザのプロファイルとユーザ登録を
// DBおよび セッションから削除します
ProfileManager.DeleteProfile(args.AnonymousID);
AnonymousIdentificationModule.ClearAnonymousIdentifier();
Membership.DeleteUser(args.AnonymousID, true);
}
}
}
// プロファイルから前回設定値の読み込み (新規の場合はデフォルト値)
var profile = Context.Profile;
var profileGroup = profile.GetProfileGroup("SqlEnclosure");
var pattern = (string)profileGroup.GetPropertyValue("Pattern");
var replaceChars = (String)profileGroup.GetPropertyValue("ReplaceChars");
<!-- 匿名ユーザを有効にすると、自動的に、アクセスしたユーザに対する
Usersレコードが追記されて、どんどん無制限に増える.
自動的には削除されず、削除するAPIもないため独自のガベージ処理が必要となる.
-->
<anonymousIdentification
enabled="true"
cookieless="AutoDetect"
cookieProtection="Validation"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieTimeout="1"
cookiePath="/"
cookieName=".ASPXANONYMOUS"
domain=""
/>
<!-- SQL Server Compact Edition 4.0 を使ったメンバーシップ・プロファイルの利用方法.
(1) NuGetのPackage Managerで、コンポーネントをインストールする.
"PM> Install-Package Microsoft.AspNet.Providers.SqlCE"
これで、SqlCE4のライブラリと、Universal Provider for Session, Membership, Roles, and User Profile
がインストールされる.
(2) ConnectionStringでApp_Data下のsdfファイル名を指定する。
初回利用時にテーブルは自動作成される.
-->
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<!-- メンバーシッププロバイダは、パスワードはハッシュ化しない。
フォーマットとして、Clear:0、Encrypted:2のいずれかを使用できる -->
<add name="DefaultMembershipProvider"
type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection"
passwordFormat="Encrypted"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/"/>
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider"
enabled="true"
cacheRolesInCookie="true">
<providers>
<add name="DefaultRoleProvider"
type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection"
applicationName="/" />
</providers>
</roleManager>
<!-- プロファイルの設定はプロパティが多数あるので外部ファイルに分離.
※ Webアプリケーションプロジェクトの場合、PageクラスのProfileプロパティは作成されず、
厳密な型指定されたプロファイルクラス(ProfileCommon)は自動生成されないことに注意.
http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx
-->
<profile configSource="Config\profile.xml"/>
<!--
<sessionState mode="InProc"
customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider"
type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection"
applicationName="/" />
</providers>
</sessionState>
-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment