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>();
}
}
}

View File

@@ -0,0 +1,94 @@
//------------------------------------------------------------------------------
// <copyright file="ClientFormsIdentity.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices
{
using System;
using System.Net;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Security;
using System.Web.Security;
using System.Diagnostics.CodeAnalysis;
public class ClientFormsIdentity : IIdentity, IDisposable
{
public string Name { get { return _Name; }}
public bool IsAuthenticated { get { return _IsAuthenticated; }}
public string AuthenticationType { get { return _AuthenticationType; } }
public CookieContainer AuthenticationCookies { get { return _AuthenticationCookies; } }
public MembershipProvider Provider { get { return _Provider; } }
public ClientFormsIdentity(string name, string password, MembershipProvider provider, string authenticationType, bool isAuthenticated, CookieContainer authenticationCookies)
{
_Name = name;
_AuthenticationType = authenticationType;
_IsAuthenticated = isAuthenticated;
_AuthenticationCookies = authenticationCookies;
_Password = GetSecureStringFromString(password);
_Provider = provider;
}
public void RevalidateUser()
{
if (_Disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
_Provider.ValidateUser(_Name, GetStringFromSecureString(_Password));
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_Password != null)
{
_Password.Dispose();
}
}
_Disposed = true;
}
private string _Name;
private bool _IsAuthenticated;
private string _AuthenticationType;
private CookieContainer _AuthenticationCookies;
private SecureString _Password;
private MembershipProvider _Provider;
private bool _Disposed;
private static SecureString GetSecureStringFromString(string password)
{
char[] passwordChars = password.ToCharArray();
SecureString ss = new SecureString();
for (int iter = 0; iter < passwordChars.Length; iter++)
ss.AppendChar(passwordChars[iter]);
ss.MakeReadOnly();
return ss;
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Reviewed and approved by feature crew")]
[SecuritySafeCritical]
private static string GetStringFromSecureString(SecureString securePass)
{
IntPtr bstr = IntPtr.Zero;
try {
bstr = Marshal.SecureStringToBSTR(securePass);
return Marshal.PtrToStringBSTR(bstr);
} finally {
if (bstr != IntPtr.Zero)
Marshal.FreeBSTR(bstr);
}
}
}
}

View File

@@ -0,0 +1,25 @@
//------------------------------------------------------------------------------
// <copyright file="ClientRolePrincipal.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices
{
using System;
using System.Net;
using System.Security.Principal;
public class ClientRolePrincipal : IPrincipal
{
public IIdentity Identity { get { return _Identity; } }
private IIdentity _Identity;
public ClientRolePrincipal(IIdentity identity) {
_Identity = identity;
}
public bool IsInRole(string role)
{
return System.Web.Security.Roles.IsUserInRole(_Identity.Name, role);
}
}
}

View File

@@ -0,0 +1,56 @@
//------------------------------------------------------------------------------
// <copyright file="ConnectivityStatus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices
{
using System;
using System.IO;
using System.Security.Principal;
using System.Security;
using System.Security.Permissions;
using System.Security.AccessControl;
public static class ConnectivityStatus
{
public static bool IsOffline {
get {
if (!_IsOfflineFetched)
FetchIsOffline();
return _IsOffline;
}
set {
if (IsOffline != value) {
_IsOffline = value;
StoreIsOffline();
}
}
}
private static bool _IsOffline;
private static bool _IsOfflineFetched;
//[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private static void FetchIsOffline()
{
string path = Path.Combine(System.Windows.Forms.Application.UserAppDataPath, "AppIsOffline");
_IsOffline = File.Exists(path);
_IsOfflineFetched = true;
}
//[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private static void StoreIsOffline()
{
string path = Path.Combine(System.Windows.Forms.Application.UserAppDataPath, "AppIsOffline");
if (!_IsOffline) {
File.Delete(path);
} else {
using (FileStream fs = File.Create(path)) {
fs.Write(new byte[0], 0, 0);
}
}
}
}
}

