Imported Upstream version 4.6.0.125

Former-commit-id: a2155e9bd80020e49e72e86c44da02a8ac0e57a4
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2016-08-03 10:59:49 +00:00
parent a569aebcfd
commit e79aa3c0ed
17047 changed files with 3137615 additions and 392334 deletions

View File

@@ -0,0 +1,231 @@
//------------------------------------------------------------------------------
// <copyright file="ApplicationServiceHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Globalization;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.Profile;
using System.Web.Resources;
internal static class ApplicationServiceHelper {
// store profile properties allowed for get/set over the webservice
// a dictionary is used for perf, as .ContainsKey is called often
// These dictionaries are used for concurrent reads, but all writes are done on a new instance one per thread
// and isn't available for reading from other threads until the operation is complete.
// So it is safe to use Dictionary<K,V> in this case.
// We use Dictionary<string, object> instead of Dictionary<string, bool> to avoid violating
// FxCop Rule CA908: UseApprovedGenericsForPrecompiledAssemblies.
private static Dictionary<string, object> _profileAllowedGet;
private static Dictionary<string, object> _profileAllowedSet;
private static bool? _profileServiceEnabled;
private static bool? _roleServiceEnabled;
private static bool? _authServiceEnabled;
private static bool _authRequiresSSL;
internal static Dictionary<string, object> ProfileAllowedGet {
get {
EnsureProfileConfigLoaded();
return _profileAllowedGet;
}
}
internal static Dictionary<string, object> ProfileAllowedSet {
get {
EnsureProfileConfigLoaded();
return _profileAllowedSet;
}
}
internal static bool AuthenticationServiceEnabled {
get {
EnsureAuthenticationConfigLoaded();
return _authServiceEnabled.Value;
}
}
internal static bool ProfileServiceEnabled {
get {
EnsureProfileConfigLoaded();
return _profileServiceEnabled.Value;
}
}
internal static bool RoleServiceEnabled {
get {
// Get the flag on demand from config
if (_roleServiceEnabled == null) {
ScriptingRoleServiceSection roleServiceSection = ScriptingRoleServiceSection.GetConfigurationSection();
_roleServiceEnabled = (roleServiceSection != null) && roleServiceSection.Enabled;
}
return _roleServiceEnabled.Value;
}
}
internal static void EnsureAuthenticated(HttpContext context) {
//
bool authenticated = false;
IPrincipal user = GetCurrentUser(context);
if (user != null) {
IIdentity userIdentity = user.Identity;
if (userIdentity != null) {
authenticated = userIdentity.IsAuthenticated;
}
}
if (!authenticated) {
throw new HttpException(AtlasWeb.UserIsNotAuthenticated);
}
}
private static void EnsureAuthenticationConfigLoaded() {
// DevDiv 52730: drop the unnecessary double checked lock
if (_authServiceEnabled == null) {
ScriptingAuthenticationServiceSection authServicesSection = ScriptingAuthenticationServiceSection.GetConfigurationSection();
if (authServicesSection != null) {
_authRequiresSSL = authServicesSection.RequireSSL;
_authServiceEnabled = authServicesSection.Enabled;
}
else {
_authServiceEnabled = false;
}
}
}
// Fail if the Authentication Service is disabled or this is a non-ssl request and ssl is required
internal static void EnsureAuthenticationServiceEnabled(HttpContext context, bool enforceSSL) {
if (!AuthenticationServiceEnabled) {
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, AtlasWeb.AppService_Disabled, "AuthenticationService"));
}
if (enforceSSL && _authRequiresSSL && !context.Request.IsSecureConnection) {
throw new HttpException(403, AtlasWeb.AppService_RequiredSSL);
}
}
private static void EnsureProfileConfigLoaded() {
if (_profileServiceEnabled == null) {
#pragma warning disable 0436
ScriptingProfileServiceSection profileServiceSection = ScriptingProfileServiceSection.GetConfigurationSection();
#pragma warning restore 0436
Dictionary<string, object> readAccessProperties = null;
Dictionary<string, object> writeAccessProperties = null;
bool enabled = (profileServiceSection != null) && profileServiceSection.Enabled;
if (enabled) {
string[] enabledForRead = profileServiceSection.ReadAccessProperties;
if (enabledForRead != null && enabledForRead.Length > 0) {
readAccessProperties = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
ParseProfilePropertyList(readAccessProperties, enabledForRead);
}
string[] enabledForWriting = profileServiceSection.WriteAccessProperties;
if (enabledForWriting != null && enabledForWriting.Length > 0) {
writeAccessProperties = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
ParseProfilePropertyList(writeAccessProperties, enabledForWriting);
}
}
_profileAllowedGet = readAccessProperties;
_profileAllowedSet = writeAccessProperties;
_profileServiceEnabled = enabled;
}
}
// Fail if the Profile Service is disabled
internal static void EnsureProfileServiceEnabled() {
if (!ProfileServiceEnabled) {
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, AtlasWeb.AppService_Disabled, "ProfileService"));
}
}
// Fail if the Role Service is disabled
internal static void EnsureRoleServiceEnabled() {
if (!RoleServiceEnabled) {
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, AtlasWeb.AppService_Disabled, "RoleService"));
}
}
internal static IPrincipal GetCurrentUser(HttpContext context) {
return (context != null) ? context.User : Thread.CurrentPrincipal;
}
internal static Collection<ProfilePropertyMetadata> GetProfilePropertiesMetadata() {
EnsureProfileConfigLoaded();
if (ProfileBase.Properties == null) {
return new Collection<ProfilePropertyMetadata>();
}
Collection<ProfilePropertyMetadata> metadatas = new Collection<ProfilePropertyMetadata>();
foreach (SettingsProperty property in ProfileBase.Properties) {
string propertyName = property.Name;
// only return property metadata for properties that are allowed for Reading and/or Writing
bool allowedReadOrWrite = _profileAllowedGet.ContainsKey(propertyName) || _profileAllowedSet.ContainsKey(propertyName);
if (!allowedReadOrWrite) {
continue;
}
string defaultValue = null;
if (property.DefaultValue != null) {
if (property.DefaultValue is string) {
defaultValue = (string)property.DefaultValue;
}
else {
defaultValue = Convert.ToBase64String((byte[])property.DefaultValue);
}
}
ProfilePropertyMetadata metadata = new ProfilePropertyMetadata();
metadata.PropertyName = propertyName;
metadata.DefaultValue = defaultValue;
metadata.TypeName = property.PropertyType.AssemblyQualifiedName;
metadata.AllowAnonymousAccess = (bool)property.Attributes["AllowAnonymous"];
metadata.SerializeAs = (int)property.SerializeAs;
metadata.IsReadOnly = property.IsReadOnly;
metadatas.Add(metadata);
}
return metadatas;
}
internal static string GetUserName(IPrincipal user) {
if (user == null || user.Identity == null) {
return String.Empty;
}
else {
return user.Identity.Name;
}
}
private static void ParseProfilePropertyList(Dictionary<string, object> dictionary, string[] properties) {
foreach (string property in properties) {
string trimmed = property == null ? String.Empty : property.Trim();
if (property.Length > 0) {
dictionary[trimmed] = true;
}
}
}
}
}

