comparison Demo/Asp.Net/BusinessLogic/ProfileProvider.cs @ 0:f990fcb411a9

Копия текущей версии из github
author cin
date Thu, 27 Mar 2014 21:46:09 +0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f990fcb411a9
1 using System;
2 using System.Collections.Generic;
3 using System.Collections.Specialized;
4 using System.Configuration;
5 using System.Web.Profile;
6
7 namespace PetShop.BusinessLogic
8 {
9 using DataAccess;
10 using ObjectModel;
11
12 public sealed class ProfileProvider : System.Web.Profile.ProfileProvider
13 {
14 private static string _applicationName = ".NET Pet Shop 4.0";
15
16 /// <summary>
17 /// The name of the application using the custom profile provider.
18 /// </summary>
19 public override string ApplicationName
20 {
21 get { return _applicationName; }
22 set { _applicationName = value; }
23 }
24
25 /// <summary>
26 /// Initializes the provider.
27 /// </summary>
28 /// <param name="name">The friendly name of the provider.</param>
29 /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
30 public override void Initialize(string name, NameValueCollection config)
31 {
32 if (config == null)
33 throw new ArgumentNullException("config");
34
35 if (string.IsNullOrEmpty(config["description"]))
36 {
37 config.Remove("description");
38 config.Add("description", "Pet Shop Custom Profile Provider");
39 }
40
41 if (string.IsNullOrEmpty(name))
42 name = "PetShopProfileProvider";
43
44 if (config["applicationName"] != null && !string.IsNullOrEmpty(config["applicationName"].Trim()))
45 _applicationName = config["applicationName"];
46
47 base.Initialize(name, config);
48 }
49
50 private const string ERR_INVALID_PARAMETER = "Invalid Profile parameter:";
51 private const string PROFILE_SHOPPINGCART = "ShoppingCart";
52 private const string PROFILE_WISHLIST = "WishList";
53 private const string PROFILE_ACCOUNT = "AccountInfo";
54
55 /// <summary>
56 /// Returns the collection of settings property values for the specified application instance and settings property group.
57 /// </summary>
58 /// <param name="context">A System.Configuration.SettingsContext describing the current application use.</param>
59 /// <param name="collection">A System.Configuration.SettingsPropertyCollection containing the settings property group whose values are to be retrieved.</param>
60 /// <returns>A System.Configuration.SettingsPropertyValueCollection containing the values for the specified settings property group.</returns>
61 public override SettingsPropertyValueCollection GetPropertyValues(
62 SettingsContext context, SettingsPropertyCollection collection)
63 {
64 string username = (string)context["UserName"];
65 bool isAuthenticated = (bool) context["IsAuthenticated"];
66
67 SettingsPropertyValueCollection svc = new SettingsPropertyValueCollection();
68
69 foreach (SettingsProperty prop in collection)
70 {
71 SettingsPropertyValue pv = new SettingsPropertyValue(prop);
72
73 switch (pv.Property.Name)
74 {
75 case PROFILE_SHOPPINGCART: pv.PropertyValue = GetCartItems(username, true); break;
76 case PROFILE_WISHLIST: pv.PropertyValue = GetCartItems(username, false); break;
77 case PROFILE_ACCOUNT:
78 if (isAuthenticated)
79 pv.PropertyValue = GetAccountInfo(username);
80 break;
81
82 default:
83 throw new ApplicationException(ERR_INVALID_PARAMETER + " name.");
84 }
85
86 svc.Add(pv);
87 }
88
89 return svc;
90 }
91
92 /// <summary>
93 /// Sets the values of the specified group of property settings.
94 /// </summary>
95 /// <param name="context">A System.Configuration.SettingsContext describing the current application usage.</param>
96 /// <param name="collection">A System.Configuration.SettingsPropertyValueCollection representing the group of property settings to set.</param>
97 public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
98 {
99 string username = (string)context["UserName"];
100
101 CheckUserName(username);
102
103 bool isAuthenticated = (bool)context["IsAuthenticated"];
104 int uniqueID = GetUniqueID(username, isAuthenticated, false, ApplicationName);
105
106 foreach (SettingsPropertyValue pv in collection)
107 {
108 if (pv.PropertyValue != null)
109 {
110 switch (pv.Property.Name)
111 {
112 case PROFILE_SHOPPINGCART: SetCartItems(uniqueID, (Cart)pv.PropertyValue, true); break;
113 case PROFILE_WISHLIST: SetCartItems(uniqueID, (Cart)pv.PropertyValue, false); break;
114 case PROFILE_ACCOUNT:
115 if (isAuthenticated)
116 SetAccountInfo(uniqueID, (Address)pv.PropertyValue);
117 break;
118
119 default:
120 throw new ApplicationException(ERR_INVALID_PARAMETER + " name.");
121 }
122 }
123 }
124
125 UpdateActivityDates(username, false);
126 }
127
128 private int GetUniqueID(string userName, bool isAuthenticated, bool ignoreAuthenticationType, string appName)
129 {
130 int? uniqueID = ignoreAuthenticationType ?
131 Accessor.GetUniqueID (userName, appName) :
132 Accessor.GetUniqueIDAuth(userName, appName, isAuthenticated);
133
134 return uniqueID ?? Accessor.CreateProfile(userName, appName, isAuthenticated);
135 }
136
137 private Address GetAccountInfo(string username)
138 {
139 return Accessor.GetAccountInfo(username, _applicationName);
140 }
141
142 private Cart GetCartItems(string username, bool isShoppingCart)
143 {
144 Cart cart = new Cart();
145
146 foreach (CartItem cartItem in Accessor.GetCartItems(username, _applicationName, isShoppingCart))
147 cart.Add(cartItem);
148
149 return cart;
150 }
151
152 private void SetAccountInfo(int uniqueID, Address address)
153 {
154 Accessor.SetAccountInfo(uniqueID, address);
155 }
156
157 private void SetCartItems(int uniqueID, Cart cart, bool isShoppingCart)
158 {
159 Accessor.SetCartItems(uniqueID, cart.Items, isShoppingCart);
160 }
161
162 // UpdateActivityDates
163 // Updates the LastActivityDate and LastUpdatedDate values
164 // when profile properties are accessed by the
165 // GetPropertyValues and SetPropertyValues methods.
166 // Passing true as the activityOnly parameter will update
167 // only the LastActivityDate.
168 private void UpdateActivityDates(string username, bool activityOnly)
169 {
170 if (activityOnly)
171 Accessor.UpdateActivityDate(username, _applicationName);
172 else
173 Accessor.UpdateActivityAndUdpateDates(username, _applicationName);
174 }
175
176 /// <summary>
177 /// Deletes profile properties and information for the supplied list of profiles.
178 /// </summary>
179 /// <param name="profiles">A System.Web.Profile.ProfileInfoCollection of information about profiles that are to be deleted.</param>
180 /// <returns>The number of profiles deleted from the data source.</returns>
181 public override int DeleteProfiles(ProfileInfoCollection profiles)
182 {
183 int deleteCount = 0;
184
185 foreach (ProfileInfo p in profiles)
186 if (DeleteProfile(p.UserName))
187 deleteCount++;
188
189 return deleteCount;
190 }
191
192 /// <summary>
193 /// Deletes profile properties and information for profiles that match the supplied list of user names.
194 /// </summary>
195 /// <param name="usernames">A string array of user names for profiles to be deleted.</param>
196 /// <returns>The number of profiles deleted from the data source.</returns>
197 public override int DeleteProfiles(string[] usernames)
198 {
199 int deleteCount = 0;
200
201 foreach (string user in usernames)
202 if (DeleteProfile(user))
203 deleteCount++;
204
205 return deleteCount;
206 }
207
208 // DeleteProfile
209 // Deletes profile data from the database for the specified user name.
210 private bool DeleteProfile(string username)
211 {
212 CheckUserName(username);
213
214 int? uniqueID = Accessor.GetUniqueID(username, _applicationName);
215
216 return uniqueID != null && Accessor.DeleteProfile(uniqueID.Value) > 0;
217 }
218
219 // Verifies user name for sise and comma
220 private static void CheckUserName(string userName)
221 {
222 if (string.IsNullOrEmpty(userName) || userName.Length > 256 || userName.IndexOf(",") > 0)
223 throw new ApplicationException(ERR_INVALID_PARAMETER + " user name.");
224 }
225
226 /// <summary>
227 /// Deletes all user-profile data for profiles in which the last activity date occurred before the specified date.
228 /// </summary>
229 /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are deleted.</param>
230 /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate value of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
231 /// <returns>The number of profiles deleted from the data source.</returns>
232 public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
233 {
234 IList<string> list;
235
236 switch (authenticationOption)
237 {
238 case ProfileAuthenticationOption.Anonymous:
239 list = Accessor.GetInactiveProfiles(userInactiveSinceDate, ApplicationName, true);
240 break;
241
242 case ProfileAuthenticationOption.Authenticated:
243 list = Accessor.GetInactiveProfiles(userInactiveSinceDate, ApplicationName, false);
244 break;
245
246 default:
247 list = Accessor.GetInactiveProfiles(userInactiveSinceDate, ApplicationName);
248 break;
249 }
250
251 string[] userArray = new string[list.Count];
252
253 list.CopyTo(userArray, 0);
254
255 return DeleteProfiles(userArray);
256 }
257
258 /// <summary>
259 /// Retrieves profile information for profiles in which the user name matches the specified user names.
260 /// </summary>
261 /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
262 /// <param name="usernameToMatch">The user name to search for.</param>
263 /// <param name="pageIndex">The index of the page of results to return.</param>
264 /// <param name="pageSize">The size of the page of results to return.</param>
265 /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param>
266 /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information
267 /// for profiles where the user name matches the supplied usernameToMatch parameter.</returns>
268 public override ProfileInfoCollection FindProfilesByUserName(
269 ProfileAuthenticationOption authenticationOption, string usernameToMatch,
270 int pageIndex, int pageSize, out int totalRecords)
271 {
272 CheckParameters(pageIndex, pageSize);
273
274 return GetProfileInfo(authenticationOption, usernameToMatch, null, pageIndex, pageSize, out totalRecords);
275 }
276
277 /// <summary>
278 /// Retrieves profile information for profiles in which the last activity date occurred on or before the specified date and the user name matches the specified user name.
279 /// </summary>
280 /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
281 /// <param name="usernameToMatch">The user name to search for.</param>
282 /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate value of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
283 /// <param name="pageIndex">The index of the page of results to return.</param>
284 /// <param name="pageSize">The size of the page of results to return.</param>
285 /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param>
286 /// <returns>A System.Web.Profile.ProfileInfoCollection containing user profile information for inactive profiles where the user name matches the supplied usernameToMatch parameter.</returns>
287 public override ProfileInfoCollection FindInactiveProfilesByUserName(
288 ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate,
289 int pageIndex, int pageSize, out int totalRecords)
290 {
291 CheckParameters(pageIndex, pageSize);
292
293 return GetProfileInfo(authenticationOption, usernameToMatch, userInactiveSinceDate, pageIndex, pageSize, out totalRecords);
294 }
295
296 /// <summary>
297 /// Retrieves user profile data for all profiles in the data source.
298 /// </summary>
299 /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
300 /// <param name="pageIndex">The index of the page of results to return.</param>
301 /// <param name="pageSize">The size of the page of results to return.</param>
302 /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param>
303 /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information for all profiles in the data source.</returns>
304 public override ProfileInfoCollection GetAllProfiles(
305 ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords)
306 {
307 CheckParameters(pageIndex, pageSize);
308
309 return GetProfileInfo(authenticationOption, null, null, pageIndex, pageSize, out totalRecords);
310 }
311
312 /// <summary>
313 /// Retrieves user-profile data from the data source for profiles in which the last activity date occurred on or before the specified date.
314 /// </summary>
315 /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
316 /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
317 /// <param name="pageIndex">The index of the page of results to return.</param>
318 /// <param name="pageSize">The size of the page of results to return.</param>
319 /// <param name="totalRecords">When this method returns, contains the total number of profiles.</param>
320 /// <returns>A System.Web.Profile.ProfileInfoCollection containing user-profile information about the inactive profiles.</returns>
321 public override ProfileInfoCollection GetAllInactiveProfiles(
322 ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate,
323 int pageIndex, int pageSize, out int totalRecords)
324 {
325 CheckParameters(pageIndex, pageSize);
326
327 return GetProfileInfo(authenticationOption, null, userInactiveSinceDate, pageIndex, pageSize, out totalRecords);
328 }
329
330 /// <summary>
331 /// Returns the number of profiles in which the last activity date occurred on or before the specified date.
332 /// </summary>
333 /// <param name="authenticationOption">One of the System.Web.Profile.ProfileAuthenticationOption values, specifying whether anonymous, authenticated, or both types of profiles are returned.</param>
334 /// <param name="userInactiveSinceDate">A System.DateTime that identifies which user profiles are considered inactive. If the System.Web.Profile.ProfileInfo.LastActivityDate of a user profile occurs on or before this date and time, the profile is considered inactive.</param>
335 /// <returns>The number of profiles in which the last activity date occurred on or before the specified date.</returns>
336 public override int GetNumberOfInactiveProfiles(
337 ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
338 {
339 int inactiveProfiles = 0;
340
341 ProfileInfoCollection profiles = GetProfileInfo(authenticationOption, null, userInactiveSinceDate, 0, 0, out inactiveProfiles);
342
343 return inactiveProfiles;
344 }
345
346 private static void CheckParameters(int pageIndex, int pageSize)
347 {
348 if (pageIndex < 1 || pageSize < 1)
349 throw new ApplicationException(ERR_INVALID_PARAMETER + " page index.");
350 }
351
352 // GetProfileInfo
353 // Retrieves a count of profiles and creates a
354 // ProfileInfoCollection from the profile data in the
355 // database. Called by GetAllProfiles, GetAllInactiveProfiles,
356 // FindProfilesByUserName, FindInactiveProfilesByUserName,
357 // and GetNumberOfInactiveProfiles.
358 // Specifying a pageIndex of 0 retrieves a count of the results only.
359 private ProfileInfoCollection GetProfileInfo(
360 ProfileAuthenticationOption authenticationOption,
361 string usernameToMatch,
362 DateTime? userInactiveSinceDate,
363 int pageIndex,
364 int pageSize,
365 out int totalRecords)
366 {
367 totalRecords = 0;
368
369 ProfileInfoCollection profiles = new ProfileInfoCollection();
370
371 // Count profiles only.
372 if (pageSize == 0)
373 return profiles;
374
375 int counter = 0;
376 int startIndex = pageSize * (pageIndex - 1);
377 int endIndex = startIndex + pageSize - 1;
378
379 bool? isAnonymous = null;
380
381 if (authenticationOption == ProfileAuthenticationOption.Anonymous)
382 isAnonymous = true;
383 else if (authenticationOption == ProfileAuthenticationOption.Authenticated)
384 isAnonymous = false;
385
386 foreach (CustomProfile profile in Accessor.GetProfile(
387 isAnonymous, usernameToMatch, userInactiveSinceDate, _applicationName, out totalRecords))
388 {
389 if (counter >= startIndex)
390 {
391 ProfileInfo p = new ProfileInfo(
392 profile.UserName,
393 profile.IsAnonymous ?? true,
394 profile.LastActivityDate ?? DateTime.MinValue,
395 profile.LastUpdatedDate ?? DateTime.MinValue, 0);
396
397 profiles.Add(p);
398 }
399
400 if (counter >= endIndex)
401 break;
402
403 counter++;
404 }
405
406 return profiles;
407 }
408
409 #region Accessor
410
411 ProfileAccessor Accessor
412 {
413 [System.Diagnostics.DebuggerStepThrough]
414 get { return ProfileAccessor.CreateInstance(); }
415 }
416
417 #endregion
418 }
419 }