View File

@@ -0,0 +1,324 @@
//------------------------------------------------------------------------------
// <copyright file="ClientData.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices.Providers
{
using System;
using System.Security;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Globalization;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Schema;
using System.Xml;
using System.Collections.Specialized;
using System.IO.IsolatedStorage;
internal class ClientData
{
internal enum ClientDateStoreOrderEnum {
LastLoggedInUserName = 0,
LastLoggedInDateUtc = 1,
PasswordHash = 2,
PasswordSalt = 3,
Roles = 4,
RolesCachedDateUtc = 5,
SettingsNames = 6,
SettingsStoredAs = 7,
SettingsValues = 8,
SettingsNeedReset = 9,
SettingsCacheIsMoreFresh = 10,
CookieNames = 11,
CookieValues = 12
}
private const int _NumStoredValues = 13;
private static string[] _StoredValueNames = new string[_NumStoredValues] {
"LastLoggedInUserName",
"LastLoggedInDateUtc",
"PasswordHash",
"PasswordSalt",
"Roles",
"RolesCachedDateUtc",
"SettingsNames",
"SettingsStoredAs",
"SettingsValues",
"SettingsNeedReset",
"SettingsCacheIsMoreFresh",
"CookieNames",
"CookieValues"};
private object[] _StoredValues = new object[_NumStoredValues] {
"",
DateTime.UtcNow.AddYears(-1),
string.Empty,
string.Empty,
new string[0],
DateTime.UtcNow.AddYears(-1),
new string[0],
new string[0],
new string[0],
false,
false,
new string[0],
new string[0]};
private ClientData() { }
private ClientData(XmlReader reader)
{
reader.ReadStartElement("ClientData");
for (int iter = 0; iter < _NumStoredValues; iter++) {
reader.ReadStartElement(_StoredValueNames[iter]);
if (_StoredValues[iter] is string)
_StoredValues[iter] = reader.ReadContentAsString();
else if (_StoredValues[iter] is DateTime) {
string s = reader.ReadContentAsString();
long l = long.Parse(s, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
_StoredValues[iter] = DateTime.FromFileTimeUtc(l);
} else if (_StoredValues[iter] is bool) {
string s = reader.ReadContentAsString();
_StoredValues[iter] = !(string.IsNullOrEmpty(s) || s != "1");
} else {
_StoredValues[iter] = ReadStringArray(reader);
}
reader.ReadEndElement();
}
reader.ReadEndElement();
}
private static string[] ReadStringArray(XmlReader reader)
{
//string count = reader.GetAttribute("count");
//if (string.IsNullOrEmpty(count))
// return new string[0];
StringCollection sc = new StringCollection();
while (reader.IsStartElement())
{
reader.ReadStartElement("item");
sc.Add(reader.ReadContentAsString());
reader.ReadEndElement();
}
string[] retValue = new string[sc.Count];
sc.CopyTo(retValue, 0);
return retValue;
}
private static void WriteStringArray(XmlWriter writer, string [] arrToWrite)
{
//writer.WriteAttributeString("count", arrToWrite.Length.ToString());
if (arrToWrite.Length == 0)
writer.WriteValue(string.Empty);
for (int iter = 0; iter < arrToWrite.Length; iter++) {
writer.WriteStartElement("item");
writer.WriteValue((arrToWrite[iter]==null) ? string.Empty : arrToWrite[iter]);
writer.WriteEndElement();
}
}
// App data
internal string LastLoggedInUserName { get { return (string)_StoredValues[(int)ClientDateStoreOrderEnum.LastLoggedInUserName]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.LastLoggedInUserName] = value; } }
internal DateTime LastLoggedInDateUtc { get { return (DateTime)_StoredValues[(int)ClientDateStoreOrderEnum.LastLoggedInDateUtc]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.LastLoggedInDateUtc] = value; } }
// Membership data
internal string PasswordHash { get { return (string)_StoredValues[(int)ClientDateStoreOrderEnum.PasswordHash]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.PasswordHash] = value; } }
internal string PasswordSalt { get { return (string)_StoredValues[(int)ClientDateStoreOrderEnum.PasswordSalt]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.PasswordSalt] = value; } }
// Roles data
internal string[] Roles { get { return (string[])_StoredValues[(int)ClientDateStoreOrderEnum.Roles]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.Roles] = value; } }
internal DateTime RolesCachedDateUtc { get { return (DateTime)_StoredValues[(int)ClientDateStoreOrderEnum.RolesCachedDateUtc]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.RolesCachedDateUtc] = value; } }
// Settings data
internal string[] SettingsNames { get { return (string[])_StoredValues[(int)ClientDateStoreOrderEnum.SettingsNames]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.SettingsNames] = value; } }
internal string[] SettingsStoredAs{ get { return (string[])_StoredValues[(int)ClientDateStoreOrderEnum.SettingsStoredAs]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.SettingsStoredAs] = value; } }
internal string[] SettingsValues { get { return (string[])_StoredValues[(int)ClientDateStoreOrderEnum.SettingsValues]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.SettingsValues] = value; } }
internal bool SettingsNeedReset { get { return (bool)_StoredValues[(int)ClientDateStoreOrderEnum.SettingsNeedReset]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.SettingsNeedReset] = value; } }
internal bool SettingsCacheIsMoreFresh { get { return (bool)_StoredValues[(int)ClientDateStoreOrderEnum.SettingsCacheIsMoreFresh]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.SettingsCacheIsMoreFresh] = value; } }
// Cookie data
internal string[] CookieNames { get { return (string[])_StoredValues[(int)ClientDateStoreOrderEnum.CookieNames]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.CookieNames] = value; } }
internal string[] CookieValues { get { return (string[])_StoredValues[(int)ClientDateStoreOrderEnum.CookieValues]; } set { _StoredValues[(int)ClientDateStoreOrderEnum.CookieValues] = value; } }
// Filename
private string FileName = string.Empty;
private bool UsingIsolatedStorage = false;
private const string _IsolatedDir = "System.Web.Extensions.ClientServices.ClientData";
internal void Save()
{
if (!UsingIsolatedStorage) {
using (XmlWriter writer = XmlWriter.Create(FileName)) {
Save(writer);
}
} else {
using(IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly()) {
if (f.GetDirectoryNames(_IsolatedDir).Length == 0)
f.CreateDirectory(_IsolatedDir);
using(IsolatedStorageFileStream fs = new IsolatedStorageFileStream(FileName, FileMode.Create, f)) {
using (XmlWriter writer = XmlWriter.Create(fs)) {
Save(writer);
}
}
}
}
}
private void Save(XmlWriter writer)
{
writer.WriteStartElement("ClientData");
for (int iter = 0; iter < _NumStoredValues; iter++) {
writer.WriteStartElement(_StoredValueNames[iter]);
if (_StoredValues[iter] == null) {
writer.WriteValue(string.Empty);
} else if (_StoredValues[iter] is string) {
writer.WriteValue(_StoredValues[iter]);
} else if (_StoredValues[iter] is bool) {
writer.WriteValue(((bool)_StoredValues[iter]) ? "1" : "0");
} else if (_StoredValues[iter] is DateTime) {
writer.WriteValue(((DateTime)_StoredValues[iter]).ToFileTimeUtc().ToString("X", CultureInfo.InvariantCulture));
} else {
WriteStringArray(writer, (string[])_StoredValues[iter]);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
}
internal static ClientData Load(string username, bool useIsolatedStorage)
{
ClientData cd = null;
string fileName = null;
if (useIsolatedStorage) {
fileName = _IsolatedDir + "\\" + SqlHelper.GetPartialDBFileName(username, ".clientdata");
try {
using(IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly()) {
using(IsolatedStorageFileStream fs = new IsolatedStorageFileStream(fileName, FileMode.Open, f)) {
using (XmlReader xr = XmlReader.Create(fs)) {
cd = new ClientData(xr);
}
}
}
} catch {} // ignore exceptions
} else {
fileName = SqlHelper.GetFullDBFileName(username, ".clientdata");
try {
if (File.Exists(fileName)) {
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
using (XmlReader xr = XmlReader.Create(fs)) {
cd = new ClientData(xr);
}
}
}
} catch {} // ignore exceptions
}
if (cd == null)
cd = new ClientData();
cd.UsingIsolatedStorage = useIsolatedStorage;
cd.FileName = fileName;
return cd;
}
}
internal static class ClientDataManager
{
static private ClientData _applicationClientData;
static private ClientData _userClientData;
static private string _curUserName;
internal static ClientData GetAppClientData(bool useIsolatedStore)
{
if (_applicationClientData == null)
_applicationClientData = ClientData.Load(null, useIsolatedStore);
return _applicationClientData;
}
internal static ClientData GetUserClientData(string username, bool useIsolatedStore)
{
if (username != _curUserName) {
_curUserName = username;
_userClientData = ClientData.Load(username, useIsolatedStore);
}
return _userClientData;
}
internal static string GetCookie(string username, string cookieName, bool useIsolatedStore)
{
ClientData cd = GetUserClientData(username, useIsolatedStore);
if (cd.CookieNames == null) {
cd.CookieNames = new string[0];
cd.CookieValues = new string[0];
return null;
}
for(int iter=0; iter<cd.CookieNames.Length; iter++)
if (string.Compare(cookieName, cd.CookieNames[iter], StringComparison.OrdinalIgnoreCase) == 0)
return cd.CookieValues[iter];
return null;
}
internal static string StoreCookie(string username, string cookieName, string cookieValue, bool useIsolatedStore)
{
ClientData cd = GetUserClientData(username, useIsolatedStore);
if (cd.CookieNames == null) {
cd.CookieNames = new string[0];
cd.CookieValues = new string[0];
} else {
for(int iter=0; iter<cd.CookieNames.Length; iter++) {
if (cd.CookieValues[iter].StartsWith(cookieName + "=", StringComparison.OrdinalIgnoreCase)) {
if (cd.CookieValues[iter] != cookieName + "=" + cookieValue) {
cd.CookieValues[iter] = cookieName + "=" + cookieValue;
cd.Save();
}
return cd.CookieNames[iter];
}
}
}
string name = Guid.NewGuid().ToString("N");
string [] names = new string[cd.CookieNames.Length+1];
string [] vals = new string[cd.CookieNames.Length+1];
cd.CookieNames.CopyTo(names, 0);
cd.CookieValues.CopyTo(vals, 0);
names[cd.CookieNames.Length] = name;
vals[cd.CookieNames.Length] = cookieName + "=" + cookieValue;
cd.CookieNames = names;
cd.CookieValues = vals;
cd.Save();
return name;
}
internal static void DeleteAllCookies(string username, bool useIsolatedStore)
{
ClientData cd = GetUserClientData(username, useIsolatedStore);
cd.CookieNames = new string[0];
cd.CookieValues = new string[0];
}
}
}