View File

@@ -0,0 +1,31 @@
//------------------------------------------------------------------------------
// <copyright file="ApplicationServicesHostFactory.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Diagnostics.CodeAnalysis;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace System.Web.ApplicationServices {
public class ApplicationServicesHostFactory : ServiceHostFactory {
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) {
ServiceHost host = null;
if (typeof(ProfileService).Equals(serviceType)) {
host = new ServiceHost(new ProfileService(), baseAddresses);
}
else if (typeof(RoleService).Equals(serviceType)) {
host = new ServiceHost(new RoleService(), baseAddresses);
}
else if (typeof(AuthenticationService).Equals(serviceType)) {
host = new ServiceHost(new AuthenticationService(), baseAddresses);
}
else {
host = base.CreateServiceHost(serviceType, baseAddresses);
}
return host;
}
}
}

View File

@@ -0,0 +1,52 @@
//------------------------------------------------------------------------------
// <copyright file="AuthenticatingEventArgs.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices
{
using System;
using System.Web;
public class AuthenticatingEventArgs : EventArgs
{
private bool _authenticated;
public bool Authenticated {
get { return _authenticated; }
set { _authenticated = value; }
}
private bool _authenticationIsComplete;
public bool AuthenticationIsComplete {
get { return _authenticationIsComplete; }
set { _authenticationIsComplete = value; }
}
private string _userName;
public string UserName {
get { return _userName; }
}
private string _password;
public string Password {
get { return _password; }
}
private string _customCredential;
public string CustomCredential {
get { return _customCredential; }
}
internal AuthenticatingEventArgs(string username, string password, string customCredential) {
_authenticated = false;
_authenticationIsComplete = false;
_userName = username;
_password = password;
_customCredential = customCredential;
}
//hiding default constructor
private AuthenticatingEventArgs() { }
}
}

