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

View File

@@ -0,0 +1,15 @@
//------------------------------------------------------------------------------
// <copyright file="IClientFormsAuthenticationCredentialsProvider.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices.Providers
{
using System;
using System.Diagnostics.CodeAnalysis;
public interface IClientFormsAuthenticationCredentialsProvider
{
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Reviewed and approved by feature crew")]
ClientFormsAuthenticationCredentials GetCredentials();
}
}

View File

@@ -0,0 +1,27 @@
//------------------------------------------------------------------------------
// <copyright file="SettingsSavedEventArgs.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.ClientServices.Providers {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
public class SettingsSavedEventArgs : EventArgs {
private ReadOnlyCollection<string> _failedSettingsList;
public SettingsSavedEventArgs(IEnumerable<string> failedSettingsList) {
List<string> list =
(failedSettingsList == null) ? new List<string>() : new List<string>(failedSettingsList);
_failedSettingsList = new ReadOnlyCollection<string>(list);
}
public ReadOnlyCollection<string> FailedSettingsList {
get {
return _failedSettingsList;
}
}
}
}

View File

@@ -0,0 +1,314 @@
//------------------------------------------------------------------------------
// <copyright file="SqlHelper.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.Reflection;
using System.Diagnostics.CodeAnalysis;
using System.Web.Resources;
internal static class SqlHelper
{
private const string _SQL_CE_Tag = "|SQL/CE|";
private const string _SQL_FILES_Tag = "|FILES|";
private const string _SQL_CE_CONN_STRING = "Data Source = |SQL/CE|";
private const string _Isolated_Storage_Tag = "|Isolated_Storage|";
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static string GetDefaultConnectionString()
{
return _SQL_FILES_Tag;
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static int IsSpecialConnectionString(string connectionString) {
if (string.IsNullOrEmpty(connectionString))
return 1; // Default to FILES
if (string.Compare(connectionString, _SQL_FILES_Tag, StringComparison.OrdinalIgnoreCase) == 0)
return 1;
// if (string.Compare(connectionString, _Isolated_Storage_Tag, StringComparison.OrdinalIgnoreCase) == 0)
// return 2; -- disable isolated storage
return 3;
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static DbConnection GetConnection(string username, string connectionString, string sqlProvider)
{
if (connectionString.Contains(_SQL_CE_Tag) || (sqlProvider != null && sqlProvider.Contains(".SqlServerCe"))) {
try {
return GetSqlCeConnection(username, connectionString);
} catch (TypeLoadException e) {
throw new ArgumentException(AtlasWeb.SqlHelper_SqlEverywhereNotInstalled, e);
}
}
DbConnection connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static void AddParameter(DbConnection conn, DbCommand cmd, string paramName, object paramValue)
{
if (!(conn is SqlConnection))
AddSqlCeParameter(cmd, paramName, paramValue);
else
cmd.Parameters.Add(new SqlParameter(paramName, paramValue));
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static string GetCookieFromDB(string name, string username, string connectionString, string sqlProvider)
{
if (connectionString == _SQL_FILES_Tag)
return ClientDataManager.GetCookie(username, name, false);
if (connectionString == _Isolated_Storage_Tag)
return ClientDataManager.GetCookie(username, name, true);
using (DbConnection connection = GetConnection(username, connectionString, sqlProvider)) {
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT PropertyValue FROM UserProperties WHERE PropertyName = @PropName";
AddParameter(connection, cmd, "@PropName", "CookieName_" + name);
return (cmd.ExecuteScalar() as string);
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static string StoreCookieInDB(string cookieName, string cookieValue, string username, string connectionString, string sqlProvider)
{
if (connectionString == _SQL_FILES_Tag)
return ClientDataManager.StoreCookie(username, cookieName, cookieValue, false);
if (connectionString == _Isolated_Storage_Tag)
return ClientDataManager.StoreCookie(username, cookieName, cookieValue, true);
string name = Guid.NewGuid().ToString("N");
using (DbConnection connection = GetConnection(username, connectionString, sqlProvider)) {
DbTransaction trans = null;
try {
trans = connection.BeginTransaction();
DbCommand cmd = connection.CreateCommand();
// delete old cookie
cmd.CommandText = "DELETE FROM UserProperties WHERE PropertyName LIKE N'CookieName_%' AND PropertyValue LIKE @PropValue";
cmd.Transaction = trans;
AddParameter(connection, cmd, "@PropValue", cookieName + "=%");
cmd.ExecuteNonQuery();
if (!string.IsNullOrEmpty(cookieValue)) {
cmd = connection.CreateCommand();
cmd.Transaction = trans;
cmd.CommandText = "INSERT INTO UserProperties (PropertyName, PropertyValue) VALUES (@PropName, @PropValue)";
AddParameter(connection, cmd, "@PropName", "CookieName_" + name);
AddParameter(connection, cmd, "@PropValue", cookieName + "=" + cookieValue);
cmd.ExecuteNonQuery();
return name;
}
return cookieName;
} catch {
if (trans != null) {
trans.Rollback();
trans = null;
}
throw;
} finally {
if (trans != null)
trans.Commit();
}
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static void DeleteAllCookies(string username, string connectionString, string sqlProvider)
{
if (connectionString == _SQL_FILES_Tag || connectionString == _Isolated_Storage_Tag) {
ClientDataManager.DeleteAllCookies(username, connectionString == _Isolated_Storage_Tag);
return;
}
using (DbConnection connection = GetConnection(username, connectionString, sqlProvider)) {
DbTransaction trans = null;
try {
trans = connection.BeginTransaction();
DbCommand cmd = connection.CreateCommand();
cmd.CommandText = "DELETE FROM UserProperties WHERE PropertyName LIKE N'CookieName_%'";
cmd.Transaction = trans;
cmd.ExecuteNonQuery();
} catch {
if (trans != null) {
trans.Rollback();
trans = null;
}
throw;
} finally {
if (trans != null)
trans.Commit();
}
}
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private static Type _SqlCeConnectionType = null;
private static Type _SqlCeParamType = null;
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private static DbConnection GetSqlCeConnection(string username, string connectionString)
{
DbConnection conn = CreateDBIfRequired(username, connectionString);
if (conn == null)
conn = CreateNewSqlCeConnection(connectionString, true); //new SqlCeConnection(connectionString);
return conn;
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
// [PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private static DbConnection CreateDBIfRequired(string username, string connectionString) {
if (!connectionString.Contains(_SQL_CE_Tag))
return null;
DbConnection conn = null;
try {
conn = CreateNewSqlCeConnection(connectionString, false);
if (string.Compare(conn.Database.Trim(), _SQL_CE_Tag, StringComparison.OrdinalIgnoreCase) != 0) {
conn.Open();
return conn;
}
conn.Dispose();
conn = null;
} catch (TypeLoadException e) {
throw new ArgumentException(AtlasWeb.SqlHelper_SqlEverywhereNotInstalled, e);
}
string fileName = GetFullDBFileName(username, "_DB.spf");
bool needToCreateDB = (File.Exists(fileName) == false);
connectionString = connectionString.Replace(_SQL_CE_Tag, fileName);
if (needToCreateDB) {
using (IDisposable engine = (IDisposable)Activator.CreateInstance(GetSqlCeType("SqlCeEngine"), new object[] { connectionString })) {
engine.GetType().InvokeMember("CreateDatabase", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
null, engine, null, CultureInfo.InvariantCulture);
}
using (conn = CreateNewSqlCeConnection(connectionString, true)) {
DbCommand cmd = conn.CreateCommand();
if (username == null) {
cmd.CommandText = "CREATE TABLE ApplicationProperties (PropertyName nvarchar(256), PropertyValue nvarchar(256))";
cmd.ExecuteNonQuery();
} else {
cmd.CommandText = "CREATE TABLE UserProperties (PropertyName nvarchar(256), PropertyValue nvarchar(256))";
cmd.ExecuteNonQuery();
cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE Roles (UserName nvarchar(256), RoleName nvarchar(256))";
cmd.ExecuteNonQuery();
cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE Settings (PropertyName nvarchar(256), PropertyStoredAs nvarchar(1), PropertyValue nvarchar(2048))";
cmd.ExecuteNonQuery();
}
}
}
return CreateNewSqlCeConnection(connectionString, true);
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private static Type GetSqlCeType(string typeName)
{
// Try versionless
Type t = Type.GetType("System.Data.SqlServerCe." + typeName + ", System.Data.SqlServerCe",
false, true);
if (t != null)
return t;
// Try version 3.5
t = Type.GetType("System.Data.SqlServerCe." + typeName +
", System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91",
false, true);
if (t != null)
return t;
// Try version 3.0
t = Type.GetType("System.Data.SqlServerCe." + typeName +
", System.Data.SqlServerCe, Version=3.0.3600.0, Culture=neutral, PublicKeyToken=3be235df1c8d2ad3",
false, true);
if (t != null)
return t;
// Call 3.5 again to throw error
return Type.GetType("System.Data.SqlServerCe." + typeName +
", System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91",
true, true);
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private static DbConnection CreateNewSqlCeConnection(string connectionString, bool openConn)
{
if (_SqlCeConnectionType == null)
_SqlCeConnectionType = GetSqlCeType("SqlCeConnection");
DbConnection conn = (DbConnection) Activator.CreateInstance(_SqlCeConnectionType, new object[] {connectionString});
if (openConn)
conn.Open();
return conn;
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
private static void AddSqlCeParameter(DbCommand cmd, string paramName, object paramValue)
{
if (_SqlCeParamType == null)
_SqlCeParamType = GetSqlCeType("SqlCeParameter");
cmd.Parameters.Add((DbParameter) Activator.CreateInstance(_SqlCeParamType, new object[]{paramName, paramValue}));
}
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
internal static string GetFullDBFileName(string username, string extension)
{
return Path.Combine(Application.UserAppDataPath, GetPartialDBFileName(username, extension));
}
internal static string GetPartialDBFileName(string username, string extension)
{
if (string.IsNullOrEmpty(username)) {
return "Application" + extension;
}
char[] usernameChars = username.ToCharArray();
for (int iter = 0; iter < usernameChars.Length; iter++)
if (!char.IsLetterOrDigit(usernameChars[iter]))
usernameChars[iter] = '_';
return "User_" + new string(usernameChars) + extension;
}
}
}

View File

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