View File

@@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <copyright file="ClientFormsAuthenticationCredentials.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices.Providers
{
using System;
using System.Diagnostics.CodeAnalysis;
public class ClientFormsAuthenticationCredentials
{
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId="username", Justification="consistent with Whidbey")]
public ClientFormsAuthenticationCredentials(string username, string password, bool rememberMe)
{
_UserName = username;
_Password = password;
_RememberMe = rememberMe;
}
public string UserName { get { return _UserName; } set { _UserName = value; } }
public string Password { get { return _Password; } set { _Password = value; } }
public bool RememberMe { get { return _RememberMe; } set { _RememberMe = value; } }
private string _UserName;
private string _Password;
private bool _RememberMe;
}
}

View File

@@ -0,0 +1,448 @@
//------------------------------------------------------------------------------
// <copyright file="ClientRoleProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices.Providers
{
using System;
using System.Web.Security;
using System.Threading;
using System.Security.Principal;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Net;
using System.Web.ClientServices;
using System.Web.Resources;
using System.Configuration;
using System.Globalization;
using System.Collections;
using System.Text;
using System.Runtime.InteropServices;
using System.Data.Common;
using System.Security;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Diagnostics.CodeAnalysis;
public class ClientRoleProvider : RoleProvider
{
private string _ConnectionString = null;
private string _ConnectionStringProvider = null;
private string _ServiceUri = null;
private string[] _Roles = null;
private string _CurrentUser = null;
private int _CacheTimeout = 1440; // 1 day in minutes
private DateTime _CacheExpiryDate = DateTime.UtcNow;
private bool _HonorCookieExpiry = false;
private bool _UsingFileSystemStore = false;
private bool _UsingIsolatedStore = false;
private bool _UsingWFCService = false;
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
base.Initialize(name, config);
ServiceUri = config["serviceUri"];
string temp = config["cacheTimeout"];
if (!string.IsNullOrEmpty(temp))
_CacheTimeout = int.Parse(temp, CultureInfo.InvariantCulture);
_ConnectionString = config["connectionStringName"];
if (string.IsNullOrEmpty(_ConnectionString)) {
_ConnectionString = SqlHelper.GetDefaultConnectionString();
} else {
if (ConfigurationManager.ConnectionStrings[_ConnectionString] != null) {
_ConnectionStringProvider = ConfigurationManager.ConnectionStrings[_ConnectionString].ProviderName;
_ConnectionString = ConfigurationManager.ConnectionStrings[_ConnectionString].ConnectionString;
}
}
switch(SqlHelper.IsSpecialConnectionString(_ConnectionString))
{
case 1:
_UsingFileSystemStore = true;
break;
case 2:
_UsingIsolatedStore = true;
break;
default:
break;
}
temp = config["honorCookieExpiry"];
if (!string.IsNullOrEmpty(temp))
_HonorCookieExpiry = (string.Compare(temp, "true", StringComparison.OrdinalIgnoreCase) == 0);
config.Remove("name");
config.Remove("description");
config.Remove("cacheTimeout");
config.Remove("connectionStringName");
config.Remove("serviceUri");
config.Remove("honorCookieExpiry");
foreach (string attribUnrecognized in config.Keys)
if (!String.IsNullOrEmpty(attribUnrecognized))
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, AtlasWeb.AttributeNotRecognized, attribUnrecognized));
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
public override bool IsUserInRole(string username, string roleName)
{
string[] roles = GetRolesForUser(username);
foreach (string role in roles)
if (string.Compare(role, roleName, StringComparison.OrdinalIgnoreCase) == 0)
return true;
return false;
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
public override string[] GetRolesForUser(string username)
{
lock (this) {
IPrincipal p = Thread.CurrentPrincipal;
if (p == null || p.Identity == null || !p.Identity.IsAuthenticated)
return new string[0];
if (!string.IsNullOrEmpty(username) && string.Compare(username, p.Identity.Name, StringComparison.OrdinalIgnoreCase) != 0)
throw new ArgumentException(AtlasWeb.ArgumentMustBeCurrentUser, "username");
// Serve from memory cache if it is for the last-user, and the roles are fresh
if (string.Compare(_CurrentUser, p.Identity.Name, StringComparison.OrdinalIgnoreCase) == 0 && DateTime.UtcNow < _CacheExpiryDate)
return _Roles;
// Fetch from database, cache it, and serve it
if (GetRolesFromDBForUser(p.Identity.Name)) // Return true, only if the roles are fresh. Also, sets _CurrentUser, _Roles and _CacheExpiryDate
return _Roles;
if (ConnectivityStatus.IsOffline)
return new string[0];
// Reset variables
_Roles = null;
_CacheExpiryDate = DateTime.UtcNow;
_CurrentUser = p.Identity.Name;
GetRolesForUserCore(p.Identity);
if (!_HonorCookieExpiry && _Roles.Length < 1 && (p.Identity is ClientFormsIdentity))
{
((ClientFormsIdentity)p.Identity).RevalidateUser();
GetRolesForUserCore(p.Identity);
}
StoreRolesForCurrentUser();
return _Roles;
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
public void ResetCache()
{
lock (this){
_Roles = null;
_CacheExpiryDate = DateTime.UtcNow;
RemoveRolesFromDB();
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// Private methods
[SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods", Justification="Reviewed and approved by feature crew")]
private void GetRolesForUserCore(IIdentity identity)
{
// (new PermissionSet(PermissionState.Unrestricted)).Assert(); //
CookieContainer cookies = null;
if (identity is ClientFormsIdentity)
cookies = ((ClientFormsIdentity)identity).AuthenticationCookies;
if (_UsingWFCService) {
throw new NotImplementedException();
// CustomBinding binding = ProxyHelper.GetBinding();
// ChannelFactory<RolesService> channelFactory = new ChannelFactory<RolesService>(binding, new EndpointAddress(GetServiceUri())); //(@"http://localhost/AuthSvc/service.svc"));
// RolesService clientService = channelFactory.CreateChannel();
// using (new OperationContextScope((IContextChannel)clientService)) {
// ProxyHelper.AddCookiesToWCF(cookies, GetServiceUri(), _CurrentUser, _ConnectionString, _ConnectionStringProvider);
// _Roles = clientService.GetRolesForCurrentUser();
// if (_Roles == null)
// _Roles = new string[0];
// ProxyHelper.GetCookiesFromWCF(cookies, GetServiceUri(), _CurrentUser, _ConnectionString, _ConnectionStringProvider);
// }
} else {
object o = ProxyHelper.CreateWebRequestAndGetResponse(GetServiceUri() + "/GetRolesForCurrentUser",
ref cookies,
identity.Name,
_ConnectionString,
_ConnectionStringProvider,
null,
null,
typeof(string []));
if (o != null)
_Roles = (string []) o;
else
_Roles = new string[0];
}
_CacheExpiryDate = DateTime.UtcNow.AddMinutes(_CacheTimeout);
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private void RemoveRolesFromDB()
{
// if (MustAssertForSql)
// (new PermissionSet(PermissionState.Unrestricted)).Assert();
if (string.IsNullOrEmpty(_CurrentUser))
return;
if (_UsingFileSystemStore || _UsingIsolatedStore) {
ClientData cd = ClientDataManager.GetUserClientData(_CurrentUser, _UsingIsolatedStore);
cd.Roles = null;
cd.Save();
return;
}
using (DbConnection conn = SqlHelper.GetConnection(_CurrentUser, _ConnectionString, _ConnectionStringProvider)) {
DbTransaction trans = null;
try {
trans = conn.BeginTransaction();
DbCommand cmd = conn.CreateCommand();
cmd.CommandText = "DELETE FROM Roles WHERE UserName = @UserName";
SqlHelper.AddParameter(conn, cmd, "@UserName", _CurrentUser);
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
cmd = conn.CreateCommand();
cmd.CommandText = "DELETE FROM UserProperties WHERE PropertyName = @RolesCachedDate";
SqlHelper.AddParameter(conn, cmd, "@RolesCachedDate", "RolesCachedDate_" + _CurrentUser);
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
} catch {
if (trans != null) {
trans.Rollback();
trans = null;
}
throw;
} finally {
if (trans != null)
trans.Commit();
}
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private void StoreRolesForCurrentUser()
{
if (_UsingFileSystemStore || _UsingIsolatedStore) {
ClientData cd = ClientDataManager.GetUserClientData(_CurrentUser, _UsingIsolatedStore);
cd.Roles = _Roles;
cd.RolesCachedDateUtc = DateTime.UtcNow;
cd.Save();
return;
}
// if (MustAssertForSql)
// (new PermissionSet(PermissionState.Unrestricted)).Assert();
RemoveRolesFromDB(); // Remove all old roles
DbTransaction trans = null;
using (DbConnection conn = SqlHelper.GetConnection(_CurrentUser, _ConnectionString, _ConnectionStringProvider)) {
try {
trans = conn.BeginTransaction();
// Add the roles
DbCommand cmd = null;
foreach(string role in _Roles) {
cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Roles(UserName, RoleName) VALUES(@UserName, @RoleName)";
SqlHelper.AddParameter(conn, cmd, "@UserName", _CurrentUser);
SqlHelper.AddParameter(conn, cmd, "@RoleName", role);
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
}
cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO UserProperties (PropertyName, PropertyValue) VALUES(@RolesCachedDate, @Date)";
SqlHelper.AddParameter(conn, cmd, "@RolesCachedDate", "RolesCachedDate_" + _CurrentUser);
SqlHelper.AddParameter(conn, cmd, "@Date", DateTime.UtcNow.ToFileTimeUtc().ToString(CultureInfo.InvariantCulture));
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
} catch {
if (trans != null) {
trans.Rollback();
trans = null;
}
throw;
} finally {
if (trans != null)
trans.Commit();
}
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private bool GetRolesFromDBForUser(string username)
{
_Roles = null;
_CacheExpiryDate = DateTime.UtcNow;
_CurrentUser = username;
// if (MustAssertForSql)
// (new PermissionSet(PermissionState.Unrestricted)).Assert();
if (_UsingFileSystemStore || _UsingIsolatedStore) {
ClientData cd = ClientDataManager.GetUserClientData(username, _UsingIsolatedStore);
if (cd.Roles == null)
return false;
_Roles = cd.Roles;
_CacheExpiryDate = cd.RolesCachedDateUtc.AddMinutes(_CacheTimeout);
if (!ConnectivityStatus.IsOffline && _CacheExpiryDate < DateTime.UtcNow) // expired roles
return false;
return true;
}
using (DbConnection conn = SqlHelper.GetConnection(_CurrentUser, _ConnectionString, _ConnectionStringProvider)) {
DbTransaction trans = null;
try {
trans = conn.BeginTransaction();
DbCommand cmd = conn.CreateCommand();
cmd.Transaction = trans;
cmd.CommandText = "SELECT PropertyValue FROM UserProperties WHERE PropertyName = @RolesCachedDate";
SqlHelper.AddParameter(conn, cmd, "@RolesCachedDate", "RolesCachedDate_" + _CurrentUser);
string date = cmd.ExecuteScalar() as string;
if (date == null) // not cached
return false;
long filetime = long.Parse(date, CultureInfo.InvariantCulture);
_CacheExpiryDate = DateTime.FromFileTimeUtc(filetime).AddMinutes(_CacheTimeout);
if (!ConnectivityStatus.IsOffline && _CacheExpiryDate < DateTime.UtcNow) // expired roles
return false;
cmd = conn.CreateCommand();
cmd.Transaction = trans;
cmd.CommandText = "SELECT RoleName FROM Roles WHERE UserName = @UserName ORDER BY RoleName";
SqlHelper.AddParameter(conn, cmd, "@UserName", _CurrentUser);
ArrayList al = new ArrayList();
using (DbDataReader reader = cmd.ExecuteReader()) {
while (reader.Read())
al.Add(reader.GetString(0));
}
_Roles = new string[al.Count];
for (int iter = 0; iter < al.Count; iter++)
_Roles[iter] = (string)al[iter];
return true;
} catch {
if (trans != null) {
trans.Rollback();
trans = null;
}
throw;
} finally {
if (trans != null)
trans.Commit();
}
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private string GetServiceUri()
{
if (string.IsNullOrEmpty(_ServiceUri))
throw new ArgumentException(AtlasWeb.ServiceUriNotFound);
return _ServiceUri;
}
[SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Reviewed and approved by feature crew")]
public string ServiceUri
{
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Reviewed and approved by feature crew")]
get {
return _ServiceUri;
}
[SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "Reviewed and approved by feature crew")]
set {
_ServiceUri = value;
if (string.IsNullOrEmpty(_ServiceUri)) {
_UsingWFCService = false;
} else {
_UsingWFCService = _ServiceUri.EndsWith(".svc", StringComparison.OrdinalIgnoreCase);
}
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// private bool _MustAssertForSqlDecided = false;
// private bool _MustAssertForSql = false;
// private bool MustAssertForSql {
// get {
// if (!_MustAssertForSqlDecided) {
// _MustAssertForSql = (_ConnectionString == "Data Source = |SQL\\CE|");
// _MustAssertForSqlDecided = true;
// }
// return _MustAssertForSql;
// }
// }
public override string ApplicationName { get { return ""; } set { } }
public override void CreateRole(string roleName)
{
throw new NotSupportedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotSupportedException();
}
public override bool RoleExists(string roleName)
{
throw new NotSupportedException();
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotSupportedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotSupportedException();
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotSupportedException();
}
public override string[] GetAllRoles()
{
throw new NotSupportedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotSupportedException();
}
}
}

View File

@@ -0,0 +1,139 @@
//------------------------------------------------------------------------------
// <copyright file="ClientWindowsAuthenticationMembershipProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices.Providers
{
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;
using System.Web;
using System.Web.Resources;
using System.Web.Security;
using System.Threading;
using System.Security;
using System.Security.Principal;
using System.Collections.Specialized;
using System.Web.ClientServices;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
public class ClientWindowsAuthenticationMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
if (!string.IsNullOrEmpty(password))
throw new ArgumentException(AtlasWeb.ArgumentMustBeNull, "password");
if (!string.IsNullOrEmpty(username) && string.Compare(username, id.Name, StringComparison.OrdinalIgnoreCase) != 0)
throw new ArgumentException(AtlasWeb.ArgumentMustBeNull, "username");
Thread.CurrentPrincipal = new ClientRolePrincipal(id);
return true;
}
public void Logout()
{
Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
}
public override bool EnablePasswordRetrieval { get { return false; } }
public override bool EnablePasswordReset { get { return false; } }
public override bool RequiresQuestionAndAnswer { get { return false; } }
public override string ApplicationName { get { return ""; } set { } }
public override int MaxInvalidPasswordAttempts { get { return int.MaxValue; } }
public override int PasswordAttemptWindow { get { return int.MaxValue; } }
public override bool RequiresUniqueEmail { get { return false; } }
public override MembershipPasswordFormat PasswordFormat { get { return MembershipPasswordFormat.Hashed; } }
public override int MinRequiredPasswordLength { get { return 1; } }
public override int MinRequiredNonAlphanumericCharacters { get { return 0; } }
public override string PasswordStrengthRegularExpression { get { return "*"; } }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer,
bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
throw new NotSupportedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotSupportedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotSupportedException();
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotSupportedException();
}
public override string ResetPassword(string username, string answer)
{
throw new NotSupportedException();
}
public override void UpdateUser(MembershipUser user)
{
throw new NotSupportedException();
}
public override bool UnlockUser(string username)
{
throw new NotSupportedException();
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotSupportedException();
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new NotSupportedException();
}
public override string GetUserNameByEmail(string email)
{
throw new NotSupportedException();
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotSupportedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotSupportedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotSupportedException();
}
}
}

Some files were not shown because too many files have changed in this diff Show More