View File

@@ -0,0 +1,195 @@
//------------------------------------------------------------------------------
// <copyright file="AuthenticationService.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices {
using System;
using System.Diagnostics.CodeAnalysis;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Management;
using System.Web.Resources;
using System.Web.Security;
/// <devdoc>
/// Implements login service contract to be exposed as a WCF service. Uses Membership provider
/// or custom authentication login in the Authenticating event. Also uses Forms.SetAuthCookie() or
/// custom cookie generation via the CreatingCookie event.
/// </devdoc>
[
AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required),
ServiceContract(Namespace="http://asp.net/ApplicationServices/v200"),
ServiceBehavior(Namespace="http://asp.net/ApplicationServices/v200", InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)
]
public class AuthenticationService {
/// <devdoc>
/// Raised to authenticate the user . The event handler sets the e.AuthenticationIsComplete flag to true
/// and e.Authenticated to the result.
/// </devdoc>
private static object _authenticatingEventHandlerLock = new object();
private static EventHandler<AuthenticatingEventArgs> _authenticating;
public static event EventHandler<AuthenticatingEventArgs> Authenticating {
add {
lock (_authenticatingEventHandlerLock) {
_authenticating += value;
}
}
remove {
lock (_authenticatingEventHandlerLock) {
_authenticating -= value;
}
}
}
/// <devdoc>
/// Raised to create and set the cookie. The event handler shouldset the e.CookieIsSet flag to true, if it is
/// setting the cookie.
/// </devdoc>
private static object _creatingCookieEventHandlerLock = new object();
private static EventHandler<CreatingCookieEventArgs> _creatingCookie;
public static event EventHandler<CreatingCookieEventArgs> CreatingCookie {
add {
lock (_creatingCookieEventHandlerLock) {
_creatingCookie += value;
}
}
remove {
lock (_creatingCookieEventHandlerLock) {
_creatingCookie -= value;
}
}
}
public AuthenticationService() {
}
/// <devdoc>
/// Raises the AuthentincatingEvent if atleast one handler is assigned.
/// </devdoc>
private void OnAuthenticating(AuthenticatingEventArgs e) {
EventHandler<AuthenticatingEventArgs> handler = _authenticating;
if (null != handler) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the CreatingCookieEvent if atleast one handler is assigned.
/// </devdoc>
private void OnCreatingCookie(CreatingCookieEventArgs e) {
EventHandler<CreatingCookieEventArgs> handler = _creatingCookie;
if (null != handler) {
handler(this, e);
}
}
/// <devdoc>
/// Validates user credentials,without actually setting the FormAuth cookie
/// </devdoc>
/// <param name="username">Username of the account</param>
/// <param name="password">Password of the account</param>
/// <param name="customCredential">Any misc. string to be used by custom authentication logic</param>
/// <returns>True, if credentials are valid, otherwise false</returns>
[OperationContract]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="username", Justification="consistent with Whidbey")]
public bool ValidateUser(string username, string password, string customCredential) {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return LoginInternal(username, password, customCredential, false, false);
}
/// <devdoc>
/// Validates user credentials,and sets the FormAuth cookie if the credentials are valid.
/// </devdoc>
/// <param name="username">Username of the account</param>
/// <param name="password">Password of the account</param>
/// <param name="customCredential">Any misc. string to be used by custom authentication logic</param>
/// <param name="isPersistent">If true the persistant cookie is generated. </param>
/// <returns>True, if credentials are valid, otherwise false</returns>
[OperationContract]
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="username", Justification="consistent with Whidbey")]
public bool Login(string username, string password, string customCredential, bool isPersistent) {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return LoginInternal(username, password, customCredential, isPersistent, true);
}
/// <devdoc>
/// Checks whether the Forms Authentication cookie attached to the request is valid.
/// </devdoc>
[OperationContract]
public bool IsLoggedIn() {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, true);
return HttpContext.Current.User.Identity.IsAuthenticated;
}
/// <devdoc>
/// Clears the Forms Authentication cookie
/// </devdoc>
[OperationContract]
public void Logout() {
ApplicationServiceHelper.EnsureAuthenticationServiceEnabled(HttpContext.Current, false);
FormsAuthentication.SignOut();
}
/// <devdoc>
/// Validates the user credentials.
/// </devdoc>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="customCredential"></param>
/// <param name="isPersistent"></param>
/// <param name="setCookie">If this is true, CreatingCookie event is raised, and cookie is set in HttpResponse</param>
/// <returns></returns>
private bool LoginInternal(string username, string password, string customCredential, bool isPersistent, bool setCookie) {
if (null == username) {
throw new ArgumentNullException("username");
}
if (null == password) {
throw new ArgumentNullException("password");
}
AuthenticatingEventArgs authEventArgs = new AuthenticatingEventArgs(username, password, customCredential);
try {
OnAuthenticating(authEventArgs);
if (!authEventArgs.AuthenticationIsComplete) {
MembershipValidate(authEventArgs);
}
if (!authEventArgs.Authenticated) {
Logout();
}
if (authEventArgs.Authenticated && setCookie) {
CreatingCookieEventArgs cookieEventArgs = new CreatingCookieEventArgs(username, password, isPersistent, customCredential);
OnCreatingCookie(cookieEventArgs);
if (!cookieEventArgs.CookieIsSet) {
SetCookie(username, isPersistent);
}
}
}
catch (Exception e) {
LogException(e);
throw;
}
return authEventArgs.Authenticated;
}
private static void MembershipValidate(AuthenticatingEventArgs e) {
e.Authenticated = Membership.ValidateUser(e.UserName, e.Password);
}
private static void SetCookie(string username, bool isPersistent) {
FormsAuthentication.SetAuthCookie(username, isPersistent);
}
private void LogException(Exception e) {
WebServiceErrorEvent errorevent = new WebServiceErrorEvent(AtlasWeb.UnhandledExceptionEventLogMessage, this, e);
errorevent.Raise();
}
}
}

View File

@@ -0,0 +1,50 @@
//------------------------------------------------------------------------------
// <copyright file="CreatingCookieEventArgs.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices
{
using System;
public class CreatingCookieEventArgs : EventArgs {
private string _userName;
public string UserName {
get { return _userName; }
}
private string _password;
public string Password {
get { return _password; }
}
private string _customCredential ;
public string CustomCredential {
get { return _customCredential;}
}
private bool _isPersistent ;
public bool IsPersistent {
get { return _isPersistent;}
}
private bool _cookieIsSet;
public bool CookieIsSet {
set { _cookieIsSet = value; }
get { return _cookieIsSet; }
}
internal CreatingCookieEventArgs(string username, string password, bool isPersistent, string customCredential ) {
_cookieIsSet = false;
_userName = username;
_password = password;
_password = password;
_isPersistent = isPersistent;
_customCredential = customCredential;
}
//hiding default constructor
private CreatingCookieEventArgs() { }
}
}

View File

@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <copyright file="KnownTypesProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Configuration;
using System.Reflection;
using System.Web.Profile;
namespace System.Web.ApplicationServices
{
public static class KnownTypesProvider
{
public static Type[] GetKnownTypes(ICustomAttributeProvider knownTypeAttributeTarget)
{
if (ProfileBase.Properties == null)
return new Type[0];
Type[] retArray = new Type[ProfileBase.Properties.Count];
int i = 0;
foreach (SettingsProperty property in ProfileBase.Properties)
{
retArray[i++] = property.PropertyType;
}
return retArray;
}
}
}

View File

@@ -0,0 +1,124 @@
//------------------------------------------------------------------------------
// <copyright file="ProfilePropertyMetadata.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices
{
using System;
using System.Runtime.Serialization;
[DataContract]
public class ProfilePropertyMetadata : IExtensibleDataObject
{
private ExtensionDataObject _extensionDataObject;
private String _propertyName;
public ExtensionDataObject ExtensionData {
get {
return _extensionDataObject;
}
set {
_extensionDataObject = value;
}
}
[DataMember]
public String PropertyName
{
get
{
return _propertyName;
}
set
{
_propertyName = value;
}
}
private String _typeName;
[DataMember]
public String TypeName
{
get
{
return _typeName;
}
set
{
_typeName = value;
}
}
private bool _allowAnonymousAccess;
[DataMember]
public bool AllowAnonymousAccess
{
get
{
return _allowAnonymousAccess;
}
set
{
_allowAnonymousAccess = value;
}
}
private bool _isReadOnly;
[DataMember]
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
set
{
_isReadOnly = value;
}
}
/* Uncommnet once accessmode is available
public ProfileServiceAccess _accessMode;
[DataMember]
public ProfileServiceAccess AccessMode
{
get
{
return _accessMode;
}
set
{
_accessMode = value;
}
}
*/
private int _serializeAs;
[DataMember]
public int SerializeAs
{
get
{
return _serializeAs;
}
set
{
_serializeAs = value;
}
}
private string _defaultValue;
[DataMember]
public string DefaultValue
{
get
{
return _defaultValue;
}
set
{
_defaultValue = value;
}
}
}
}

View File

@@ -0,0 +1,317 @@
//------------------------------------------------------------------------------
// <copyright file="ProfileService.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web;
using System.Web.Management;
using System.Web.Profile;
using System.Web.Resources;
[ServiceContract(Namespace="http://asp.net/ApplicationServices/v200")]
[ServiceKnownType("GetKnownTypes", typeof(KnownTypesProvider))]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(Namespace="http://asp.net/ApplicationServices/v200", InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class ProfileService {
//////////////////////////////////////////////////////////////////////
/// <devdoc>
/// Raised to allow developers to validate property values being set by the client
/// </devdoc>
private static object _validatingPropertiesEventHandlerLock = new object();
private static EventHandler<ValidatingPropertiesEventArgs> _validatingProperties;
public static event EventHandler<ValidatingPropertiesEventArgs> ValidatingProperties {
add {
lock (_validatingPropertiesEventHandlerLock) {
_validatingProperties += value;
}
}
remove {
lock (_validatingPropertiesEventHandlerLock) {
_validatingProperties -= value;
}
}
}
/// <devdoc>
/// Raises the ValidatingPropertiesEvent if atleast one handler is assigned.
/// </devdoc>
private void OnValidatingProperties(ValidatingPropertiesEventArgs e) {
EventHandler<ValidatingPropertiesEventArgs> handler = _validatingProperties;
if (null != handler) {
handler(this, e);
}
}
public ProfileService() {
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
[OperationContract]
public Dictionary<string, object> GetPropertiesForCurrentUser(IEnumerable<string> properties, bool authenticatedUserOnly) {
if (properties == null) {
throw new ArgumentNullException("properties");
}
ApplicationServiceHelper.EnsureProfileServiceEnabled();
if (authenticatedUserOnly) {
ApplicationServiceHelper.EnsureAuthenticated(HttpContext.Current);
}
Dictionary<string, object> retDict = new Dictionary<string, object>();
ProfileBase pb = null;
try {
pb = GetProfileForCurrentUser(authenticatedUserOnly);
}
catch (Exception e) {
LogException(e);
throw;
}
if (pb == null) {
return null;
}
Dictionary<string, object> allowedGet = ApplicationServiceHelper.ProfileAllowedGet;
if (allowedGet == null || allowedGet.Count == 0) {
// there are no readable properties
return retDict;
}
foreach (string property in properties) {
if (property == null) {
throw new ArgumentNullException("properties");
}
if (allowedGet.ContainsKey(property)) {
try {
SettingsPropertyValue value = GetPropertyValue(pb, property);
if (value != null) {
retDict.Add(property, value.PropertyValue);
value.IsDirty = false;
}
}
catch (Exception e) {
LogException(e);
throw;
}
}
}
return retDict;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
[OperationContract]
public Dictionary<string, object> GetAllPropertiesForCurrentUser(bool authenticatedUserOnly) {
ApplicationServiceHelper.EnsureProfileServiceEnabled();
if (authenticatedUserOnly) {
ApplicationServiceHelper.EnsureAuthenticated(HttpContext.Current);
}
Dictionary<string, object> retDict = new Dictionary<string, object>();
try {
ProfileBase pb = GetProfileForCurrentUser(authenticatedUserOnly);
if (pb == null) {
return null;
}
Dictionary<string, object> allowedGet = ApplicationServiceHelper.ProfileAllowedGet;
if (allowedGet == null || allowedGet.Count == 0) {
// there are no readable properties
return retDict;
}
foreach (KeyValuePair<string, object> entry in allowedGet) {
string propertyName = entry.Key;
SettingsPropertyValue value = GetPropertyValue(pb, propertyName);
if (value != null) {
retDict.Add(propertyName, value.PropertyValue);
value.IsDirty = false;
}
}
}
catch (Exception e) {
LogException(e);
throw;
}
return retDict;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
[OperationContract]
public Collection<string> SetPropertiesForCurrentUser(IDictionary<string, object> values, bool authenticatedUserOnly) {
if (values == null) {
throw new ArgumentNullException("values");
}
ApplicationServiceHelper.EnsureProfileServiceEnabled();
if (authenticatedUserOnly) {
ApplicationServiceHelper.EnsureAuthenticated(HttpContext.Current);
}
Collection<string> sc = new Collection<string>();
try {
ValidatingPropertiesEventArgs vp = new ValidatingPropertiesEventArgs(values);
OnValidatingProperties(vp);
Dictionary<string, object> allowedSet = ApplicationServiceHelper.ProfileAllowedSet;
ProfileBase pb = GetProfileForCurrentUser(authenticatedUserOnly);
foreach (KeyValuePair<string, object> kvp in values) {
string propertyName = kvp.Key;
if (pb == null) {
sc.Add(propertyName);
continue;
}
if (vp.FailedProperties.Contains(propertyName)) {
sc.Add(propertyName);
continue;
}
if (allowedSet == null) {
sc.Add(propertyName);
continue;
}
if (!allowedSet.ContainsKey(propertyName)) {
sc.Add(propertyName);
continue;
}
SettingsProperty settingProperty = ProfileBase.Properties[propertyName];
if (settingProperty == null) {
// property not found
sc.Add(propertyName);
continue;
}
if (settingProperty.IsReadOnly || (pb.IsAnonymous && !(bool)settingProperty.Attributes["AllowAnonymous"])) {
// property is readonly, or the profile is anonymous and the property isn't enabled for anonymous access
sc.Add(propertyName);
continue;
}
SettingsPropertyValue value = GetPropertyValue(pb, kvp.Key);
if (value == null) { // property not found
sc.Add(propertyName);
continue;
}
else {
try {
pb[propertyName] = kvp.Value;
}
catch (System.Configuration.Provider.ProviderException) {
// provider specific error
sc.Add(propertyName);
}
catch (System.Configuration.SettingsPropertyNotFoundException) {
sc.Add(propertyName);
}
catch (System.Configuration.SettingsPropertyWrongTypeException) {
sc.Add(propertyName);
}
}
}
pb.Save();
}
catch (Exception e) {
LogException(e);
throw;
}
return sc;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
[OperationContract]
public ProfilePropertyMetadata[] GetPropertiesMetadata() {
ApplicationServiceHelper.EnsureProfileServiceEnabled();
try {
// todo: convert to array is temporary -- this method should just return Collection<> like the other profileservice does.
Collection<ProfilePropertyMetadata> metadatas = ApplicationServiceHelper.GetProfilePropertiesMetadata();
ProfilePropertyMetadata[] metadatasArray = new ProfilePropertyMetadata[metadatas.Count];
metadatas.CopyTo(metadatasArray, 0);
return metadatasArray;
}
catch (Exception e) {
LogException(e);
throw;
}
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
private static SettingsPropertyValue GetPropertyValue(ProfileBase pb, string name) {
SettingsProperty prop = ProfileBase.Properties[name];
if (prop == null) {
return null;
}
SettingsPropertyValue p = pb.PropertyValues[name];
if (p == null) {
// not fetched from provider
pb.GetPropertyValue(name); // to force a fetch from the provider
p = pb.PropertyValues[name];
if (p == null) {
return null;
}
}
return p;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
private static ProfileBase GetProfileForCurrentUser(bool authenticatedUserOnly) {
HttpContext context = HttpContext.Current;
IPrincipal user = ApplicationServiceHelper.GetCurrentUser(context);
string name = null;
bool isAuthenticated = false;
if (user == null || user.Identity == null || string.IsNullOrEmpty(user.Identity.Name)) { // anonymous user?
isAuthenticated = false;
if (!authenticatedUserOnly && context != null && !string.IsNullOrEmpty(context.Request.AnonymousID)) { // Use Anonymous ID?
name = context.Request.AnonymousID;
}
}
else {
name = user.Identity.Name;
isAuthenticated = user.Identity.IsAuthenticated;
}
if (!isAuthenticated && (authenticatedUserOnly || string.IsNullOrEmpty(name))) {
if (context != null)
throw new HttpException(AtlasWeb.UserIsNotAuthenticated);
else
throw new Exception(AtlasWeb.UserIsNotAuthenticated);
}
return ProfileBase.Create(name, isAuthenticated);
}
private void LogException(Exception e) {
WebServiceErrorEvent errorevent = new WebServiceErrorEvent(AtlasWeb.UnhandledExceptionEventLogMessage, this, e);
errorevent.Raise();
}
}
}

View File

@@ -0,0 +1,119 @@
//------------------------------------------------------------------------------
// <copyright file="RolesService.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices {
using System;
using System.Diagnostics.CodeAnalysis;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Configuration;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Security;
using System.Web.Configuration;
using System.Web.Management;
using System.Web.Resources;
using System.Security.Principal;
using System.Web.Hosting;
using System.Threading;
using System.Configuration.Provider;
[
AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required),
ServiceContract(Namespace = "http://asp.net/ApplicationServices/v200"),
ServiceBehavior(Namespace="http://asp.net/ApplicationServices/v200", InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)
]
public class RoleService {
private static object _selectingProviderEventHandlerLock = new object();
private static EventHandler<SelectingProviderEventArgs> _selectingProvider;
public static event EventHandler<SelectingProviderEventArgs> SelectingProvider {
add {
lock (_selectingProviderEventHandlerLock) {
_selectingProvider += value;
}
}
remove {
lock (_selectingProviderEventHandlerLock) {
_selectingProvider -= value;
}
}
}
private static void EnsureProviderEnabled() {
if (!Roles.Enabled) {
throw new ProviderException(AtlasWeb.RoleService_RolesFeatureNotEnabled);
}
}
private RoleProvider GetRoleProvider(IPrincipal user) {
string providerName = Roles.Provider.Name;
SelectingProviderEventArgs args = new SelectingProviderEventArgs(user, providerName);
OnSelectingProvider(args);
providerName = args.ProviderName;
RoleProvider provider = Roles.Providers[providerName];
if (provider == null) {
throw new ProviderException(AtlasWeb.RoleService_RoleProviderNotFound);
}
return provider;
}
[OperationContract]
public string[] GetRolesForCurrentUser() {
try {
ApplicationServiceHelper.EnsureRoleServiceEnabled();
EnsureProviderEnabled();
IPrincipal user = ApplicationServiceHelper.GetCurrentUser(HttpContext.Current);
string username = ApplicationServiceHelper.GetUserName(user);
RoleProvider provider = GetRoleProvider(user);
return provider.GetRolesForUser(username);
}
catch (Exception e) {
LogException(e);
throw;
}
}
[OperationContract]
public bool IsCurrentUserInRole(string role) {
if (role == null) {
throw new ArgumentNullException("role");
}
try {
ApplicationServiceHelper.EnsureRoleServiceEnabled();
EnsureProviderEnabled();
IPrincipal user = ApplicationServiceHelper.GetCurrentUser(HttpContext.Current);
string username = ApplicationServiceHelper.GetUserName(user);
RoleProvider provider = GetRoleProvider(user);
return provider.IsUserInRole(username, role);
}
catch (Exception e) {
LogException(e);
throw;
}
}
private void LogException(Exception e) {
WebServiceErrorEvent errorevent = new WebServiceErrorEvent(AtlasWeb.UnhandledExceptionEventLogMessage, this, e);
errorevent.Raise();
}
private void OnSelectingProvider(SelectingProviderEventArgs e) {
EventHandler<SelectingProviderEventArgs> handler = _selectingProvider;
if (handler != null) {
handler(this, e);
}
}
public RoleService() {
}
}
}

View File

@@ -0,0 +1,35 @@
//------------------------------------------------------------------------------
// <copyright file="SelectingProviderEventArgs.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices
{
using System;
using System.Security.Principal;
using System.Web;
public class SelectingProviderEventArgs : EventArgs
{
private IPrincipal _user;
public IPrincipal User {
get { return _user; }
}
private string _providerName;
public string ProviderName {
get { return _providerName; }
set { _providerName = value; }
}
internal SelectingProviderEventArgs(IPrincipal user, string providerName)
{
_user = user;
_providerName = providerName;
}
//hiding default constructor
private SelectingProviderEventArgs() { }
}
}

View File

@@ -0,0 +1,36 @@
//------------------------------------------------------------------------------
// <copyright file="ValidatingPropertiesEventArgs.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ApplicationServices
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web;
public class ValidatingPropertiesEventArgs: EventArgs{
private IDictionary<string,object> _properties;
public IDictionary<string,object> Properties{
get{
return _properties;
}
}
private Collection<string> _failedProperties;
public Collection<string> FailedProperties{
get{
return _failedProperties;
}
}
internal ValidatingPropertiesEventArgs(){}
internal ValidatingPropertiesEventArgs(IDictionary<string,object> properties){
_properties = properties;
_failedProperties = new Collection<string>();
}
}
}