diff options
author | Andrew Arnott <andrewarnott@gmail.com> | 2013-03-26 11:19:06 -0700 |
---|---|---|
committer | Andrew Arnott <andrewarnott@gmail.com> | 2013-03-26 11:19:06 -0700 |
commit | 3d37ff45cab6838d80b22e6b782a0b9b4c2f4aeb (patch) | |
tree | c15816c3d7f6e74334553f2ff98605ce1c22c538 | |
parent | 5e9014f36b2d53b8e419918675df636540ea24e2 (diff) | |
parent | e6f7409f4caceb7bc2a5b4ddbcb1a4097af340f2 (diff) | |
download | DotNetOpenAuth-3d37ff45cab6838d80b22e6b782a0b9b4c2f4aeb.zip DotNetOpenAuth-3d37ff45cab6838d80b22e6b782a0b9b4c2f4aeb.tar.gz DotNetOpenAuth-3d37ff45cab6838d80b22e6b782a0b9b4c2f4aeb.tar.bz2 |
Move to HttpClient throughout library.
588 files changed, 44777 insertions, 12696 deletions
diff --git a/nuget/DotNetOpenAuth.OAuth.ServiceProvider.nuspec b/nuget/DotNetOpenAuth.OAuth.ServiceProvider.nuspec index 57b8beb..ac0b355 100644 --- a/nuget/DotNetOpenAuth.OAuth.ServiceProvider.nuspec +++ b/nuget/DotNetOpenAuth.OAuth.ServiceProvider.nuspec @@ -17,7 +17,6 @@ </description> <dependencies> <dependency id="DotNetOpenAuth.OAuth.Core" version="[$version$]" /> - <dependency id="DotNetOpenAuth.OAuth.Common" version="[$version$]" /> </dependencies> </metadata> <files> diff --git a/nuget/DotNetOpenAuth.OAuth.nuspec b/nuget/DotNetOpenAuth.OAuth.nuspec index b8e2fd7..d673d73 100644 --- a/nuget/DotNetOpenAuth.OAuth.nuspec +++ b/nuget/DotNetOpenAuth.OAuth.nuspec @@ -14,6 +14,7 @@ <description>This package contains shared code for other NuGet packages, and contains no public API in and of itself.</description> <dependencies> <dependency id="DotNetOpenAuth.Core" version="[$version$]" /> + <dependency id="DotNetOpenAuth.OAuth.Common" version="[$version$]" /> </dependencies> </metadata> <files> diff --git a/nuget/DotNetOpenAuth.OAuth2.ResourceServer.nuspec b/nuget/DotNetOpenAuth.OAuth2.ResourceServer.nuspec index e7a0942..6d1a8bc 100644 --- a/nuget/DotNetOpenAuth.OAuth2.ResourceServer.nuspec +++ b/nuget/DotNetOpenAuth.OAuth2.ResourceServer.nuspec @@ -18,7 +18,6 @@ </description> <dependencies> <dependency id="DotNetOpenAuth.OAuth2.Core" version="[$oauth2version$]" /> - <dependency id="DotNetOpenAuth.OAuth.Common" version="[$version$]" /> </dependencies> </metadata> <files> diff --git a/nuget/DotNetOpenAuth.OAuth2.nuspec b/nuget/DotNetOpenAuth.OAuth2.nuspec index 6726fcb..4969f7f 100644 --- a/nuget/DotNetOpenAuth.OAuth2.nuspec +++ b/nuget/DotNetOpenAuth.OAuth2.nuspec @@ -14,6 +14,7 @@ <description>This package contains shared code for other NuGet packages, and contains no public API in and of itself.</description> <dependencies> <dependency id="DotNetOpenAuth.Core" version="[$version$]" /> + <dependency id="DotNetOpenAuth.OAuth.Common" version="[$version$]" /> </dependencies> </metadata> <files> diff --git a/projecttemplates/MvcRelyingParty/Code/Extensions.cs b/projecttemplates/MvcRelyingParty/Code/Extensions.cs index 4af5413..09437b0 100644 --- a/projecttemplates/MvcRelyingParty/Code/Extensions.cs +++ b/projecttemplates/MvcRelyingParty/Code/Extensions.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; @@ -13,5 +15,32 @@ internal static Uri ActionFull(this UrlHelper urlHelper, string actionName, string controllerName) { return new Uri(HttpContext.Current.Request.Url, urlHelper.Action(actionName, controllerName)); } + + internal static Task ToApm(this Task task, AsyncCallback callback, object state) { + if (task == null) { + throw new ArgumentNullException("task"); + } + + var tcs = new TaskCompletionSource<object>(state); + task.ContinueWith( + t => { + if (t.IsFaulted) { + tcs.TrySetException(t.Exception.InnerExceptions); + } else if (t.IsCanceled) { + tcs.TrySetCanceled(); + } else { + tcs.TrySetResult(null); + } + + if (callback != null) { + callback(tcs.Task); + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + + return tcs.Task; + } } } diff --git a/projecttemplates/MvcRelyingParty/Code/OpenIdRelyingPartyService.cs b/projecttemplates/MvcRelyingParty/Code/OpenIdRelyingPartyService.cs index 30f3fae..0506286 100644 --- a/projecttemplates/MvcRelyingParty/Code/OpenIdRelyingPartyService.cs +++ b/projecttemplates/MvcRelyingParty/Code/OpenIdRelyingPartyService.cs @@ -2,29 +2,30 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; + using Validation; public interface IOpenIdRelyingParty { Channel Channel { get; } - IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy); + Task<IAuthenticationRequest> CreateRequestAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)); - IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy); + Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)); - ActionResult AjaxDiscovery(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy); + Task<ActionResult> AjaxDiscoveryAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)); - string PreloadDiscoveryResults(Realm realm, Uri returnTo, Uri privacyPolicy, params Identifier[] identifiers); + Task<string> PreloadDiscoveryResultsAsync(Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken), params Identifier[] identifiers); - ActionResult ProcessAjaxOpenIdResponse(); + Task<ActionResult> ProcessAjaxOpenIdResponseAsync(HttpRequestBase request, CancellationToken cancellationToken = default(CancellationToken)); - IAuthenticationResponse GetResponse(); - - IAuthenticationResponse GetResponse(HttpRequestBase request); + Task<IAuthenticationResponse> GetResponseAsync(HttpRequestBase request, CancellationToken cancellationToken = default(CancellationToken)); } /// <summary> @@ -52,22 +53,16 @@ get { return relyingParty.Channel; } } - public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy) { - return this.CreateRequests(userSuppliedIdentifier, realm, returnTo, privacyPolicy).First(); + public async Task<IAuthenticationRequest> CreateRequestAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)) { + return (await this.CreateRequestsAsync(userSuppliedIdentifier, realm, returnTo, privacyPolicy, cancellationToken)).First(); } - public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy) { - if (userSuppliedIdentifier == null) { - throw new ArgumentNullException("userSuppliedIdentifier"); - } - if (realm == null) { - throw new ArgumentNullException("realm"); - } - if (returnTo == null) { - throw new ArgumentNullException("returnTo"); - } + public async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.NotNull(realm, "realm"); + Requires.NotNull(returnTo, "returnTo"); - var requests = relyingParty.CreateRequests(userSuppliedIdentifier, realm, returnTo); + var requests = (await relyingParty.CreateRequestsAsync(userSuppliedIdentifier, realm, returnTo, cancellationToken)).ToList(); foreach (IAuthenticationRequest request in requests) { // Ask for the user's email, not because we necessarily need it to do our work, @@ -78,31 +73,33 @@ FullName = DemandLevel.Request, PolicyUrl = privacyPolicy, }); - - yield return request; } - } - public ActionResult AjaxDiscovery(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy) { - return relyingParty.AsAjaxDiscoveryResult( - this.CreateRequests(userSuppliedIdentifier, realm, returnTo, privacyPolicy)).AsActionResult(); + return requests; } - public string PreloadDiscoveryResults(Realm realm, Uri returnTo, Uri privacyPolicy, params Identifier[] identifiers) { - return relyingParty.AsAjaxPreloadedDiscoveryResult( - identifiers.SelectMany(id => this.CreateRequests(id, realm, returnTo, privacyPolicy))); + public async Task<ActionResult> AjaxDiscoveryAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)) { + return (await relyingParty.AsAjaxDiscoveryResultAsync( + await this.CreateRequestsAsync(userSuppliedIdentifier, realm, returnTo, privacyPolicy, cancellationToken), + cancellationToken)).AsActionResult(); } - public ActionResult ProcessAjaxOpenIdResponse() { - return relyingParty.ProcessResponseFromPopup().AsActionResult(); + public async Task<string> PreloadDiscoveryResultsAsync(Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken), params Identifier[] identifiers) { + var results = new List<IAuthenticationRequest>(); + foreach (var id in identifiers) { + var discoveryResult = await this.CreateRequestsAsync(id, realm, returnTo, privacyPolicy, cancellationToken); + results.AddRange(discoveryResult); + } + + return await relyingParty.AsAjaxPreloadedDiscoveryResultAsync(results, cancellationToken); } - public IAuthenticationResponse GetResponse() { - return relyingParty.GetResponse(); + public async Task<ActionResult> ProcessAjaxOpenIdResponseAsync(HttpRequestBase request, CancellationToken cancellationToken = default(CancellationToken)) { + return (await relyingParty.ProcessResponseFromPopupAsync(request, cancellationToken)).AsActionResult(); } - public IAuthenticationResponse GetResponse(HttpRequestBase request) { - return relyingParty.GetResponse(request); + public Task<IAuthenticationResponse> GetResponseAsync(HttpRequestBase request, CancellationToken cancellationToken = default(CancellationToken)) { + return relyingParty.GetResponseAsync(request, cancellationToken); } #endregion diff --git a/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs b/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs index 4ce8592..bf45838 100644 --- a/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs +++ b/projecttemplates/MvcRelyingParty/Controllers/AccountController.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Net; using System.Security.Principal; + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Security; @@ -50,8 +51,8 @@ [Authorize, AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)] [HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking - public ActionResult Authorize() { - var pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest(); + public async Task<ActionResult> Authorize() { + var pendingRequest = await OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken); if (pendingRequest == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request."); } @@ -61,7 +62,8 @@ // Consider auto-approving if safe to do so. if (((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest)) { var approval = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name); - return OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponse(approval).AsActionResult(); + var response = await OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(approval, Response.ClientDisconnectedToken); + return response.AsActionResult(); } var model = new AccountAuthorizeModel { @@ -74,8 +76,8 @@ } [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] - public ActionResult AuthorizeResponse(bool isApproved) { - var pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest(); + public async Task<ActionResult> AuthorizeResponse(bool isApproved) { + var pendingRequest = await OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken); if (pendingRequest == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request."); } @@ -95,7 +97,8 @@ response = OAuthServiceProvider.AuthorizationServer.PrepareRejectAuthorizationRequest(pendingRequest); } - return OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponse(response).AsActionResult(); + var responseMessage = await OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken); + return responseMessage.AsActionResult(); } [Authorize, AcceptVerbs(HttpVerbs.Delete)] // ValidateAntiForgeryToken would be GREAT here, but it's not a FORM POST operation so that doesn't work. diff --git a/projecttemplates/MvcRelyingParty/Controllers/AuthController.cs b/projecttemplates/MvcRelyingParty/Controllers/AuthController.cs index 9c87147..926c254 100644 --- a/projecttemplates/MvcRelyingParty/Controllers/AuthController.cs +++ b/projecttemplates/MvcRelyingParty/Controllers/AuthController.cs @@ -9,6 +9,7 @@ namespace MvcRelyingParty.Controllers { using System.Collections.Generic; using System.Linq; using System.Net; + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using DotNetOpenAuth.Messaging; @@ -63,24 +64,25 @@ namespace MvcRelyingParty.Controllers { /// </summary> /// <param name="identifier">The identifier on which to perform discovery.</param> /// <returns>The JSON result of discovery.</returns> - public ActionResult Discover(string identifier) { + public Task<ActionResult> Discover(string identifier) { if (!this.Request.IsAjaxRequest()) { throw new InvalidOperationException(); } - return this.RelyingParty.AjaxDiscovery( + return this.RelyingParty.AjaxDiscoveryAsync( identifier, Realm.AutoDetect, Url.ActionFull("PopUpReturnTo"), - this.PrivacyPolicyUrl); + this.PrivacyPolicyUrl, + Response.ClientDisconnectedToken); } /// <summary> /// Prepares a web page to help the user supply his login information. /// </summary> /// <returns>The action result.</returns> - public ActionResult LogOn() { - this.PreloadDiscoveryResults(); + public async Task<ActionResult> LogOn() { + await this.PreloadDiscoveryResultsAsync(); return View(); } @@ -88,8 +90,8 @@ namespace MvcRelyingParty.Controllers { /// Prepares a web page to help the user supply his login information. /// </summary> /// <returns>The action result.</returns> - public ActionResult LogOnPopUp() { - this.PreloadDiscoveryResults(); + public async Task<ActionResult> LogOnPopUp() { + await this.PreloadDiscoveryResultsAsync(); return View(); } @@ -103,8 +105,8 @@ namespace MvcRelyingParty.Controllers { /// hack attempts and result in errors when validation is turned on. /// </remarks> [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post), ValidateInput(false)] - public ActionResult PopUpReturnTo() { - return this.RelyingParty.ProcessAjaxOpenIdResponse(); + public Task<ActionResult> PopUpReturnTo() { + return this.RelyingParty.ProcessAjaxOpenIdResponseAsync(this.Request, this.Response.ClientDisconnectedToken); } /// <summary> @@ -118,15 +120,15 @@ namespace MvcRelyingParty.Controllers { /// hack attempts and result in errors when validation is turned on. /// </remarks> [AcceptVerbs(HttpVerbs.Post), ValidateInput(false)] - public ActionResult LogOnPostAssertion(string openid_openidAuthData) { + public async Task<ActionResult> LogOnPostAssertion(string openid_openidAuthData) { IAuthenticationResponse response; if (!string.IsNullOrEmpty(openid_openidAuthData)) { // Always say it's a GET since the payload is all in the URL, even the large ones. var auth = new Uri(openid_openidAuthData); HttpRequestBase clientResponseInfo = HttpRequestInfo.Create("GET", auth, headers: Request.Headers); - response = this.RelyingParty.GetResponse(clientResponseInfo); + response = await this.RelyingParty.GetResponseAsync(clientResponseInfo, Response.ClientDisconnectedToken); } else { - response = this.RelyingParty.GetResponse(); + response = await this.RelyingParty.GetResponseAsync(Request, Response.ClientDisconnectedToken); } if (response != null) { switch (response.Status) { @@ -155,7 +157,7 @@ namespace MvcRelyingParty.Controllers { } [Authorize, AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken, ValidateInput(false)] - public ActionResult AddAuthenticationToken(string openid_openidAuthData) { + public async Task<ActionResult> AddAuthenticationToken(string openid_openidAuthData) { IAuthenticationResponse response; if (!string.IsNullOrEmpty(openid_openidAuthData)) { var auth = new Uri(openid_openidAuthData); @@ -166,9 +168,9 @@ namespace MvcRelyingParty.Controllers { // Always say it's a GET since the payload is all in the URL, even the large ones. HttpRequestBase clientResponseInfo = HttpRequestInfo.Create("GET", auth, headers: headers); - response = this.RelyingParty.GetResponse(clientResponseInfo); + response = await this.RelyingParty.GetResponseAsync(clientResponseInfo, Response.ClientDisconnectedToken); } else { - response = this.RelyingParty.GetResponse(); + response = await this.RelyingParty.GetResponseAsync(Request, Response.ClientDisconnectedToken); } if (response != null) { switch (response.Status) { @@ -208,11 +210,15 @@ namespace MvcRelyingParty.Controllers { /// <summary> /// Preloads discovery results for the OP buttons we display on the selector in the ViewData. /// </summary> - private void PreloadDiscoveryResults() { - this.ViewData["PreloadedDiscoveryResults"] = this.RelyingParty.PreloadDiscoveryResults( + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + private async Task PreloadDiscoveryResultsAsync() { + this.ViewData["PreloadedDiscoveryResults"] = this.RelyingParty.PreloadDiscoveryResultsAsync( Realm.AutoDetect, Url.ActionFull("PopUpReturnTo"), this.PrivacyPolicyUrl, + Response.ClientDisconnectedToken, "https://me.yahoo.com/", "https://www.google.com/accounts/o8/id"); } diff --git a/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj b/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj index 6f6db1e..703f1c7 100644 --- a/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj +++ b/projecttemplates/MvcRelyingParty/MvcRelyingParty.csproj @@ -56,6 +56,8 @@ <Reference Include="System.Data.Entity"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web.ApplicationServices" /> <Reference Include="System.Web.DynamicData" /> <Reference Include="System.Web.Entity" /> @@ -71,6 +73,10 @@ <Reference Include="System.EnterpriseServices" /> <Reference Include="System.Web.Mobile" /> <Reference Include="System.Xml.Linq" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\src\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> + </Reference> </ItemGroup> <ItemGroup> <Compile Include="Code\Extensions.cs" /> @@ -170,6 +176,10 @@ <Content Include="Views\Web.config" /> </ItemGroup> <ItemGroup> + <ProjectReference Include="..\..\samples\DotNetOpenAuth.ApplicationBlock\DotNetOpenAuth.ApplicationBlock.csproj"> + <Project>{aa78d112-d889-414b-a7d4-467b34c7b663}</Project> + <Name>DotNetOpenAuth.ApplicationBlock</Name> + </ProjectReference> <ProjectReference Include="..\..\src\DotNetOpenAuth.InfoCard.UI\DotNetOpenAuth.InfoCard.UI.csproj"> <Project>{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}</Project> <Name>DotNetOpenAuth.InfoCard.UI</Name> diff --git a/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs b/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs index 72c37a5..190c1f8 100644 --- a/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs +++ b/projecttemplates/MvcRelyingParty/OAuthTokenEndpoint.ashx.cs @@ -8,8 +8,11 @@ namespace MvcRelyingParty { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; + using System.Threading.Tasks; using System.Web; using System.Web.SessionState; + using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using RelyingPartyLogic; @@ -17,7 +20,7 @@ namespace MvcRelyingParty { /// <summary> /// An OAuth 2.0 token endpoint. /// </summary> - public class OAuthTokenEndpoint : IHttpHandler, IRequiresSessionState { + public class OAuthTokenEndpoint : HttpAsyncHandlerBase, IRequiresSessionState { /// <summary> /// Initializes a new instance of the <see cref="OAuthTokenEndpoint"/> class. /// </summary> @@ -30,17 +33,14 @@ namespace MvcRelyingParty { /// <returns> /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false. /// </returns> - public bool IsReusable { + public override bool IsReusable { get { return true; } } - /// <summary> - /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface. - /// </summary> - /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> - public void ProcessRequest(HttpContext context) { + protected override async Task ProcessRequestAsync(HttpContext context) { var serviceProvider = OAuthServiceProvider.AuthorizationServer; - serviceProvider.HandleTokenRequest().Respond(); + var response = await serviceProvider.HandleTokenRequestAsync(new HttpRequestWrapper(context.Request), context.Response.ClientDisconnectedToken); + await response.SendAsync(new HttpContextWrapper(context), context.Response.ClientDisconnectedToken); } } } diff --git a/projecttemplates/MvcRelyingParty/Web.config b/projecttemplates/MvcRelyingParty/Web.config index d59d8fb..5b00f66 100644 --- a/projecttemplates/MvcRelyingParty/Web.config +++ b/projecttemplates/MvcRelyingParty/Web.config @@ -133,12 +133,15 @@ <level value="INFO"/> </logger> </log4net> - <appSettings/> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> <connectionStrings> <!-- Remember to keep this connection string in sync with the one (if any) that appears in the log4net section. --> <add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MvcRelyingParty.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/> </connectionStrings> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this @@ -148,7 +151,6 @@ <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> - <remove assembly="DotNetOpenAuth.Contracts"/> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> diff --git a/projecttemplates/MvcRelyingParty/packages.config b/projecttemplates/MvcRelyingParty/packages.config index 6562527..2f4e283 100644 --- a/projecttemplates/MvcRelyingParty/packages.config +++ b/projecttemplates/MvcRelyingParty/packages.config @@ -1,4 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs b/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs index 0e2618c..3d37e1f 100644 --- a/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthAuthenticationModule.cs @@ -8,7 +8,10 @@ namespace RelyingPartyLogic { using System; using System.Collections.Generic; using System.Linq; + using System.Security.Claims; using System.Security.Principal; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Security; using DotNetOpenAuth.Messaging; @@ -52,13 +55,21 @@ namespace RelyingPartyLogic { using (var crypto = OAuthResourceServer.CreateRSA()) { var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); var resourceServer = new ResourceServer(tokenAnalyzer); + var context = this.application.Context; + Task.Run( + async delegate { + ProtocolFaultResponseException exception = null; + try { + IPrincipal principal = await resourceServer.GetPrincipalAsync(new HttpRequestWrapper(context.Request)); + context.User = principal; + return; + } catch (ProtocolFaultResponseException ex) { + exception = ex; + } - try { - IPrincipal principal = resourceServer.GetPrincipal(new HttpRequestWrapper(this.application.Context.Request)); - this.application.Context.User = principal; - } catch (ProtocolFaultResponseException ex) { - ex.CreateErrorResponse().Send(); - } + var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None); + await errorResponse.SendAsync(); + }).Wait(); } } @@ -74,7 +85,7 @@ namespace RelyingPartyLogic { /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Web.Security.RoleManagerEventArgs"/> instance containing the event data.</param> private void roleManager_GetRoles(object sender, RoleManagerEventArgs e) { - if (this.application.User is DotNetOpenAuth.OAuth.ChannelElements.OAuthPrincipal) { + if (this.application.User is ClaimsPrincipal) { e.RolesPopulated = true; } } diff --git a/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs index 6daf56e..f40cf36 100644 --- a/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs +++ b/projecttemplates/RelyingPartyLogic/OAuthAuthorizationManager.cs @@ -13,6 +13,8 @@ namespace RelyingPartyLogic { using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; @@ -33,40 +35,43 @@ namespace RelyingPartyLogic { var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via; - using (var crypto = OAuthResourceServer.CreateRSA()) { - var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); - var resourceServer = new ResourceServer(tokenAnalyzer); + return Task.Run( + async delegate { + using (var crypto = OAuthResourceServer.CreateRSA()) { + var tokenAnalyzer = new SpecialAccessTokenAnalyzer(crypto, crypto); + var resourceServer = new ResourceServer(tokenAnalyzer); + ProtocolFaultResponseException exception = null; + try { + IPrincipal principal = + await resourceServer.GetPrincipalAsync(httpDetails, requestUri, CancellationToken.None, operationContext.IncomingMessageHeaders.Action); + var policy = new OAuthPrincipalAuthorizationPolicy(principal); + var policies = new List<IAuthorizationPolicy> { policy, }; - try { - IPrincipal principal = resourceServer.GetPrincipal(httpDetails, requestUri, operationContext.IncomingMessageHeaders.Action); - var policy = new OAuthPrincipalAuthorizationPolicy(principal); - var policies = new List<IAuthorizationPolicy> { - policy, - }; + var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); + if (operationContext.IncomingMessageProperties.Security != null) { + operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; + } else { + operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { + ServiceSecurityContext = securityContext, + }; + } - var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); - if (operationContext.IncomingMessageProperties.Security != null) { - operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; - } else { - operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { - ServiceSecurityContext = securityContext, - }; - } + securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, }; - securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { - principal.Identity, - }; + return true; + } catch (ProtocolFaultResponseException ex) { + // Return the appropriate unauthorized response to the client. + exception = ex; + } catch (DotNetOpenAuth.Messaging.ProtocolException /* ex*/) { + ////Logger.Error("Error processing OAuth messages.", ex); + } - return true; - } catch (ProtocolFaultResponseException ex) { - // Return the appropriate unauthorized response to the client. - ex.CreateErrorResponse().Send(); - } catch (DotNetOpenAuth.Messaging.ProtocolException/* ex*/) { - ////Logger.Error("Error processing OAuth messages.", ex); - } - } + var errorResponse = await exception.CreateErrorResponseAsync(CancellationToken.None); + await errorResponse.SendAsync(); + } - return false; + return false; + }).Result; } } } diff --git a/projecttemplates/WebFormsRelyingParty/Code/SiteUtilities.cs b/projecttemplates/WebFormsRelyingParty/Code/SiteUtilities.cs index f5cdb84..a945793 100644 --- a/projecttemplates/WebFormsRelyingParty/Code/SiteUtilities.cs +++ b/projecttemplates/WebFormsRelyingParty/Code/SiteUtilities.cs @@ -9,6 +9,8 @@ namespace WebFormsRelyingParty.Code { using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; + using System.Threading; + using System.Threading.Tasks; using System.Web; public static class SiteUtilities { @@ -52,5 +54,32 @@ namespace WebFormsRelyingParty.Code { throw new InvalidOperationException("Invalid CSRF check."); } + + internal static Task ToApm(this Task task, AsyncCallback callback, object state) { + if (task == null) { + throw new ArgumentNullException("task"); + } + + var tcs = new TaskCompletionSource<object>(state); + task.ContinueWith( + t => { + if (t.IsFaulted) { + tcs.TrySetException(t.Exception.InnerExceptions); + } else if (t.IsCanceled) { + tcs.TrySetCanceled(); + } else { + tcs.TrySetResult(null); + } + + if (callback != null) { + callback(tcs.Task); + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + + return tcs.Task; + } } } diff --git a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx index 9ec00a8..f316ee5 100644 --- a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx +++ b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" +<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Async="true" CodeBehind="OAuthAuthorize.aspx.cs" Inherits="WebFormsRelyingParty.Members.OAuthAuthorize" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="server"> diff --git a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs index 93d73c3..c82b08c 100644 --- a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs +++ b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs @@ -24,42 +24,79 @@ namespace WebFormsRelyingParty.Members { private EndUserAuthorizationRequest pendingRequest; protected void Page_Load(object sender, EventArgs e) { - if (!IsPostBack) { - this.pendingRequest = OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequest(); - if (this.pendingRequest == null) { - throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request."); - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!IsPostBack) { + this.pendingRequest = + await + OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequestAsync( + new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (this.pendingRequest == null) { + throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request."); + } - this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie(); - var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier); - this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name); - this.scopeLabel.Text = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope)); + this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie(); + var requestingClient = + Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier); + this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name); + this.scopeLabel.Text = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope)); - // Consider auto-approving if safe to do so. - if (((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices).CanBeAutoApproved(this.pendingRequest)) { - OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name); - } - this.ViewState["AuthRequest"] = this.pendingRequest; - } else { - Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value); - this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"]; - } + // Consider auto-approving if safe to do so. + if ( + ((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices) + .CanBeAutoApproved(this.pendingRequest)) { + var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest( + this.pendingRequest, HttpContext.Current.User.Identity.Name); + var responseMessage = + await + OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync( + response, Response.ClientDisconnectedToken); + await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); + this.Context.Response.End(); + } + this.ViewState["AuthRequest"] = this.pendingRequest; + } else { + Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value); + this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"]; + } + })); } protected void yesButton_Click(object sender, EventArgs e) { - var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier); - Database.LoggedInUser.ClientAuthorizations.Add( - new ClientAuthorization { - Client = requestingClient, - Scope = OAuthUtilities.JoinScopes(this.pendingRequest.Scope), - User = Database.LoggedInUser, - CreatedOnUtc = DateTime.UtcNow.CutToSecond(), - }); - OAuthServiceProvider.AuthorizationServer.ApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var requestingClient = + Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier); + Database.LoggedInUser.ClientAuthorizations.Add( + new ClientAuthorization { + Client = requestingClient, + Scope = OAuthUtilities.JoinScopes(this.pendingRequest.Scope), + User = Database.LoggedInUser, + CreatedOnUtc = DateTime.UtcNow.CutToSecond(), + }); + var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest( + this.pendingRequest, HttpContext.Current.User.Identity.Name); + var responseMessage = + await + OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken); + await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); + this.Context.Response.End(); + })); } protected void noButton_Click(object sender, EventArgs e) { - OAuthServiceProvider.AuthorizationServer.RejectAuthorizationRequest(this.pendingRequest); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var response = OAuthServiceProvider.AuthorizationServer.PrepareRejectAuthorizationRequest(this.pendingRequest); + var responseMessage = + await + OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken); + await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); + this.Context.Response.End(); + })); } } } diff --git a/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs b/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs index 65e4e9e..2c84fc6 100644 --- a/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs +++ b/projecttemplates/WebFormsRelyingParty/OAuthTokenEndpoint.ashx.cs @@ -8,16 +8,19 @@ namespace WebFormsRelyingParty { using System; using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; using System.Web; using System.Web.SessionState; + using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using RelyingPartyLogic; + using WebFormsRelyingParty.Code; /// <summary> /// An OAuth 2.0 token endpoint. /// </summary> - public class OAuthTokenEndpoint : IHttpHandler, IRequiresSessionState { + public class OAuthTokenEndpoint : HttpAsyncHandlerBase, IRequiresSessionState { /// <summary> /// Initializes a new instance of the <see cref="OAuthTokenEndpoint"/> class. /// </summary> @@ -30,16 +33,14 @@ namespace WebFormsRelyingParty { /// <returns> /// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false. /// </returns> - public bool IsReusable { + public override bool IsReusable { get { return true; } } - /// <summary> - /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface. - /// </summary> - /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> - public void ProcessRequest(HttpContext context) { - OAuthServiceProvider.AuthorizationServer.HandleTokenRequest().Respond(); + protected override async Task ProcessRequestAsync(HttpContext context) { + var serviceProvider = OAuthServiceProvider.AuthorizationServer; + var response = await serviceProvider.HandleTokenRequestAsync(new HttpRequestWrapper(context.Request), context.Response.ClientDisconnectedToken); + await response.SendAsync(new HttpContextWrapper(context), context.Response.ClientDisconnectedToken); } } } diff --git a/projecttemplates/WebFormsRelyingParty/Web.config b/projecttemplates/WebFormsRelyingParty/Web.config index 55179ae..4def867 100644 --- a/projecttemplates/WebFormsRelyingParty/Web.config +++ b/projecttemplates/WebFormsRelyingParty/Web.config @@ -137,12 +137,15 @@ <level value="INFO" /> </logger> </log4net> - <appSettings /> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> <connectionStrings> <!-- Remember to keep this connection string in sync with the one (if any) that appears in the log4net section. --> <add name="DatabaseEntities" connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\WebFormsRelyingParty.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" /> </connectionStrings> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this @@ -151,7 +154,6 @@ --> <compilation debug="true" targetFramework="4.0"> <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> diff --git a/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj b/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj index 2e0871e..11384e2 100644 --- a/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj +++ b/projecttemplates/WebFormsRelyingParty/WebFormsRelyingParty.csproj @@ -65,6 +65,8 @@ <Reference Include="System.IdentityModel"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> @@ -250,6 +252,10 @@ <Content Include="PrivacyPolicy.aspx" /> </ItemGroup> <ItemGroup> + <ProjectReference Include="..\..\samples\DotNetOpenAuth.ApplicationBlock\DotNetOpenAuth.ApplicationBlock.csproj"> + <Project>{aa78d112-d889-414b-a7d4-467b34c7b663}</Project> + <Name>DotNetOpenAuth.ApplicationBlock</Name> + </ProjectReference> <ProjectReference Include="..\..\src\DotNetOpenAuth.InfoCard.UI\DotNetOpenAuth.InfoCard.UI.csproj"> <Project>{E040EB58-B4D2-457B-A023-AE6EF3BD34DE}</Project> <Name>DotNetOpenAuth.InfoCard.UI</Name> diff --git a/projecttemplates/WebFormsRelyingParty/packages.config b/projecttemplates/WebFormsRelyingParty/packages.config index 6562527..8e40260 100644 --- a/projecttemplates/WebFormsRelyingParty/packages.config +++ b/projecttemplates/WebFormsRelyingParty/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj index 81160f2..19f26b5 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj +++ b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj @@ -33,6 +33,7 @@ <ApplicationVersion>1.0.0.%2a</ApplicationVersion> <UseApplicationTrust>false</UseApplicationTrust> <BootstrapperEnabled>true</BootstrapperEnabled> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\src\</SolutionDir> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> @@ -68,11 +69,16 @@ <DefineConstants>$(DefineConstants);SAMPLESONLY</DefineConstants> </PropertyGroup> <ItemGroup> + <Reference Include="Newtonsoft.Json"> + <HintPath>..\..\src\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath> + </Reference> <Reference Include="System" /> <Reference Include="System.configuration" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.ServiceModel.Web" /> <Reference Include="System.Web" /> @@ -93,10 +99,8 @@ <Compile Include="Facebook\FacebookGraph.cs" /> <Compile Include="CustomExtensions\UIRequestAtRelyingPartyFactory.cs" /> <Compile Include="GoogleConsumer.cs" /> + <Compile Include="HttpAsyncHandlerBase.cs" /> <Compile Include="InMemoryClientAuthorizationTracker.cs" /> - <Compile Include="InMemoryTokenManager.cs"> - <SubType>Code</SubType> - </Compile> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="TwitterConsumer.cs" /> <Compile Include="Util.cs" /> @@ -131,6 +135,10 @@ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project> <Name>DotNetOpenAuth.Core</Name> </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth.Common\DotNetOpenAuth.OAuth.Common.csproj"> + <Project>{115217c5-22cd-415c-a292-0dd0238cdd89}</Project> + <Name>DotNetOpenAuth.OAuth.Common</Name> + </ProjectReference> <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth.Consumer\DotNetOpenAuth.OAuth.Consumer.csproj"> <Project>{B202E40D-4663-4A2B-ACDA-865F88FF7CAA}</Project> <Name>DotNetOpenAuth.OAuth.Consumer</Name> @@ -168,6 +176,10 @@ <Name>DotNetOpenAuth.OpenId</Name> </ProjectReference> </ItemGroup> + <ItemGroup> + <None Include="packages.config" /> + </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " /> + <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> </Project>
\ No newline at end of file diff --git a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs index 1bdb04d..a7c062e 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs @@ -7,14 +7,20 @@ namespace DotNetOpenAuth.ApplicationBlock { using System; using System.Collections.Generic; + using System.Configuration; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using System.Web; using System.Xml; using System.Xml.Linq; using DotNetOpenAuth.Messaging; @@ -24,16 +30,15 @@ namespace DotNetOpenAuth.ApplicationBlock { /// <summary> /// A consumer capable of communicating with Google Data APIs. /// </summary> - public static class GoogleConsumer { + public class GoogleConsumer : Consumer { /// <summary> /// The Consumer to use for accessing Google data APIs. /// </summary> - public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthAuthorizeToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetAccessToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; + public static readonly ServiceProviderDescription ServiceDescription = + new ServiceProviderDescription( + "https://www.google.com/accounts/OAuthGetRequestToken", + "https://www.google.com/accounts/OAuthAuthorizeToken", + "https://www.google.com/accounts/OAuthGetAccessToken"); /// <summary> /// A mapping between Google's applications and their URI scope values. @@ -60,7 +65,19 @@ namespace DotNetOpenAuth.ApplicationBlock { /// <summary> /// The URI to get contacts once authorization is granted. /// </summary> - private static readonly MessageReceivingEndpoint GetContactsEndpoint = new MessageReceivingEndpoint("http://www.google.com/m8/feeds/contacts/default/full/", HttpDeliveryMethods.GetRequest); + private static readonly Uri GetContactsEndpoint = new Uri("http://www.google.com/m8/feeds/contacts/default/full/"); + + /// <summary> + /// Initializes a new instance of the <see cref="GoogleConsumer"/> class. + /// </summary> + public GoogleConsumer() { + this.ServiceProvider = ServiceDescription; + this.ConsumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; + this.ConsumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; + this.TemporaryCredentialStorage = HttpContext.Current != null + ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() + : new MemoryTemporaryCredentialStorage(); + } /// <summary> /// The many specific authorization scopes Google offers. @@ -149,91 +166,60 @@ namespace DotNetOpenAuth.ApplicationBlock { } /// <summary> - /// The service description to use for accessing Google data APIs using an X509 certificate. + /// Gets the scope URI in Google's format. /// </summary> - /// <param name="signingCertificate">The signing certificate.</param> - /// <returns>A service description that can be used to create an instance of - /// <see cref="DesktopConsumer"/> or <see cref="WebConsumer"/>. </returns> - public static ServiceProviderDescription CreateRsaSha1ServiceDescription(X509Certificate2 signingCertificate) { - if (signingCertificate == null) { - throw new ArgumentNullException("signingCertificate"); - } - - return new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthAuthorizeToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetAccessToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new RsaSha1ConsumerSigningBindingElement(signingCertificate) }, - }; + /// <param name="scope">The scope, which may include one or several Google applications.</param> + /// <returns>A space-delimited list of URIs for the requested Google applications.</returns> + public static string GetScopeUri(Applications scope) { + return string.Join(" ", Util.GetIndividualFlags(scope).Select(app => DataScopeUris[(Applications)app]).ToArray()); } /// <summary> /// Requests authorization from Google to access data from a set of Google applications. /// </summary> - /// <param name="consumer">The Google consumer previously constructed using <see cref="CreateWebConsumer"/> or <see cref="CreateDesktopConsumer"/>.</param> /// <param name="requestedAccessScope">The requested access scope.</param> - public static void RequestAuthorization(WebConsumer consumer, Applications requestedAccessScope) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); - } - + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public Task<Uri> RequestUserAuthorizationAsync(Applications requestedAccessScope, CancellationToken cancellationToken = default(CancellationToken)) { var extraParameters = new Dictionary<string, string> { { "scope", GetScopeUri(requestedAccessScope) }, }; Uri callback = Util.GetCallbackUrlFromContext(); - var request = consumer.PrepareRequestUserAuthorization(callback, extraParameters, null); - consumer.Channel.Send(request); - } - - /// <summary> - /// Requests authorization from Google to access data from a set of Google applications. - /// </summary> - /// <param name="consumer">The Google consumer previously constructed using <see cref="CreateWebConsumer"/> or <see cref="CreateDesktopConsumer"/>.</param> - /// <param name="requestedAccessScope">The requested access scope.</param> - /// <param name="requestToken">The unauthorized request token assigned by Google.</param> - /// <returns>The request token</returns> - public static Uri RequestAuthorization(DesktopConsumer consumer, Applications requestedAccessScope, out string requestToken) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); - } - - var extraParameters = new Dictionary<string, string> { - { "scope", GetScopeUri(requestedAccessScope) }, - }; - - return consumer.RequestUserAuthorization(extraParameters, null, out requestToken); + return this.RequestUserAuthorizationAsync(callback, extraParameters, cancellationToken); } /// <summary> /// Gets the Gmail address book's contents. /// </summary> - /// <param name="consumer">The Google consumer.</param> /// <param name="accessToken">The access token previously retrieved.</param> /// <param name="maxResults">The maximum number of entries to return. If you want to receive all of the contacts, rather than only the default maximum, you can specify a very large number here.</param> /// <param name="startIndex">The 1-based index of the first result to be retrieved (for paging).</param> - /// <returns>An XML document returned by Google.</returns> - public static XDocument GetContacts(ConsumerBase consumer, string accessToken, int maxResults/* = 25*/, int startIndex/* = 1*/) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); - } - - var extraData = new Dictionary<string, string>() { - { "start-index", startIndex.ToString(CultureInfo.InvariantCulture) }, - { "max-results", maxResults.ToString(CultureInfo.InvariantCulture) }, - }; - var request = consumer.PrepareAuthorizedRequest(GetContactsEndpoint, accessToken, extraData); - + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// An XML document returned by Google. + /// </returns> + public async Task<XDocument> GetContactsAsync(AccessToken accessToken, int maxResults = 25, int startIndex = 1, CancellationToken cancellationToken = default(CancellationToken)) { // Enable gzip compression. Google only compresses the response for recognized user agent headers. - Mike Lim - request.AutomaticDecompression = DecompressionMethods.GZip; - request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.151 Safari/534.16"; - - var response = consumer.Channel.WebRequestHandler.GetResponse(request); - string body = response.GetResponseReader().ReadToEnd(); - XDocument result = XDocument.Parse(body); - return result; + var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }; + using (var httpClient = this.CreateHttpClient(accessToken, handler)) { + var request = new HttpRequestMessage(HttpMethod.Get, GetContactsEndpoint); + request.Content = new FormUrlEncodedContent( + new Dictionary<string, string>() { + { "start-index", startIndex.ToString(CultureInfo.InvariantCulture) }, + { "max-results", maxResults.ToString(CultureInfo.InvariantCulture) }, + }); + request.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.151 Safari/534.16")); + using (var response = await httpClient.SendAsync(request, cancellationToken)) { + string body = await response.Content.ReadAsStringAsync(); + XDocument result = XDocument.Parse(body); + return result; + } + } } - public static void PostBlogEntry(ConsumerBase consumer, string accessToken, string blogUrl, string title, XElement body) { + public async Task PostBlogEntryAsync(AccessToken accessToken, string blogUrl, string title, XElement body, CancellationToken cancellationToken = default(CancellationToken)) { string feedUrl; var getBlogHome = WebRequest.Create(blogUrl); using (var blogHomeResponse = getBlogHome.GetResponse()) { @@ -258,31 +244,21 @@ namespace DotNetOpenAuth.ApplicationBlock { XmlWriter xw = XmlWriter.Create(ms, xws); entry.WriteTo(xw); xw.Flush(); - - WebRequest request = consumer.PrepareAuthorizedRequest(new MessageReceivingEndpoint(feedUrl, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), accessToken); - request.ContentType = "application/atom+xml"; - request.Method = "POST"; - request.ContentLength = ms.Length; ms.Seek(0, SeekOrigin.Begin); - using (Stream requestStream = request.GetRequestStream()) { - ms.CopyTo(requestStream); - } - using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { - if (response.StatusCode == HttpStatusCode.Created) { - // Success - } else { - // Error! + + var request = new HttpRequestMessage(HttpMethod.Post, feedUrl); + request.Content = new StreamContent(ms); + request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml"); + using (var httpClient = this.CreateHttpClient(accessToken)) { + using (var response = await httpClient.SendAsync(request, cancellationToken)) { + if (response.StatusCode == HttpStatusCode.Created) { + // Success + } else { + // Error! + response.EnsureSuccessStatusCode(); // throw some meaningful exception. + } } } } - - /// <summary> - /// Gets the scope URI in Google's format. - /// </summary> - /// <param name="scope">The scope, which may include one or several Google applications.</param> - /// <returns>A space-delimited list of URIs for the requested Google applications.</returns> - public static string GetScopeUri(Applications scope) { - return string.Join(" ", Util.GetIndividualFlags(scope).Select(app => DataScopeUris[(Applications)app]).ToArray()); - } } } diff --git a/samples/DotNetOpenAuth.ApplicationBlock/HttpAsyncHandlerBase.cs b/samples/DotNetOpenAuth.ApplicationBlock/HttpAsyncHandlerBase.cs new file mode 100644 index 0000000..a72a9b1 --- /dev/null +++ b/samples/DotNetOpenAuth.ApplicationBlock/HttpAsyncHandlerBase.cs @@ -0,0 +1,60 @@ +//----------------------------------------------------------------------- +// <copyright file="HttpAsyncHandlerBase.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.ApplicationBlock { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using System.Web; + + public abstract class HttpAsyncHandlerBase : IHttpAsyncHandler { + public abstract bool IsReusable { get; } + + public IAsyncResult BeginProcessRequest(HttpContext context, System.AsyncCallback cb, object extraData) { + return ToApm(this.ProcessRequestAsync(context), cb, extraData); + } + + public void EndProcessRequest(IAsyncResult result) { + ((Task)result).Wait(); // rethrows exceptions + } + + public void ProcessRequest(HttpContext context) { + this.ProcessRequestAsync(context).GetAwaiter().GetResult(); + } + + protected abstract Task ProcessRequestAsync(HttpContext context); + + private static Task ToApm(Task task, AsyncCallback callback, object state) { + if (task == null) { + throw new ArgumentNullException("task"); + } + + var tcs = new TaskCompletionSource<object>(state); + task.ContinueWith( + t => { + if (t.IsFaulted) { + tcs.TrySetException(t.Exception.InnerExceptions); + } else if (t.IsCanceled) { + tcs.TrySetCanceled(); + } else { + tcs.TrySetResult(null); + } + + if (callback != null) { + callback(tcs.Task); + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + + return tcs.Task; + } + } +} diff --git a/samples/DotNetOpenAuth.ApplicationBlock/InMemoryTokenManager.cs b/samples/DotNetOpenAuth.ApplicationBlock/InMemoryTokenManager.cs deleted file mode 100644 index 35f6c08..0000000 --- a/samples/DotNetOpenAuth.ApplicationBlock/InMemoryTokenManager.cs +++ /dev/null @@ -1,147 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="InMemoryTokenManager.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.ApplicationBlock { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - using DotNetOpenAuth.OpenId.Extensions.OAuth; - -#if SAMPLESONLY - /// <summary> - /// A token manager that only retains tokens in memory. - /// Meant for SHORT TERM USE TOKENS ONLY. - /// </summary> - /// <remarks> - /// A likely application of this class is for "Sign In With Twitter", - /// where the user only signs in without providing any authorization to access - /// Twitter APIs except to authenticate, since that access token is only useful once. - /// </remarks> - internal class InMemoryTokenManager : IConsumerTokenManager, IOpenIdOAuthTokenManager { - private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); - - /// <summary> - /// Initializes a new instance of the <see cref="InMemoryTokenManager"/> class. - /// </summary> - /// <param name="consumerKey">The consumer key.</param> - /// <param name="consumerSecret">The consumer secret.</param> - public InMemoryTokenManager(string consumerKey, string consumerSecret) { - if (string.IsNullOrEmpty(consumerKey)) { - throw new ArgumentNullException("consumerKey"); - } - - this.ConsumerKey = consumerKey; - this.ConsumerSecret = consumerSecret; - } - - /// <summary> - /// Gets the consumer key. - /// </summary> - /// <value>The consumer key.</value> - public string ConsumerKey { get; private set; } - - /// <summary> - /// Gets the consumer secret. - /// </summary> - /// <value>The consumer secret.</value> - public string ConsumerSecret { get; private set; } - - #region ITokenManager Members - - /// <summary> - /// Gets the Token Secret given a request or access token. - /// </summary> - /// <param name="token">The request or access token.</param> - /// <returns> - /// The secret associated with the given token. - /// </returns> - /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception> - public string GetTokenSecret(string token) { - return this.tokensAndSecrets[token]; - } - - /// <summary> - /// Stores a newly generated unauthorized request token, secret, and optional - /// application-specific parameters for later recall. - /// </summary> - /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param> - /// <param name="response">The response message that includes the unauthorized request token.</param> - /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception> - /// <remarks> - /// Request tokens stored by this method SHOULD NOT associate any user account with this token. - /// It usually opens up security holes in your application to do so. Instead, you associate a user - /// account with access tokens (not request tokens) in the <see cref="ExpireRequestTokenAndStoreNewAccessToken"/> - /// method. - /// </remarks> - public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { - this.tokensAndSecrets[response.Token] = response.TokenSecret; - } - - /// <summary> - /// Deletes a request token and its associated secret and stores a new access token and secret. - /// </summary> - /// <param name="consumerKey">The Consumer that is exchanging its request token for an access token.</param> - /// <param name="requestToken">The Consumer's request token that should be deleted/expired.</param> - /// <param name="accessToken">The new access token that is being issued to the Consumer.</param> - /// <param name="accessTokenSecret">The secret associated with the newly issued access token.</param> - /// <remarks> - /// <para> - /// Any scope of granted privileges associated with the request token from the - /// original call to <see cref="StoreNewRequestToken"/> should be carried over - /// to the new Access Token. - /// </para> - /// <para> - /// To associate a user account with the new access token, - /// <see cref="System.Web.HttpContext.User">HttpContext.Current.User</see> may be - /// useful in an ASP.NET web application within the implementation of this method. - /// Alternatively you may store the access token here without associating with a user account, - /// and wait until <see cref="WebConsumer.ProcessUserAuthorization()"/> or - /// <see cref="DesktopConsumer.ProcessUserAuthorization(string, string)"/> return the access - /// token to associate the access token with a user account at that point. - /// </para> - /// </remarks> - public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { - this.tokensAndSecrets.Remove(requestToken); - this.tokensAndSecrets[accessToken] = accessTokenSecret; - } - - /// <summary> - /// Classifies a token as a request token or an access token. - /// </summary> - /// <param name="token">The token to classify.</param> - /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> - public TokenType GetTokenType(string token) { - throw new NotImplementedException(); - } - - #endregion - - #region IOpenIdOAuthTokenManager Members - - /// <summary> - /// Stores a new request token obtained over an OpenID request. - /// </summary> - /// <param name="consumerKey">The consumer key.</param> - /// <param name="authorization">The authorization message carrying the request token and authorized access scope.</param> - /// <remarks> - /// <para>The token secret is the empty string.</para> - /// <para>Tokens stored by this method should be short-lived to mitigate - /// possible security threats. Their lifetime should be sufficient for the - /// relying party to receive the positive authentication assertion and immediately - /// send a follow-up request for the access token.</para> - /// </remarks> - public void StoreOpenIdAuthorizedRequestToken(string consumerKey, AuthorizationApprovedResponse authorization) { - this.tokensAndSecrets[authorization.RequestToken] = string.Empty; - } - - #endregion - } -#else -#error The InMemoryTokenManager class is only for samples as it forgets all tokens whenever the application restarts! You should implement IConsumerTokenManager in your own app that stores tokens in a persistent store (like a SQL database). -#endif -}
\ No newline at end of file diff --git a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs index 013e66b..16f1c92 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs @@ -11,71 +11,80 @@ namespace DotNetOpenAuth.ApplicationBlock { using System.Globalization; using System.IO; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Runtime.Serialization.Json; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; + using Newtonsoft.Json.Linq; + /// <summary> /// A consumer capable of communicating with Twitter. /// </summary> - public static class TwitterConsumer { + public class TwitterConsumer : Consumer { /// <summary> /// The description of Twitter's OAuth protocol URIs for use with actually reading/writing /// a user's private Twitter data. /// </summary> - public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/request_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/authorize", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/access_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; + public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription( + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/authorize", + "https://api.twitter.com/oauth/access_token"); /// <summary> /// The description of Twitter's OAuth protocol URIs for use with their "Sign in with Twitter" feature. /// </summary> - public static readonly ServiceProviderDescription SignInWithTwitterServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/request_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/authenticate", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/access_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; + public static readonly ServiceProviderDescription SignInWithTwitterServiceDescription = new ServiceProviderDescription( + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/authenticate", + "https://api.twitter.com/oauth/access_token"); /// <summary> /// The URI to get a user's favorites. /// </summary> - private static readonly MessageReceivingEndpoint GetFavoritesEndpoint = new MessageReceivingEndpoint("http://twitter.com/favorites.xml", HttpDeliveryMethods.GetRequest); + private static readonly Uri GetFavoritesEndpoint = new Uri("http://twitter.com/favorites.xml"); /// <summary> /// The URI to get the data on the user's home page. /// </summary> - private static readonly MessageReceivingEndpoint GetFriendTimelineStatusEndpoint = new MessageReceivingEndpoint("http://twitter.com/statuses/friends_timeline.xml", HttpDeliveryMethods.GetRequest); + private static readonly Uri GetFriendTimelineStatusEndpoint = new Uri("https://api.twitter.com/1.1/statuses/home_timeline.json"); - private static readonly MessageReceivingEndpoint UpdateProfileBackgroundImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_background_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + private static readonly Uri UpdateProfileBackgroundImageEndpoint = new Uri("http://twitter.com/account/update_profile_background_image.xml"); - private static readonly MessageReceivingEndpoint UpdateProfileImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + private static readonly Uri UpdateProfileImageEndpoint = new Uri("http://twitter.com/account/update_profile_image.xml"); - private static readonly MessageReceivingEndpoint VerifyCredentialsEndpoint = new MessageReceivingEndpoint("http://api.twitter.com/1/account/verify_credentials.xml", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + private static readonly Uri VerifyCredentialsEndpoint = new Uri("http://api.twitter.com/1/account/verify_credentials.xml"); /// <summary> - /// The consumer used for the Sign in to Twitter feature. + /// Initializes a new instance of the <see cref="TwitterConsumer"/> class. /// </summary> - private static WebConsumer signInConsumer; - - /// <summary> - /// The lock acquired to initialize the <see cref="signInConsumer"/> field. - /// </summary> - private static object signInConsumerInitLock = new object(); + public TwitterConsumer() { + this.ServiceProvider = ServiceDescription; + this.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; + this.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; + this.TemporaryCredentialStorage = HttpContext.Current != null + ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() + : new MemoryTemporaryCredentialStorage(); + } /// <summary> - /// Initializes static members of the <see cref="TwitterConsumer"/> class. + /// Initializes a new instance of the <see cref="TwitterConsumer"/> class. /// </summary> - static TwitterConsumer() { - // Twitter can't handle the Expect 100 Continue HTTP header. - ServicePointManager.FindServicePoint(GetFavoritesEndpoint.Location).Expect100Continue = false; + /// <param name="consumerKey">The consumer key.</param> + /// <param name="consumerSecret">The consumer secret.</param> + public TwitterConsumer(string consumerKey, string consumerSecret) + : this() { + this.ConsumerKey = consumerKey; + this.ConsumerSecret = consumerSecret; } /// <summary> @@ -88,137 +97,160 @@ namespace DotNetOpenAuth.ApplicationBlock { } } + public static Consumer CreateConsumer(bool forWeb = true) { + string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; + string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; + if (IsTwitterConsumerConfigured) { + ITemporaryCredentialStorage storage = forWeb ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() : new MemoryTemporaryCredentialStorage(); + return new Consumer(consumerKey, consumerSecret, ServiceDescription, storage) { + HostFactories = new TwitterHostFactories(), + }; + } else { + throw new InvalidOperationException("No Twitter OAuth consumer key and secret could be found in web.config AppSettings."); + } + } + /// <summary> - /// Gets the consumer to use for the Sign in to Twitter feature. + /// Prepares a redirect that will send the user to Twitter to sign in. /// </summary> - /// <value>The twitter sign in.</value> - private static WebConsumer TwitterSignIn { - get { - if (signInConsumer == null) { - lock (signInConsumerInitLock) { - if (signInConsumer == null) { - signInConsumer = new WebConsumer(SignInWithTwitterServiceDescription, ShortTermUserSessionTokenManager); - } - } - } + /// <param name="forceNewLogin">if set to <c>true</c> the user will be required to re-enter their Twitter credentials even if already logged in to Twitter.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The redirect message. + /// </returns> + public static async Task<Uri> StartSignInWithTwitterAsync(bool forceNewLogin = false, CancellationToken cancellationToken = default(CancellationToken)) { + var redirectParameters = new Dictionary<string, string>(); + if (forceNewLogin) { + redirectParameters["force_login"] = "true"; + } + Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_"); + + var consumer = CreateConsumer(); + consumer.ServiceProvider = SignInWithTwitterServiceDescription; + Uri redirectUrl = await consumer.RequestUserAuthorizationAsync(callback, cancellationToken: cancellationToken); + return redirectUrl; + } - return signInConsumer; + /// <summary> + /// Checks the incoming web request to see if it carries a Twitter authentication response, + /// and provides the user's Twitter screen name and unique id if available. + /// </summary> + /// <param name="completeUrl">The URL that came back from the service provider to complete the authorization.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A tuple with the screen name and Twitter unique user ID if successful; otherwise <c>null</c>. + /// </returns> + public static async Task<Tuple<string, int>> TryFinishSignInWithTwitterAsync(Uri completeUrl = null, CancellationToken cancellationToken = default(CancellationToken)) { + var consumer = CreateConsumer(); + consumer.ServiceProvider = SignInWithTwitterServiceDescription; + var response = await consumer.ProcessUserAuthorizationAsync(completeUrl ?? HttpContext.Current.Request.Url, cancellationToken: cancellationToken); + if (response == null) { + return null; } + + string screenName = response.ExtraData["screen_name"]; + int userId = int.Parse(response.ExtraData["user_id"]); + return Tuple.Create(screenName, userId); } - private static InMemoryTokenManager ShortTermUserSessionTokenManager { - get { - var store = HttpContext.Current.Session; - var tokenManager = (InMemoryTokenManager)store["TwitterShortTermUserSessionTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; - if (IsTwitterConsumerConfigured) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - store["TwitterShortTermUserSessionTokenManager"] = tokenManager; - } else { - throw new InvalidOperationException("No Twitter OAuth consumer key and secret could be found in web.config AppSettings."); - } - } + public async Task<JArray> GetUpdatesAsync(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + if (String.IsNullOrEmpty(accessToken.Token)) { + throw new ArgumentNullException("accessToken.Token"); + } - return tokenManager; + using (var httpClient = this.CreateHttpClient(accessToken)) { + using (var response = await httpClient.GetAsync(GetFriendTimelineStatusEndpoint, cancellationToken)) { + response.EnsureSuccessStatusCode(); + string jsonString = await response.Content.ReadAsStringAsync(); + var json = JArray.Parse(jsonString); + return json; + } } } - public static XDocument GetUpdates(ConsumerBase twitter, string accessToken) { - IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFriendTimelineStatusEndpoint, accessToken); - return XDocument.Load(XmlReader.Create(response.GetResponseReader())); - } + public async Task<XDocument> GetFavorites(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + if (String.IsNullOrEmpty(accessToken.Token)) { + throw new ArgumentNullException("accessToken.Token"); + } - public static XDocument GetFavorites(ConsumerBase twitter, string accessToken) { - IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFavoritesEndpoint, accessToken); - return XDocument.Load(XmlReader.Create(response.GetResponseReader())); + using (var httpClient = this.CreateHttpClient(accessToken)) { + using (HttpResponseMessage response = await httpClient.GetAsync(GetFavoritesEndpoint, cancellationToken)) { + response.EnsureSuccessStatusCode(); + return XDocument.Parse(await response.Content.ReadAsStringAsync()); + } + } } - public static XDocument UpdateProfileBackgroundImage(ConsumerBase twitter, string accessToken, string image, bool tile) { - var parts = new[] { - MultipartPostPart.CreateFormFilePart("image", image, "image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant()), - MultipartPostPart.CreateFormPart("tile", tile.ToString().ToLowerInvariant()), - }; - HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateProfileBackgroundImageEndpoint, accessToken, parts); - request.ServicePoint.Expect100Continue = false; - IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request); - string responseString = response.GetResponseReader().ReadToEnd(); - return XDocument.Parse(responseString); + public async Task<XDocument> UpdateProfileBackgroundImageAsync(AccessToken accessToken, string image, bool tile, CancellationToken cancellationToken) { + var imageAttachment = new StreamContent(File.OpenRead(image)); + imageAttachment.Headers.ContentType = new MediaTypeHeaderValue("image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant()); + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileBackgroundImageEndpoint); + var content = new MultipartFormDataContent(); + content.Add(imageAttachment, "image"); + content.Add(new StringContent(tile.ToString().ToLowerInvariant()), "tile"); + request.Content = content; + request.Headers.ExpectContinue = false; + using (var httpClient = this.CreateHttpClient(accessToken)) { + using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); + string responseString = await response.Content.ReadAsStringAsync(); + return XDocument.Parse(responseString); + } + } } - public static XDocument UpdateProfileImage(ConsumerBase twitter, string accessToken, string pathToImage) { + public Task<XDocument> UpdateProfileImageAsync(AccessToken accessToken, string pathToImage, CancellationToken cancellationToken = default(CancellationToken)) { string contentType = "image/" + Path.GetExtension(pathToImage).Substring(1).ToLowerInvariant(); - return UpdateProfileImage(twitter, accessToken, File.OpenRead(pathToImage), contentType); + return this.UpdateProfileImageAsync(accessToken, File.OpenRead(pathToImage), contentType, cancellationToken); } - public static XDocument UpdateProfileImage(ConsumerBase twitter, string accessToken, Stream image, string contentType) { - var parts = new[] { - MultipartPostPart.CreateFormFilePart("image", "twitterPhoto", contentType, image), - }; - HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateProfileImageEndpoint, accessToken, parts); - IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request); - string responseString = response.GetResponseReader().ReadToEnd(); - return XDocument.Parse(responseString); + public async Task<XDocument> UpdateProfileImageAsync(AccessToken accessToken, Stream image, string contentType, CancellationToken cancellationToken = default(CancellationToken)) { + var imageAttachment = new StreamContent(image); + imageAttachment.Headers.ContentType = new MediaTypeHeaderValue(contentType); + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileImageEndpoint); + var content = new MultipartFormDataContent(); + content.Add(imageAttachment, "image", "twitterPhoto"); + request.Content = content; + using (var httpClient = this.CreateHttpClient(accessToken)) { + using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); + string responseString = await response.Content.ReadAsStringAsync(); + return XDocument.Parse(responseString); + } + } } - public static XDocument VerifyCredentials(ConsumerBase twitter, string accessToken) { - IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(VerifyCredentialsEndpoint, accessToken); - return XDocument.Load(XmlReader.Create(response.GetResponseReader())); + public async Task<XDocument> VerifyCredentialsAsync(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + using (var httpClient = this.CreateHttpClient(accessToken)) { + using (var response = await httpClient.GetAsync(VerifyCredentialsEndpoint, cancellationToken)) { + response.EnsureSuccessStatusCode(); + using (var stream = await response.Content.ReadAsStreamAsync()) { + return XDocument.Load(XmlReader.Create(stream)); + } + } + } } - public static string GetUsername(ConsumerBase twitter, string accessToken) { - XDocument xml = VerifyCredentials(twitter, accessToken); + public async Task<string> GetUsername(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + XDocument xml = await this.VerifyCredentialsAsync(accessToken, cancellationToken); XPathNavigator nav = xml.CreateNavigator(); return nav.SelectSingleNode("/user/screen_name").Value; } - /// <summary> - /// Prepares a redirect that will send the user to Twitter to sign in. - /// </summary> - /// <param name="forceNewLogin">if set to <c>true</c> the user will be required to re-enter their Twitter credentials even if already logged in to Twitter.</param> - /// <returns>The redirect message.</returns> - /// <remarks> - /// Call <see cref="OutgoingWebResponse.Send"/> or - /// <c>return StartSignInWithTwitter().<see cref="MessagingUtilities.AsActionResult">AsActionResult()</see></c> - /// to actually perform the redirect. - /// </remarks> - public static OutgoingWebResponse StartSignInWithTwitter(bool forceNewLogin) { - var redirectParameters = new Dictionary<string, string>(); - if (forceNewLogin) { - redirectParameters["force_login"] = "true"; - } - Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_"); - var request = TwitterSignIn.PrepareRequestUserAuthorization(callback, null, redirectParameters); - return TwitterSignIn.Channel.PrepareResponse(request); - } + private class TwitterHostFactories : IHostFactories { + private static readonly IHostFactories underlyingFactories = new DefaultOAuthHostFactories(); - /// <summary> - /// Checks the incoming web request to see if it carries a Twitter authentication response, - /// and provides the user's Twitter screen name and unique id if available. - /// </summary> - /// <param name="screenName">The user's Twitter screen name.</param> - /// <param name="userId">The user's Twitter unique user ID.</param> - /// <returns> - /// A value indicating whether Twitter authentication was successful; - /// otherwise <c>false</c> to indicate that no Twitter response was present. - /// </returns> - public static bool TryFinishSignInWithTwitter(out string screenName, out int userId) { - screenName = null; - userId = 0; - var response = TwitterSignIn.ProcessUserAuthorization(); - if (response == null) { - return false; + public HttpMessageHandler CreateHttpMessageHandler() { + return new WebRequestHandler(); } - screenName = response.ExtraData["screen_name"]; - userId = int.Parse(response.ExtraData["user_id"]); + public HttpClient CreateHttpClient(HttpMessageHandler handler = null) { + var client = underlyingFactories.CreateHttpClient(handler); - // If we were going to make this LOOK like OpenID even though it isn't, - // this seems like a reasonable, secure claimed id to allow the user to assume. - OpenId.Identifier fake_claimed_id = string.Format(CultureInfo.InvariantCulture, "http://twitter.com/{0}#{1}", screenName, userId); - - return true; + // Twitter can't handle the Expect 100 Continue HTTP header. + client.DefaultRequestHeaders.ExpectContinue = false; + return client; + } } } } diff --git a/samples/DotNetOpenAuth.ApplicationBlock/Util.cs b/samples/DotNetOpenAuth.ApplicationBlock/Util.cs index 0bec372..3e0795a 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/Util.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/Util.cs @@ -13,33 +13,6 @@ internal static readonly Random NonCryptoRandomDataGenerator = new Random(); /// <summary> - /// Sets the channel's outgoing HTTP requests to use default network credentials. - /// </summary> - /// <param name="channel">The channel to modify.</param> - public static void UseDefaultNetworkCredentialsOnOutgoingHttpRequests(this Channel channel) - { - Debug.Assert(!(channel.WebRequestHandler is WrappingWebRequestHandler), "Wrapping an already wrapped web request handler. This is legal, but highly suspect of a bug as you don't want to wrap the same channel repeatedly to apply the same effect."); - AddOutgoingHttpRequestTransform(channel, http => http.Credentials = CredentialCache.DefaultNetworkCredentials); - } - - /// <summary> - /// Adds some action to any outgoing HTTP request on this channel. - /// </summary> - /// <param name="channel">The channel's whose outgoing HTTP requests should be modified.</param> - /// <param name="action">The action to perform on outgoing HTTP requests.</param> - internal static void AddOutgoingHttpRequestTransform(this Channel channel, Action<HttpWebRequest> action) { - if (channel == null) { - throw new ArgumentNullException("channel"); - } - - if (action == null) { - throw new ArgumentNullException("action"); - } - - channel.WebRequestHandler = new WrappingWebRequestHandler(channel.WebRequestHandler, action); - } - - /// <summary> /// Enumerates through the individual set bits in a flag enum. /// </summary> /// <param name="flags">The flags enum value.</param> @@ -106,154 +79,5 @@ return totalCopiedBytes; } - - /// <summary> - /// Wraps some instance of a web request handler in order to perform some extra operation on all - /// outgoing HTTP requests. - /// </summary> - private class WrappingWebRequestHandler : IDirectWebRequestHandler - { - /// <summary> - /// The handler being wrapped. - /// </summary> - private readonly IDirectWebRequestHandler wrappedHandler; - - /// <summary> - /// The action to perform on outgoing HTTP requests. - /// </summary> - private readonly Action<HttpWebRequest> action; - - /// <summary> - /// Initializes a new instance of the <see cref="WrappingWebRequestHandler"/> class. - /// </summary> - /// <param name="wrappedHandler">The HTTP handler to wrap.</param> - /// <param name="action">The action to perform on outgoing HTTP requests.</param> - internal WrappingWebRequestHandler(IDirectWebRequestHandler wrappedHandler, Action<HttpWebRequest> action) - { - if (wrappedHandler == null) { - throw new ArgumentNullException("wrappedHandler"); - } - - if (action == null) { - throw new ArgumentNullException("action"); - } - - this.wrappedHandler = wrappedHandler; - this.action = action; - } - - #region Implementation of IDirectWebRequestHandler - - /// <summary> - /// Determines whether this instance can support the specified options. - /// </summary> - /// <param name="options">The set of options that might be given in a subsequent web request.</param> - /// <returns> - /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>. - /// </returns> - public bool CanSupport(DirectWebRequestOptions options) - { - return this.wrappedHandler.CanSupport(options); - } - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <returns> - /// The stream the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method. - /// Callers <i>must</i> close and dispose of the request stream when they are done - /// writing to it to avoid taking up the connection too long and causing long waits on - /// subsequent requests.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - public Stream GetRequestStream(HttpWebRequest request) - { - this.action(request); - return this.wrappedHandler.GetRequestStream(request); - } - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns> - /// The stream the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method. - /// Callers <i>must</i> close and dispose of the request stream when they are done - /// writing to it to avoid taking up the connection too long and causing long waits on - /// subsequent requests.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - public Stream GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) - { - this.action(request); - return this.wrappedHandler.GetRequestStream(request, options); - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - public IncomingWebResponse GetResponse(HttpWebRequest request) - { - // If the request has an entity, the action would have already been processed in GetRequestStream. - if (request.Method == "GET") - { - this.action(request); - } - - return this.wrappedHandler.GetResponse(request); - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - public IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options) - { - // If the request has an entity, the action would have already been processed in GetRequestStream. - if (request.Method == "GET") { - this.action(request); - } - - return this.wrappedHandler.GetResponse(request, options); - } - - #endregion - } } } diff --git a/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs index bbeb861..1dff5b6 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs @@ -7,55 +7,45 @@ namespace DotNetOpenAuth.ApplicationBlock { using System; using System.Collections.Generic; + using System.Configuration; using System.Linq; using System.Net; using System.Text; + using System.Threading; + using System.Threading.Tasks; + using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; - public static class YammerConsumer { + public class YammerConsumer : Consumer { /// <summary> /// The Consumer to use for accessing Google data APIs. /// </summary> - public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.yammer.com/oauth/request_token", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.yammer.com/oauth/authorize", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.yammer.com/oauth/access_token", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new PlaintextSigningBindingElement() }, - ProtocolVersion = ProtocolVersion.V10, - }; + public static readonly ServiceProviderDescription ServiceDescription = + new ServiceProviderDescription( + "https://www.yammer.com/oauth/request_token", + "https://www.yammer.com/oauth/authorize", + "https://www.yammer.com/oauth/access_token"); - public static DesktopConsumer CreateConsumer(IConsumerTokenManager tokenManager) { - return new DesktopConsumer(ServiceDescription, tokenManager); + public YammerConsumer() { + this.ServiceProvider = ServiceDescription; + this.ConsumerKey = ConfigurationManager.AppSettings["YammerConsumerKey"]; + this.ConsumerSecret = ConfigurationManager.AppSettings["YammerConsumerSecret"]; + this.TemporaryCredentialStorage = HttpContext.Current != null + ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() + : new MemoryTemporaryCredentialStorage(); } - public static Uri PrepareRequestAuthorization(DesktopConsumer consumer, out string requestToken) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); + /// <summary> + /// Gets a value indicating whether the Twitter consumer key and secret are set in the web.config file. + /// </summary> + public static bool IsConsumerConfigured { + get { + return !string.IsNullOrEmpty(ConfigurationManager.AppSettings["yammerConsumerKey"]) && + !string.IsNullOrEmpty(ConfigurationManager.AppSettings["yammerConsumerSecret"]); } - - Uri authorizationUrl = consumer.RequestUserAuthorization(null, null, out requestToken); - return authorizationUrl; - } - - public static AuthorizedTokenResponse CompleteAuthorization(DesktopConsumer consumer, string requestToken, string userCode) { - // Because Yammer has a proprietary callback_token parameter, and it's passed - // with the message that specifically bans extra arguments being passed, we have - // to cheat by adding the data to the URL itself here. - var customServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = ServiceDescription.RequestTokenEndpoint, - UserAuthorizationEndpoint = ServiceDescription.UserAuthorizationEndpoint, - AccessTokenEndpoint = new MessageReceivingEndpoint(ServiceDescription.AccessTokenEndpoint.Location.AbsoluteUri + "?oauth_verifier=" + Uri.EscapeDataString(userCode), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), - TamperProtectionElements = ServiceDescription.TamperProtectionElements, - ProtocolVersion = ProtocolVersion.V10, - }; - - // To use a custom service description we also must create a new WebConsumer. - var customConsumer = new DesktopConsumer(customServiceDescription, consumer.TokenManager); - var response = customConsumer.ProcessUserAuthorization(requestToken, userCode); - return response; } } } diff --git a/samples/DotNetOpenAuth.ApplicationBlock/packages.config b/samples/DotNetOpenAuth.ApplicationBlock/packages.config new file mode 100644 index 0000000..d7219c5 --- /dev/null +++ b/samples/DotNetOpenAuth.ApplicationBlock/packages.config @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/samples/InfoCardRelyingParty/web.config b/samples/InfoCardRelyingParty/web.config index 835625c..9575005 100644 --- a/samples/InfoCardRelyingParty/web.config +++ b/samples/InfoCardRelyingParty/web.config @@ -38,7 +38,9 @@ <defaultProxy enabled="true" /> </system.net> - <appSettings/> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> <connectionStrings/> <system.web> @@ -53,11 +55,7 @@ where data loss can occur. Set explicit="true" to force declaration of all variables. --> - <compilation debug="true" strict="false" explicit="true" targetFramework="4.5"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <compilation debug="true" strict="false" explicit="true" targetFramework="4.5" /> <pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID"> <namespaces> <clear/> @@ -100,7 +98,7 @@ </customErrors> --> <!-- Force ASP.NET 4.0 to respect ValidateRequest="false" in the login page to avoid false reports from the SAML token. --> - <httpRuntime requestValidationMode="2.0" /> + <httpRuntime requestValidationMode="2.0" targetFramework="4.5" /> </system.web> <!-- The system.webServer section is required for running ASP.NET AJAX under Internet diff --git a/samples/OAuth2ProtectedWebApi/App_Start/BundleConfig.cs b/samples/OAuth2ProtectedWebApi/App_Start/BundleConfig.cs new file mode 100644 index 0000000..6524cf6 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/App_Start/BundleConfig.cs @@ -0,0 +1,40 @@ +using System.Web; +using System.Web.Optimization; + +namespace OAuth2ProtectedWebApi { + public class BundleConfig { + // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 + public static void RegisterBundles(BundleCollection bundles) { + bundles.Add(new ScriptBundle("~/bundles/jquery").Include( + "~/Scripts/jquery-{version}.js")); + + bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( + "~/Scripts/jquery-ui-{version}.js")); + + bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( + "~/Scripts/jquery.unobtrusive*", + "~/Scripts/jquery.validate*")); + + // Use the development version of Modernizr to develop with and learn from. Then, when you're + // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. + bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( + "~/Scripts/modernizr-*")); + + bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css")); + + bundles.Add(new StyleBundle("~/Content/themes/base/css").Include( + "~/Content/themes/base/jquery.ui.core.css", + "~/Content/themes/base/jquery.ui.resizable.css", + "~/Content/themes/base/jquery.ui.selectable.css", + "~/Content/themes/base/jquery.ui.accordion.css", + "~/Content/themes/base/jquery.ui.autocomplete.css", + "~/Content/themes/base/jquery.ui.button.css", + "~/Content/themes/base/jquery.ui.dialog.css", + "~/Content/themes/base/jquery.ui.slider.css", + "~/Content/themes/base/jquery.ui.tabs.css", + "~/Content/themes/base/jquery.ui.datepicker.css", + "~/Content/themes/base/jquery.ui.progressbar.css", + "~/Content/themes/base/jquery.ui.theme.css")); + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/App_Start/FilterConfig.cs b/samples/OAuth2ProtectedWebApi/App_Start/FilterConfig.cs new file mode 100644 index 0000000..a482091 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/App_Start/FilterConfig.cs @@ -0,0 +1,10 @@ +using System.Web; +using System.Web.Mvc; + +namespace OAuth2ProtectedWebApi { + public class FilterConfig { + public static void RegisterGlobalFilters(GlobalFilterCollection filters) { + filters.Add(new HandleErrorAttribute()); + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/App_Start/RouteConfig.cs b/samples/OAuth2ProtectedWebApi/App_Start/RouteConfig.cs new file mode 100644 index 0000000..d64e426 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/App_Start/RouteConfig.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; + +namespace OAuth2ProtectedWebApi { + public class RouteConfig { + public static void RegisterRoutes(RouteCollection routes) { + routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + + routes.MapRoute( + name: "Default", + url: "{controller}/{action}/{id}", + defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } + ); + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/App_Start/WebApiConfig.cs b/samples/OAuth2ProtectedWebApi/App_Start/WebApiConfig.cs new file mode 100644 index 0000000..d783d13 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/App_Start/WebApiConfig.cs @@ -0,0 +1,20 @@ +namespace OAuth2ProtectedWebApi { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web.Http; + + using OAuth2ProtectedWebApi.Code; + + public static class WebApiConfig { + public static void Register(HttpConfiguration config) { + config.Routes.MapHttpRoute( + name: "DefaultApi", + routeTemplate: "api/{controller}/{id}", + defaults: new { id = RouteParameter.Optional } + ); + + config.MessageHandlers.Add(new BearerTokenHandler()); + } + } +} diff --git a/samples/OAuth2ProtectedWebApi/Code/AuthorizationServerHost.cs b/samples/OAuth2ProtectedWebApi/Code/AuthorizationServerHost.cs new file mode 100644 index 0000000..843280b --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Code/AuthorizationServerHost.cs @@ -0,0 +1,181 @@ +namespace OAuth2ProtectedWebApi.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.Security; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth2; + using DotNetOpenAuth.OAuth2.ChannelElements; + using DotNetOpenAuth.OAuth2.Messages; + using OAuth2ProtectedWebApi.Code; + + /// <summary> + /// Provides application-specific policy and persistence for OAuth 2.0 authorization servers. + /// </summary> + public class AuthorizationServerHost : IAuthorizationServerHost { + /// <summary> + /// Storage for the cryptographic keys used to protect authorization codes, refresh tokens and access tokens. + /// </summary> + /// <remarks> + /// A single, hard-coded symmetric key is hardly adequate. Applications that rely on decent security should + /// replace this implementation with one that actually stores and retrieves keys in some persistent store + /// (e.g. a database). DotNetOpenAuth will automatically take care of generating, rotating, and expiring keys + /// if you provide a real implementation of this interface. + /// TODO: Consider replacing use of <see cref="HardCodedKeyCryptoKeyStore"/> with a real persisted database table. + /// </remarks> + internal static readonly ICryptoKeyStore HardCodedCryptoKeyStore = new HardCodedKeyCryptoKeyStore("p7J1L24Qj4KGYUOrnfENF0XAhqn6rZc5dx4nxvI22Kg="); + + /// <summary> + /// Gets the store for storing crypto keys used to symmetrically encrypt and sign authorization codes and refresh tokens. + /// </summary> + /// <remarks> + /// This store should be kept strictly confidential in the authorization server(s) + /// and NOT shared with the resource server. Anyone with these secrets can mint + /// tokens to essentially grant themselves access to anything they want. + /// </remarks> + public ICryptoKeyStore CryptoKeyStore { + get { return HardCodedCryptoKeyStore; } + } + + /// <summary> + /// Gets the authorization code nonce store to use to ensure that authorization codes can only be used once. + /// </summary> + /// <value> + /// The authorization code nonce store. + /// </value> + public INonceStore NonceStore { + get { + // TODO: Consider implementing a nonce store to mitigate replay attacks on authorization codes. + return null; + } + } + + /// <summary> + /// Acquires the access token and related parameters that go into the formulation of the token endpoint's response to a client. + /// </summary> + /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client + /// that will receive that access. + /// Based on this information the receiving resource server can be determined and the lifetime of the access + /// token can be set based on the sensitivity of the resources.</param> + /// <returns> + /// A non-null parameters instance that DotNetOpenAuth will dispose after it has been used. + /// </returns> + public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { + // If your resource server and authorization server are different web apps, + // consider using asymmetric keys instead of symmetric ones by setting different + // properties on the access token below. + var accessToken = new AuthorizationServerAccessToken { + Lifetime = TimeSpan.FromHours(1), + SymmetricKeyStore = this.CryptoKeyStore, + }; + var result = new AccessTokenResult(accessToken); + return result; + } + + /// <summary> + /// Gets the client with a given identifier. + /// </summary> + /// <param name="clientIdentifier">The client identifier.</param> + /// <returns> + /// The client registration. Never null. + /// </returns> + /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception> + public IClientDescription GetClient(string clientIdentifier) { + // TODO: Consider adding a clients table in your database to track actual client accounts + // with authenticating secrets. + // For now, just allow all clients regardless of ID, and consider them "Public" clients. + return new AnyCallbackClient(); + } + + /// <summary> + /// Determines whether a described authorization is (still) valid. + /// </summary> + /// <param name="authorization">The authorization.</param> + /// <returns> + /// <c>true</c> if the original authorization is still valid; otherwise, <c>false</c>. + /// </returns> + /// <remarks> + /// <para>When establishing that an authorization is still valid, + /// it's very important to only match on recorded authorizations that + /// meet these criteria:</para> + /// 1) The client identifier matches. + /// 2) The user account matches. + /// 3) The scope on the recorded authorization must include all scopes in the given authorization. + /// 4) The date the recorded authorization was issued must be <em>no later</em> that the date the given authorization was issued. + /// <para>One possible scenario is where the user authorized a client, later revoked authorization, + /// and even later reinstated authorization. This subsequent recorded authorization + /// would not satisfy requirement #4 in the above list. This is important because the revocation + /// the user went through should invalidate all previously issued tokens as a matter of + /// security in the event the user was revoking access in order to sever authorization on a stolen + /// account or piece of hardware in which the tokens were stored. </para> + /// </remarks> + public bool IsAuthorizationValid(IAuthorizationDescription authorization) { + // If your application supports access revocation (highly recommended), + // this method should return false if the specified authorization is not + // discovered in your current authorizations table. + //// TODO: code here + + return true; + } + + /// <summary> + /// Determines whether a given set of resource owner credentials is valid based on the authorization server's user database + /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid" /> would + /// return <c>true</c>. + /// </summary> + /// <param name="userName">Username on the account.</param> + /// <param name="password">The user's password.</param> + /// <param name="accessRequest">The access request the credentials came with. + /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> + /// <returns> + /// A value that describes the result of the authorization check. + /// </returns> + /// <exception cref="System.NotSupportedException"></exception> + public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password, IAccessTokenRequest accessRequest) { + // TODO: Consider only accepting resource owner credential grants from specific clients + // based on accessRequest.ClientIdentifier and accessRequest.ClientAuthenticated. + if (Membership.ValidateUser(userName, password)) { + // Add an entry to your authorization table to record that access was granted so that + // you can conditionally return true from IsAuthorizationValid when the row is discovered. + //// TODO: code here + + // Inform DotNetOpenAuth that it may proceed to issue an access token. + return new AutomatedUserAuthorizationCheckResponse(accessRequest, true, Membership.GetUser(userName).UserName); + } else { + return new AutomatedUserAuthorizationCheckResponse(accessRequest, false, null); + } + } + + /// <summary> + /// Determines whether an access token request given a client credential grant should be authorized + /// and if so records an authorization entry such that subsequent calls to <see cref="IsAuthorizationValid" /> would + /// return <c>true</c>. + /// </summary> + /// <param name="accessRequest">The access request the credentials came with. + /// This may be useful if the authorization server wishes to apply some policy based on the client that is making the request.</param> + /// <returns> + /// A value that describes the result of the authorization check. + /// </returns> + /// <exception cref="System.NotSupportedException"></exception> + public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest) { + // TODO: Consider implementing this if your application should support clients that access data that + // doesn't belong to specific people, or clients that have elevated privileges and can access other + // people's data. + if (accessRequest.ClientAuthenticated) { + // Before returning a positive response, be *very careful* to validate the requested access scope + // to make sure it is appropriate for the requesting client. + throw new NotSupportedException(); + } else { + // Only authenticated clients should be given access. + return new AutomatedAuthorizationCheckResponse(accessRequest, false); + } + } + + private class AnyCallbackClient : ClientDescription { + public override bool IsCallbackAllowed(Uri callback) { + return true; + } + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Code/BearerTokenHandler.cs b/samples/OAuth2ProtectedWebApi/Code/BearerTokenHandler.cs new file mode 100644 index 0000000..23ec087 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Code/BearerTokenHandler.cs @@ -0,0 +1,30 @@ +namespace OAuth2ProtectedWebApi.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using System.Web; + + using DotNetOpenAuth.OAuth2; + + /// <summary> + /// An HTTP server message handler that detects OAuth 2 bearer tokens in the authorization header + /// and applies the appropriate principal to the request when found. + /// </summary> + public class BearerTokenHandler : DelegatingHandler { + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + if (request.Headers.Authorization != null) { + if (request.Headers.Authorization.Scheme == "Bearer") { + var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AuthorizationServerHost.HardCodedCryptoKeyStore)); + var principal = await resourceServer.GetPrincipalAsync(request, cancellationToken); + HttpContext.Current.User = principal; + Thread.CurrentPrincipal = principal; + } + } + + return await base.SendAsync(request, cancellationToken); + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Code/HttpHeaderAttribute.cs b/samples/OAuth2ProtectedWebApi/Code/HttpHeaderAttribute.cs new file mode 100644 index 0000000..3bff848 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Code/HttpHeaderAttribute.cs @@ -0,0 +1,41 @@ +namespace OAuth2ProtectedWebApi.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.Mvc; + + /// <summary> + /// Represents an attribute that is used to add HTTP Headers to a Controller Action response. + /// </summary> + public class HttpHeaderAttribute : ActionFilterAttribute { + /// <summary> + /// Initializes a new instance of the <see cref="HttpHeaderAttribute"/> class. + /// </summary> + /// <param name="name">The HTTP header name.</param> + /// <param name="value">The HTTP header value.</param> + public HttpHeaderAttribute(string name, string value) { + this.Name = name; + this.Value = value; + } + + /// <summary> + /// Gets or sets the name of the HTTP Header. + /// </summary> + public string Name { get; set; } + + /// <summary> + /// Gets or sets the value of the HTTP Header. + /// </summary> + public string Value { get; set; } + + /// <summary> + /// Called by the MVC framework after the action result executes. + /// </summary> + /// <param name="filterContext">The filter context.</param> + public override void OnResultExecuted(ResultExecutedContext filterContext) { + filterContext.HttpContext.Response.AppendHeader(this.Name, this.Value); + base.OnResultExecuted(filterContext); + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/Site.css b/samples/OAuth2ProtectedWebApi/Content/Site.css new file mode 100644 index 0000000..be14409 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/Site.css @@ -0,0 +1,756 @@ +html { + background-color: #e2e2e2; + margin: 0; + padding: 0; +} + +body { + background-color: #fff; + border-top: solid 10px #000; + color: #333; + font-size: .85em; + font-family: "Segoe UI", Verdana, Helvetica, Sans-Serif; + margin: 0; + padding: 0; +} + +a { + color: #333; + outline: none; + padding-left: 3px; + padding-right: 3px; + text-decoration: underline; +} + + a:link, a:visited, + a:active, a:hover { + color: #333; + } + + a:hover { + background-color: #c7d1d6; + } + +header, footer, hgroup, +nav, section { + display: block; +} + +mark { + background-color: #a6dbed; + padding-left: 5px; + padding-right: 5px; +} + +.float-left { + float: left; +} + +.float-right { + float: right; +} + +.clear-fix:after { + content: "."; + clear: both; + display: block; + height: 0; + visibility: hidden; +} + +h1, h2, h3, +h4, h5, h6 { + color: #000; + margin-bottom: 0; + padding-bottom: 0; +} + +h1 { + font-size: 2em; +} + +h2 { + font-size: 1.75em; +} + +h3 { + font-size: 1.2em; +} + +h4 { + font-size: 1.1em; +} + +h5, h6 { + font-size: 1em; +} + + h5 a:link, h5 a:visited, h5 a:active { + padding: 0; + text-decoration: none; + } + + +/* main layout +----------------------------------------------------------*/ +.content-wrapper { + margin: 0 auto; + max-width: 960px; +} + +#body { + background-color: #efeeef; + clear: both; + padding-bottom: 35px; +} + + .main-content { + background: url("../Images/accent.png") no-repeat; + padding-left: 10px; + padding-top: 30px; + } + + .featured + .main-content { + background: url("../Images/heroAccent.png") no-repeat; + } + +header .content-wrapper { + padding-top: 20px; +} + +footer { + clear: both; + background-color: #e2e2e2; + font-size: .8em; + height: 100px; +} + + +/* site title +----------------------------------------------------------*/ +.site-title { + color: #c8c8c8; + font-family: Rockwell, Consolas, "Courier New", Courier, monospace; + font-size: 2.3em; + margin: 0; +} + +.site-title a, .site-title a:hover, .site-title a:active { + background: none; + color: #c8c8c8; + outline: none; + text-decoration: none; +} + + +/* login +----------------------------------------------------------*/ +#login { + display: block; + font-size: .85em; + margin: 0 0 10px; + text-align: right; +} + + #login a { + background-color: #d3dce0; + margin-left: 10px; + margin-right: 3px; + padding: 2px 3px; + text-decoration: none; + } + + #login a.username { + background: none; + margin: 0; + padding: 0; + text-decoration: underline; + } + + #login ul { + margin: 0; + } + + #login li { + display: inline; + list-style: none; + } + + +/* menu +----------------------------------------------------------*/ +ul#menu { + font-size: 1.3em; + font-weight: 600; + margin: 0 0 5px; + padding: 0; + text-align: right; +} + + ul#menu li { + display: inline; + list-style: none; + padding-left: 15px; + } + + ul#menu li a { + background: none; + color: #999; + text-decoration: none; + } + + ul#menu li a:hover { + color: #333; + text-decoration: none; + } + + +/* page elements +----------------------------------------------------------*/ +/* featured */ +.featured { + background-color: #fff; +} + + .featured .content-wrapper { + background-color: #7ac0da; + background-image: -ms-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%); + background-image: -o-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%); + background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #7ac0da), color-stop(1, #a4d4e6)); + background-image: -webkit-linear-gradient(left, #7ac0da 0%, #a4d4e6 100%); + background-image: linear-gradient(left, #7ac0da 0%, #a4d4e6 100%); + color: #3e5667; + padding: 20px 40px 30px 40px; + } + + .featured hgroup.title h1, .featured hgroup.title h2 { + color: #fff; + } + + .featured p { + font-size: 1.1em; + } + +/* page titles */ +hgroup.title { + margin-bottom: 10px; +} + +hgroup.title h1, hgroup.title h2 { + display: inline; +} + +hgroup.title h2 { + font-weight: normal; + margin-left: 3px; +} + +/* features */ +section.feature { + width: 300px; + float: left; + padding: 10px; +} + +/* ordered list */ +ol.round { + list-style-type: none; + padding-left: 0; +} + + ol.round li { + margin: 25px 0; + padding-left: 45px; + } + + ol.round li.zero { + background: url("../Images/orderedList0.png") no-repeat; + } + + ol.round li.one { + background: url("../Images/orderedList1.png") no-repeat; + } + + ol.round li.two { + background: url("../Images/orderedList2.png") no-repeat; + } + + ol.round li.three { + background: url("../Images/orderedList3.png") no-repeat; + } + + ol.round li.four { + background: url("../Images/orderedList4.png") no-repeat; + } + + ol.round li.five { + background: url("../Images/orderedList5.png") no-repeat; + } + + ol.round li.six { + background: url("../Images/orderedList6.png") no-repeat; + } + + ol.round li.seven { + background: url("../Images/orderedList7.png") no-repeat; + } + + ol.round li.eight { + background: url("../Images/orderedList8.png") no-repeat; + } + + ol.round li.nine { + background: url("../Images/orderedList9.png") no-repeat; + } + +/* content */ +article { + float: left; + width: 70%; +} + +aside { + float: right; + width: 25%; +} + + aside ul { + list-style: none; + padding: 0; + } + + aside ul li { + background: url("../Images/bullet.png") no-repeat 0 50%; + padding: 2px 0 2px 20px; + } + +.label { + font-weight: 700; +} + +/* login page */ +#loginForm { + border-right: solid 2px #c8c8c8; + float: left; + width: 55%; +} + + #loginForm .validation-error { + display: block; + margin-left: 15px; + } + + #loginForm .validation-summary-errors ul { + margin: 0; + padding: 0; + } + + #loginForm .validation-summary-errors li { + display: inline; + list-style: none; + margin: 0; + } + + #loginForm input { + width: 250px; + } + + #loginForm input[type="checkbox"], + #loginForm input[type="submit"], + #loginForm input[type="button"], + #loginForm button { + width: auto; + } + +#socialLoginForm { + margin-left: 40px; + float: left; + width: 40%; +} + + #socialLoginForm h2 { + margin-bottom: 5px; + } + +#socialLoginList button { + margin-bottom: 12px; +} + +#logoutForm { + display: inline; +} + +/* contact */ +.contact h3 { + font-size: 1.2em; +} + +.contact p { + margin: 5px 0 0 10px; +} + +.contact iframe { + border: 1px solid #333; + margin: 5px 0 0 10px; +} + +/* forms */ +fieldset { + border: none; + margin: 0; + padding: 0; +} + + fieldset legend { + display: none; + } + + fieldset ol { + padding: 0; + list-style: none; + } + + fieldset ol li { + padding-bottom: 5px; + } + +label { + display: block; + font-size: 1.2em; + font-weight: 600; +} + +label.checkbox { + display: inline; +} + +input, textarea { + border: 1px solid #e2e2e2; + background: #fff; + color: #333; + font-size: 1.2em; + margin: 5px 0 6px 0; + padding: 5px; + width: 300px; +} + +textarea { + font-family: inherit; + width: 500px; +} + + input:focus, textarea:focus { + border: 1px solid #7ac0da; + } + + input[type="checkbox"] { + background: transparent; + border: inherit; + width: auto; + } + + input[type="submit"], + input[type="button"], + button { + background-color: #d3dce0; + border: 1px solid #787878; + cursor: pointer; + font-size: 1.2em; + font-weight: 600; + padding: 7px; + margin-right: 8px; + width: auto; + } + + td input[type="submit"], + td input[type="button"], + td button { + font-size: 1em; + padding: 4px; + margin-right: 4px; + } + +/* info and errors */ +.message-info { + border: 1px solid; + clear: both; + padding: 10px 20px; +} + +.message-error { + clear: both; + color: #e80c4d; + font-size: 1.1em; + font-weight: bold; + margin: 20px 0 10px 0; +} + +.message-success { + color: #7ac0da; + font-size: 1.3em; + font-weight: bold; + margin: 20px 0 10px 0; +} + +.error { + color: #e80c4d; +} + +/* styles for validation helpers */ +.field-validation-error { + color: #e80c4d; + font-weight: bold; +} + +.field-validation-valid { + display: none; +} + +input.input-validation-error { + border: 1px solid #e80c4d; +} + +input[type="checkbox"].input-validation-error { + border: 0 none; +} + +.validation-summary-errors { + color: #e80c4d; + font-weight: bold; + font-size: 1.1em; +} + +.validation-summary-valid { + display: none; +} + + +/* tables +----------------------------------------------------------*/ +table { + border-collapse: collapse; + border-spacing: 0; + margin-top: 0.75em; + border: 0 none; +} + +th { + font-size: 1.2em; + text-align: left; + border: none 0px; + padding-left: 0; +} + + th a { + display: block; + position: relative; + } + + th a:link, th a:visited, th a:active, th a:hover { + color: #333; + font-weight: 600; + text-decoration: none; + padding: 0; + } + + th a:hover { + color: #000; + } + + th.asc a, th.desc a { + margin-right: .75em; + } + + th.asc a:after, th.desc a:after { + display: block; + position: absolute; + right: 0em; + top: 0; + font-size: 0.75em; + } + + th.asc a:after { + content: '▲'; + } + + th.desc a:after { + content: '▼'; + } + +td { + padding: 0.25em 2em 0.25em 0em; + border: 0 none; +} + +tr.pager td { + padding: 0 0.25em 0 0; +} + + +/******************** +* Mobile Styles * +********************/ +@media only screen and (max-width: 850px) { + + /* header + ----------------------------------------------------------*/ + header .float-left, + header .float-right { + float: none; + } + + /* logo */ + header .site-title { + margin: 10px; + text-align: center; + } + + /* login */ + #login { + font-size: .85em; + margin: 0 0 12px; + text-align: center; + } + + #login ul { + margin: 5px 0; + padding: 0; + } + + #login li { + display: inline; + list-style: none; + margin: 0; + padding: 0; + } + + #login a { + background: none; + color: #999; + font-weight: 600; + margin: 2px; + padding: 0; + } + + #login a:hover { + color: #333; + } + + /* menu */ + nav { + margin-bottom: 5px; + } + + ul#menu { + margin: 0; + padding: 0; + text-align: center; + } + + ul#menu li { + margin: 0; + padding: 0; + } + + + /* main layout + ----------------------------------------------------------*/ + .main-content, + .featured + .main-content { + background-position: 10px 0; + } + + .content-wrapper { + padding-right: 10px; + padding-left: 10px; + } + + .featured .content-wrapper { + padding: 10px; + } + + /* page content */ + article, aside { + float: none; + width: 100%; + } + + /* ordered list */ + ol.round { + list-style-type: none; + padding-left: 0; + } + + ol.round li { + padding-left: 10px; + margin: 25px 0; + } + + ol.round li.zero, + ol.round li.one, + ol.round li.two, + ol.round li.three, + ol.round li.four, + ol.round li.five, + ol.round li.six, + ol.round li.seven, + ol.round li.eight, + ol.round li.nine { + background: none; + } + + /* features */ + section.feature { + float: none; + padding: 10px; + width: auto; + } + + section.feature img { + color: #999; + content: attr(alt); + font-size: 1.5em; + font-weight: 600; + } + + /* forms */ + input { + width: 90%; + } + + /* login page */ + #loginForm { + border-right: none; + float: none; + width: auto; + } + + #loginForm .validation-error { + display: block; + margin-left: 15px; + } + + #socialLoginForm { + margin-left: 0; + float: none; + width: auto; + } + + + /* footer + ----------------------------------------------------------*/ + footer .float-left, + footer .float-right { + float: none; + } + + footer { + text-align: center; + height: auto; + padding: 10px 0; + } + + footer p { + margin: 0; + } +} diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_flat_0_aaaaaa_40x100.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_flat_0_aaaaaa_40x100.png Binary files differnew file mode 100644 index 0000000..5b5dab2 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_flat_0_aaaaaa_40x100.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_flat_75_ffffff_40x100.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_flat_75_ffffff_40x100.png Binary files differnew file mode 100644 index 0000000..ac8b229 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_flat_75_ffffff_40x100.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_55_fbf9ee_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_55_fbf9ee_1x400.png Binary files differnew file mode 100644 index 0000000..ad3d634 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_55_fbf9ee_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_65_ffffff_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_65_ffffff_1x400.png Binary files differnew file mode 100644 index 0000000..42ccba2 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_65_ffffff_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_75_dadada_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_75_dadada_1x400.png Binary files differnew file mode 100644 index 0000000..5a46b47 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_75_dadada_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_75_e6e6e6_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_75_e6e6e6_1x400.png Binary files differnew file mode 100644 index 0000000..86c2baa --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_75_e6e6e6_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_95_fef1ec_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_95_fef1ec_1x400.png Binary files differnew file mode 100644 index 0000000..4443fdc --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_glass_95_fef1ec_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_highlight-soft_75_cccccc_1x100.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_highlight-soft_75_cccccc_1x100.png Binary files differnew file mode 100644 index 0000000..7c9fa6c --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-bg_highlight-soft_75_cccccc_1x100.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_222222_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_222222_256x240.png Binary files differnew file mode 100644 index 0000000..ee039dc --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_222222_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_2e83ff_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_2e83ff_256x240.png Binary files differnew file mode 100644 index 0000000..45e8928 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_2e83ff_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_454545_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_454545_256x240.png Binary files differnew file mode 100644 index 0000000..7ec70d1 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_454545_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_888888_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_888888_256x240.png Binary files differnew file mode 100644 index 0000000..5ba708c --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_888888_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_cd0a0a_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_cd0a0a_256x240.png Binary files differnew file mode 100644 index 0000000..7930a55 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/images/ui-icons_cd0a0a_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery-ui.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery-ui.css new file mode 100644 index 0000000..764b8f9 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery-ui.css @@ -0,0 +1,466 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.core.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.progressbar.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.slider.css, jquery.ui.tabs.css, jquery.ui.theme.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { display: none; } +.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } +.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } +.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; } +.ui-helper-clearfix:after { clear: both; } +.ui-helper-clearfix { zoom: 1; } +.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } + + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { cursor: default !important; } + + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } + + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } + +/* IE/Win - Fix animation bug - #4615 */ +.ui-accordion { width: 100%; } +.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; } +.ui-accordion .ui-accordion-li-fix { display: inline; } +.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; } +.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; } +.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; } +.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } +.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; } +.ui-accordion .ui-accordion-content-active { display: block; } + +.ui-autocomplete { position: absolute; cursor: default; } + +/* workarounds */ +* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ + +/* + * jQuery UI Menu 1.8.20 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Menu#theming + */ +.ui-menu { + list-style:none; + padding: 2px; + margin: 0; + display:block; + float: left; +} +.ui-menu .ui-menu { + margin-top: -3px; +} +.ui-menu .ui-menu-item { + margin:0; + padding: 0; + zoom: 1; + float: left; + clear: left; + width: 100%; +} +.ui-menu .ui-menu-item a { + text-decoration:none; + display:block; + padding:.2em .4em; + line-height:1.5; + zoom:1; +} +.ui-menu .ui-menu-item a.ui-state-hover, +.ui-menu .ui-menu-item a.ui-state-active { + font-weight: normal; + margin: -1px; +} + +.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */ +.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */ +button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */ +.ui-button-icons-only { width: 3.4em; } +button.ui-button-icons-only { width: 3.7em; } + +/*button text element */ +.ui-button .ui-button-text { display: block; line-height: 1.4; } +.ui-button-text-only .ui-button-text { padding: .4em 1em; } +.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } +.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } +.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } +.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } +/* no icon support for input elements, provide padding by default */ +input.ui-button { padding: .4em 1em; } + +/*button icon element(s) */ +.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } +.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } +.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } +.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } +.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } + +/*button sets*/ +.ui-buttonset { margin-right: 7px; } +.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } + +/* workarounds */ +button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */ + +.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } +.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; } +.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; } +.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } +.ui-datepicker .ui-datepicker-prev { left:2px; } +.ui-datepicker .ui-datepicker-next { right:2px; } +.ui-datepicker .ui-datepicker-prev-hover { left:1px; } +.ui-datepicker .ui-datepicker-next-hover { right:1px; } +.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } +.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } +.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; } +.ui-datepicker select.ui-datepicker-month-year {width: 100%;} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { width: 49%;} +.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; } +.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } +.ui-datepicker td { border: 0; padding: 1px; } +.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } +.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } +.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; } + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { width:auto; } +.ui-datepicker-multi .ui-datepicker-group { float:left; } +.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; } +.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; } +.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; } +.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; } +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; } +.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; } + +/* RTL support */ +.ui-datepicker-rtl { direction: rtl; } +.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; } +.ui-datepicker-rtl .ui-datepicker-group { float:right; } +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; } +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; } + +/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ +.ui-datepicker-cover { + display: none; /*sorry for IE5*/ + display/**/: block; /*sorry for IE5*/ + position: absolute; /*must have*/ + z-index: -1; /*must have*/ + filter: mask(); /*must have*/ + top: -4px; /*must have*/ + left: -4px; /*must have*/ + width: 200px; /*must have*/ + height: 200px; /*must have*/ +} +.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } +.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } +.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } +.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; } +.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } +.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; } +.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; } +.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } +.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } +.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } +.ui-draggable .ui-dialog-titlebar { cursor: move; } + +.ui-progressbar { height:2em; text-align: left; overflow: hidden; } +.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; } +.ui-resizable { position: relative;} +.ui-resizable-handle { position: absolute;font-size: 0.1px; display: block; } +.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } +.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } +.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } +.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } +.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } +.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } +.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } +.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } +.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;} +.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; } + +.ui-slider { position: relative; text-align: left; } +.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } +.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } + +.ui-slider-horizontal { height: .8em; } +.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } +.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } +.ui-slider-horizontal .ui-slider-range-min { left: 0; } +.ui-slider-horizontal .ui-slider-range-max { right: 0; } + +.ui-slider-vertical { width: .8em; height: 100px; } +.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } +.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } +.ui-slider-vertical .ui-slider-range-min { bottom: 0; } +.ui-slider-vertical .ui-slider-range-max { top: 0; } +.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ +.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } +.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; } +.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; } +.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ +.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } +.ui-tabs .ui-tabs-hide { display: none !important; } + +/* Component containers +----------------------------------*/ +.ui-widget { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1.1em/*{fsDefault}*/; } +.ui-widget .ui-widget { font-size: 1em; } +.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1em; } +.ui-widget-content { border: 1px solid #aaaaaa/*{borderColorContent}*/; background: #ffffff/*{bgColorContent}*/ url(images/ui-bg_flat_75_ffffff_40x100.png)/*{bgImgUrlContent}*/ 50%/*{bgContentXPos}*/ 50%/*{bgContentYPos}*/ repeat-x/*{bgContentRepeat}*/; color: #222222/*{fcContent}*/; } +.ui-widget-content a { color: #222222/*{fcContent}*/; } +.ui-widget-header { border: 1px solid #aaaaaa/*{borderColorHeader}*/; background: #cccccc/*{bgColorHeader}*/ url(images/ui-bg_highlight-soft_75_cccccc_1x100.png)/*{bgImgUrlHeader}*/ 50%/*{bgHeaderXPos}*/ 50%/*{bgHeaderYPos}*/ repeat-x/*{bgHeaderRepeat}*/; color: #222222/*{fcHeader}*/; font-weight: bold; } +.ui-widget-header a { color: #222222/*{fcHeader}*/; } + +/* Interaction states +----------------------------------*/ +.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #d3d3d3/*{borderColorDefault}*/; background: #e6e6e6/*{bgColorDefault}*/ url(images/ui-bg_glass_75_e6e6e6_1x400.png)/*{bgImgUrlDefault}*/ 50%/*{bgDefaultXPos}*/ 50%/*{bgDefaultYPos}*/ repeat-x/*{bgDefaultRepeat}*/; font-weight: normal/*{fwDefault}*/; color: #555555/*{fcDefault}*/; } +.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555/*{fcDefault}*/; text-decoration: none; } +.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #999999/*{borderColorHover}*/; background: #dadada/*{bgColorHover}*/ url(images/ui-bg_glass_75_dadada_1x400.png)/*{bgImgUrlHover}*/ 50%/*{bgHoverXPos}*/ 50%/*{bgHoverYPos}*/ repeat-x/*{bgHoverRepeat}*/; font-weight: normal/*{fwDefault}*/; color: #212121/*{fcHover}*/; } +.ui-state-hover a, .ui-state-hover a:hover { color: #212121/*{fcHover}*/; text-decoration: none; } +.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #aaaaaa/*{borderColorActive}*/; background: #ffffff/*{bgColorActive}*/ url(images/ui-bg_glass_65_ffffff_1x400.png)/*{bgImgUrlActive}*/ 50%/*{bgActiveXPos}*/ 50%/*{bgActiveYPos}*/ repeat-x/*{bgActiveRepeat}*/; font-weight: normal/*{fwDefault}*/; color: #212121/*{fcActive}*/; } +.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #212121/*{fcActive}*/; text-decoration: none; } +.ui-widget :active { outline: none; } + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #fcefa1/*{borderColorHighlight}*/; background: #fbf9ee/*{bgColorHighlight}*/ url(images/ui-bg_glass_55_fbf9ee_1x400.png)/*{bgImgUrlHighlight}*/ 50%/*{bgHighlightXPos}*/ 50%/*{bgHighlightYPos}*/ repeat-x/*{bgHighlightRepeat}*/; color: #363636/*{fcHighlight}*/; } +.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636/*{fcHighlight}*/; } +.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a/*{borderColorError}*/; background: #fef1ec/*{bgColorError}*/ url(images/ui-bg_glass_95_fef1ec_1x400.png)/*{bgImgUrlError}*/ 50%/*{bgErrorXPos}*/ 50%/*{bgErrorYPos}*/ repeat-x/*{bgErrorRepeat}*/; color: #cd0a0a/*{fcError}*/; } +.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a/*{fcError}*/; } +.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a/*{fcError}*/; } +.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } +.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } +.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png)/*{iconsContent}*/; } +.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png)/*{iconsContent}*/; } +.ui-widget-header .ui-icon {background-image: url(images/ui-icons_222222_256x240.png)/*{iconsHeader}*/; } +.ui-state-default .ui-icon { background-image: url(images/ui-icons_888888_256x240.png)/*{iconsDefault}*/; } +.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_454545_256x240.png)/*{iconsHover}*/; } +.ui-state-active .ui-icon {background-image: url(images/ui-icons_454545_256x240.png)/*{iconsActive}*/; } +.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png)/*{iconsHighlight}*/; } +.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_cd0a0a_256x240.png)/*{iconsError}*/; } + +/* positioning */ +.ui-icon-carat-1-n { background-position: 0 0; } +.ui-icon-carat-1-ne { background-position: -16px 0; } +.ui-icon-carat-1-e { background-position: -32px 0; } +.ui-icon-carat-1-se { background-position: -48px 0; } +.ui-icon-carat-1-s { background-position: -64px 0; } +.ui-icon-carat-1-sw { background-position: -80px 0; } +.ui-icon-carat-1-w { background-position: -96px 0; } +.ui-icon-carat-1-nw { background-position: -112px 0; } +.ui-icon-carat-2-n-s { background-position: -128px 0; } +.ui-icon-carat-2-e-w { background-position: -144px 0; } +.ui-icon-triangle-1-n { background-position: 0 -16px; } +.ui-icon-triangle-1-ne { background-position: -16px -16px; } +.ui-icon-triangle-1-e { background-position: -32px -16px; } +.ui-icon-triangle-1-se { background-position: -48px -16px; } +.ui-icon-triangle-1-s { background-position: -64px -16px; } +.ui-icon-triangle-1-sw { background-position: -80px -16px; } +.ui-icon-triangle-1-w { background-position: -96px -16px; } +.ui-icon-triangle-1-nw { background-position: -112px -16px; } +.ui-icon-triangle-2-n-s { background-position: -128px -16px; } +.ui-icon-triangle-2-e-w { background-position: -144px -16px; } +.ui-icon-arrow-1-n { background-position: 0 -32px; } +.ui-icon-arrow-1-ne { background-position: -16px -32px; } +.ui-icon-arrow-1-e { background-position: -32px -32px; } +.ui-icon-arrow-1-se { background-position: -48px -32px; } +.ui-icon-arrow-1-s { background-position: -64px -32px; } +.ui-icon-arrow-1-sw { background-position: -80px -32px; } +.ui-icon-arrow-1-w { background-position: -96px -32px; } +.ui-icon-arrow-1-nw { background-position: -112px -32px; } +.ui-icon-arrow-2-n-s { background-position: -128px -32px; } +.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } +.ui-icon-arrow-2-e-w { background-position: -160px -32px; } +.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } +.ui-icon-arrowstop-1-n { background-position: -192px -32px; } +.ui-icon-arrowstop-1-e { background-position: -208px -32px; } +.ui-icon-arrowstop-1-s { background-position: -224px -32px; } +.ui-icon-arrowstop-1-w { background-position: -240px -32px; } +.ui-icon-arrowthick-1-n { background-position: 0 -48px; } +.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } +.ui-icon-arrowthick-1-e { background-position: -32px -48px; } +.ui-icon-arrowthick-1-se { background-position: -48px -48px; } +.ui-icon-arrowthick-1-s { background-position: -64px -48px; } +.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } +.ui-icon-arrowthick-1-w { background-position: -96px -48px; } +.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } +.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } +.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } +.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } +.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } +.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } +.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } +.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } +.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } +.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } +.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } +.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } +.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } +.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } +.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } +.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } +.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } +.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } +.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } +.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } +.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } +.ui-icon-arrow-4 { background-position: 0 -80px; } +.ui-icon-arrow-4-diag { background-position: -16px -80px; } +.ui-icon-extlink { background-position: -32px -80px; } +.ui-icon-newwin { background-position: -48px -80px; } +.ui-icon-refresh { background-position: -64px -80px; } +.ui-icon-shuffle { background-position: -80px -80px; } +.ui-icon-transfer-e-w { background-position: -96px -80px; } +.ui-icon-transferthick-e-w { background-position: -112px -80px; } +.ui-icon-folder-collapsed { background-position: 0 -96px; } +.ui-icon-folder-open { background-position: -16px -96px; } +.ui-icon-document { background-position: -32px -96px; } +.ui-icon-document-b { background-position: -48px -96px; } +.ui-icon-note { background-position: -64px -96px; } +.ui-icon-mail-closed { background-position: -80px -96px; } +.ui-icon-mail-open { background-position: -96px -96px; } +.ui-icon-suitcase { background-position: -112px -96px; } +.ui-icon-comment { background-position: -128px -96px; } +.ui-icon-person { background-position: -144px -96px; } +.ui-icon-print { background-position: -160px -96px; } +.ui-icon-trash { background-position: -176px -96px; } +.ui-icon-locked { background-position: -192px -96px; } +.ui-icon-unlocked { background-position: -208px -96px; } +.ui-icon-bookmark { background-position: -224px -96px; } +.ui-icon-tag { background-position: -240px -96px; } +.ui-icon-home { background-position: 0 -112px; } +.ui-icon-flag { background-position: -16px -112px; } +.ui-icon-calendar { background-position: -32px -112px; } +.ui-icon-cart { background-position: -48px -112px; } +.ui-icon-pencil { background-position: -64px -112px; } +.ui-icon-clock { background-position: -80px -112px; } +.ui-icon-disk { background-position: -96px -112px; } +.ui-icon-calculator { background-position: -112px -112px; } +.ui-icon-zoomin { background-position: -128px -112px; } +.ui-icon-zoomout { background-position: -144px -112px; } +.ui-icon-search { background-position: -160px -112px; } +.ui-icon-wrench { background-position: -176px -112px; } +.ui-icon-gear { background-position: -192px -112px; } +.ui-icon-heart { background-position: -208px -112px; } +.ui-icon-star { background-position: -224px -112px; } +.ui-icon-link { background-position: -240px -112px; } +.ui-icon-cancel { background-position: 0 -128px; } +.ui-icon-plus { background-position: -16px -128px; } +.ui-icon-plusthick { background-position: -32px -128px; } +.ui-icon-minus { background-position: -48px -128px; } +.ui-icon-minusthick { background-position: -64px -128px; } +.ui-icon-close { background-position: -80px -128px; } +.ui-icon-closethick { background-position: -96px -128px; } +.ui-icon-key { background-position: -112px -128px; } +.ui-icon-lightbulb { background-position: -128px -128px; } +.ui-icon-scissors { background-position: -144px -128px; } +.ui-icon-clipboard { background-position: -160px -128px; } +.ui-icon-copy { background-position: -176px -128px; } +.ui-icon-contact { background-position: -192px -128px; } +.ui-icon-image { background-position: -208px -128px; } +.ui-icon-video { background-position: -224px -128px; } +.ui-icon-script { background-position: -240px -128px; } +.ui-icon-alert { background-position: 0 -144px; } +.ui-icon-info { background-position: -16px -144px; } +.ui-icon-notice { background-position: -32px -144px; } +.ui-icon-help { background-position: -48px -144px; } +.ui-icon-check { background-position: -64px -144px; } +.ui-icon-bullet { background-position: -80px -144px; } +.ui-icon-radio-off { background-position: -96px -144px; } +.ui-icon-radio-on { background-position: -112px -144px; } +.ui-icon-pin-w { background-position: -128px -144px; } +.ui-icon-pin-s { background-position: -144px -144px; } +.ui-icon-play { background-position: 0 -160px; } +.ui-icon-pause { background-position: -16px -160px; } +.ui-icon-seek-next { background-position: -32px -160px; } +.ui-icon-seek-prev { background-position: -48px -160px; } +.ui-icon-seek-end { background-position: -64px -160px; } +.ui-icon-seek-start { background-position: -80px -160px; } +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { background-position: -80px -160px; } +.ui-icon-stop { background-position: -96px -160px; } +.ui-icon-eject { background-position: -112px -160px; } +.ui-icon-volume-off { background-position: -128px -160px; } +.ui-icon-volume-on { background-position: -144px -160px; } +.ui-icon-power { background-position: 0 -176px; } +.ui-icon-signal-diag { background-position: -16px -176px; } +.ui-icon-signal { background-position: -32px -176px; } +.ui-icon-battery-0 { background-position: -48px -176px; } +.ui-icon-battery-1 { background-position: -64px -176px; } +.ui-icon-battery-2 { background-position: -80px -176px; } +.ui-icon-battery-3 { background-position: -96px -176px; } +.ui-icon-circle-plus { background-position: 0 -192px; } +.ui-icon-circle-minus { background-position: -16px -192px; } +.ui-icon-circle-close { background-position: -32px -192px; } +.ui-icon-circle-triangle-e { background-position: -48px -192px; } +.ui-icon-circle-triangle-s { background-position: -64px -192px; } +.ui-icon-circle-triangle-w { background-position: -80px -192px; } +.ui-icon-circle-triangle-n { background-position: -96px -192px; } +.ui-icon-circle-arrow-e { background-position: -112px -192px; } +.ui-icon-circle-arrow-s { background-position: -128px -192px; } +.ui-icon-circle-arrow-w { background-position: -144px -192px; } +.ui-icon-circle-arrow-n { background-position: -160px -192px; } +.ui-icon-circle-zoomin { background-position: -176px -192px; } +.ui-icon-circle-zoomout { background-position: -192px -192px; } +.ui-icon-circle-check { background-position: -208px -192px; } +.ui-icon-circlesmall-plus { background-position: 0 -208px; } +.ui-icon-circlesmall-minus { background-position: -16px -208px; } +.ui-icon-circlesmall-close { background-position: -32px -208px; } +.ui-icon-squaresmall-plus { background-position: -48px -208px; } +.ui-icon-squaresmall-minus { background-position: -64px -208px; } +.ui-icon-squaresmall-close { background-position: -80px -208px; } +.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } +.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } +.ui-icon-grip-solid-vertical { background-position: -32px -224px; } +.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } +.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } +.ui-icon-grip-diagonal-se { background-position: -80px -224px; } + + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px/*{cornerRadius}*/; -webkit-border-top-left-radius: 4px/*{cornerRadius}*/; -khtml-border-top-left-radius: 4px/*{cornerRadius}*/; border-top-left-radius: 4px/*{cornerRadius}*/; } +.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px/*{cornerRadius}*/; -webkit-border-top-right-radius: 4px/*{cornerRadius}*/; -khtml-border-top-right-radius: 4px/*{cornerRadius}*/; border-top-right-radius: 4px/*{cornerRadius}*/; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px/*{cornerRadius}*/; -webkit-border-bottom-left-radius: 4px/*{cornerRadius}*/; -khtml-border-bottom-left-radius: 4px/*{cornerRadius}*/; border-bottom-left-radius: 4px/*{cornerRadius}*/; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px/*{cornerRadius}*/; -webkit-border-bottom-right-radius: 4px/*{cornerRadius}*/; -khtml-border-bottom-right-radius: 4px/*{cornerRadius}*/; border-bottom-right-radius: 4px/*{cornerRadius}*/; } + +/* Overlays */ +.ui-widget-overlay { background: #aaaaaa/*{bgColorOverlay}*/ url(images/ui-bg_flat_0_aaaaaa_40x100.png)/*{bgImgUrlOverlay}*/ 50%/*{bgOverlayXPos}*/ 50%/*{bgOverlayYPos}*/ repeat-x/*{bgOverlayRepeat}*/; opacity: .3;filter:Alpha(Opacity=30)/*{opacityOverlay}*/; } +.ui-widget-shadow { margin: -8px/*{offsetTopShadow}*/ 0 0 -8px/*{offsetLeftShadow}*/; padding: 8px/*{thicknessShadow}*/; background: #aaaaaa/*{bgColorShadow}*/ url(images/ui-bg_flat_0_aaaaaa_40x100.png)/*{bgImgUrlShadow}*/ 50%/*{bgShadowXPos}*/ 50%/*{bgShadowYPos}*/ repeat-x/*{bgShadowRepeat}*/; opacity: .3;filter:Alpha(Opacity=30)/*{opacityShadow}*/; -moz-border-radius: 8px/*{cornerRadiusShadow}*/; -khtml-border-radius: 8px/*{cornerRadiusShadow}*/; -webkit-border-radius: 8px/*{cornerRadiusShadow}*/; border-radius: 8px/*{cornerRadiusShadow}*/; }
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.accordion.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.accordion.css new file mode 100644 index 0000000..5198833 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.accordion.css @@ -0,0 +1,19 @@ +/*! + * jQuery UI Accordion 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Accordion#theming + */ +/* IE/Win - Fix animation bug - #4615 */ +.ui-accordion { width: 100%; } +.ui-accordion .ui-accordion-header { cursor: pointer; position: relative; margin-top: 1px; zoom: 1; } +.ui-accordion .ui-accordion-li-fix { display: inline; } +.ui-accordion .ui-accordion-header-active { border-bottom: 0 !important; } +.ui-accordion .ui-accordion-header a { display: block; font-size: 1em; padding: .5em .5em .5em .7em; } +.ui-accordion-icons .ui-accordion-header a { padding-left: 2.2em; } +.ui-accordion .ui-accordion-header .ui-icon { position: absolute; left: .5em; top: 50%; margin-top: -8px; } +.ui-accordion .ui-accordion-content { padding: 1em 2.2em; border-top: 0; margin-top: -2px; position: relative; top: 1px; margin-bottom: 2px; overflow: auto; display: none; zoom: 1; } +.ui-accordion .ui-accordion-content-active { display: block; } diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.all.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.all.css new file mode 100644 index 0000000..af6d2ce --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.all.css @@ -0,0 +1,11 @@ +/*! + * jQuery UI CSS Framework 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming + */ +@import "jquery.ui.base.css"; +@import "jquery.ui.theme.css"; diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.autocomplete.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.autocomplete.css new file mode 100644 index 0000000..56a7710 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.autocomplete.css @@ -0,0 +1,53 @@ +/*! + * jQuery UI Autocomplete 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Autocomplete#theming + */ +.ui-autocomplete { position: absolute; cursor: default; } + +/* workarounds */ +* html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ + +/* + * jQuery UI Menu 1.8.20 + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Menu#theming + */ +.ui-menu { + list-style:none; + padding: 2px; + margin: 0; + display:block; + float: left; +} +.ui-menu .ui-menu { + margin-top: -3px; +} +.ui-menu .ui-menu-item { + margin:0; + padding: 0; + zoom: 1; + float: left; + clear: left; + width: 100%; +} +.ui-menu .ui-menu-item a { + text-decoration:none; + display:block; + padding:.2em .4em; + line-height:1.5; + zoom:1; +} +.ui-menu .ui-menu-item a.ui-state-hover, +.ui-menu .ui-menu-item a.ui-state-active { + font-weight: normal; + margin: -1px; +} diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.base.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.base.css new file mode 100644 index 0000000..49775ee --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.base.css @@ -0,0 +1,21 @@ +/*! + * jQuery UI CSS Framework 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming + */ +@import url("jquery.ui.core.css"); + +@import url("jquery.ui.accordion.css"); +@import url("jquery.ui.autocomplete.css"); +@import url("jquery.ui.button.css"); +@import url("jquery.ui.datepicker.css"); +@import url("jquery.ui.dialog.css"); +@import url("jquery.ui.progressbar.css"); +@import url("jquery.ui.resizable.css"); +@import url("jquery.ui.selectable.css"); +@import url("jquery.ui.slider.css"); +@import url("jquery.ui.tabs.css"); diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.button.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.button.css new file mode 100644 index 0000000..47b8f33 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.button.css @@ -0,0 +1,38 @@ +/*! + * jQuery UI Button 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Button#theming + */ +.ui-button { display: inline-block; position: relative; padding: 0; margin-right: .1em; text-decoration: none !important; cursor: pointer; text-align: center; zoom: 1; overflow: visible; } /* the overflow property removes extra width in IE */ +.ui-button-icon-only { width: 2.2em; } /* to make room for the icon, a width needs to be set here */ +button.ui-button-icon-only { width: 2.4em; } /* button elements seem to need a little more width */ +.ui-button-icons-only { width: 3.4em; } +button.ui-button-icons-only { width: 3.7em; } + +/*button text element */ +.ui-button .ui-button-text { display: block; line-height: 1.4; } +.ui-button-text-only .ui-button-text { padding: .4em 1em; } +.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: .4em; text-indent: -9999999px; } +.ui-button-text-icon-primary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 1em .4em 2.1em; } +.ui-button-text-icon-secondary .ui-button-text, .ui-button-text-icons .ui-button-text { padding: .4em 2.1em .4em 1em; } +.ui-button-text-icons .ui-button-text { padding-left: 2.1em; padding-right: 2.1em; } +/* no icon support for input elements, provide padding by default */ +input.ui-button { padding: .4em 1em; } + +/*button icon element(s) */ +.ui-button-icon-only .ui-icon, .ui-button-text-icon-primary .ui-icon, .ui-button-text-icon-secondary .ui-icon, .ui-button-text-icons .ui-icon, .ui-button-icons-only .ui-icon { position: absolute; top: 50%; margin-top: -8px; } +.ui-button-icon-only .ui-icon { left: 50%; margin-left: -8px; } +.ui-button-text-icon-primary .ui-button-icon-primary, .ui-button-text-icons .ui-button-icon-primary, .ui-button-icons-only .ui-button-icon-primary { left: .5em; } +.ui-button-text-icon-secondary .ui-button-icon-secondary, .ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } +.ui-button-text-icons .ui-button-icon-secondary, .ui-button-icons-only .ui-button-icon-secondary { right: .5em; } + +/*button sets*/ +.ui-buttonset { margin-right: 7px; } +.ui-buttonset .ui-button { margin-left: 0; margin-right: -.3em; } + +/* workarounds */ +button.ui-button::-moz-focus-inner { border: 0; padding: 0; } /* reset extra padding in Firefox */ diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.core.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.core.css new file mode 100644 index 0000000..a622030 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.core.css @@ -0,0 +1,38 @@ +/*! + * jQuery UI CSS Framework 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming/API + */ + +/* Layout helpers +----------------------------------*/ +.ui-helper-hidden { display: none; } +.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } +.ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } +.ui-helper-clearfix:before, .ui-helper-clearfix:after { content: ""; display: table; } +.ui-helper-clearfix:after { clear: both; } +.ui-helper-clearfix { zoom: 1; } +.ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } + + +/* Interaction Cues +----------------------------------*/ +.ui-state-disabled { cursor: default !important; } + + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } + + +/* Misc visuals +----------------------------------*/ + +/* Overlays */ +.ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.datepicker.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.datepicker.css new file mode 100644 index 0000000..11d1e78 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.datepicker.css @@ -0,0 +1,68 @@ +/*! + * jQuery UI Datepicker 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Datepicker#theming + */ +.ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; } +.ui-datepicker .ui-datepicker-header { position:relative; padding:.2em 0; } +.ui-datepicker .ui-datepicker-prev, .ui-datepicker .ui-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; } +.ui-datepicker .ui-datepicker-prev-hover, .ui-datepicker .ui-datepicker-next-hover { top: 1px; } +.ui-datepicker .ui-datepicker-prev { left:2px; } +.ui-datepicker .ui-datepicker-next { right:2px; } +.ui-datepicker .ui-datepicker-prev-hover { left:1px; } +.ui-datepicker .ui-datepicker-next-hover { right:1px; } +.ui-datepicker .ui-datepicker-prev span, .ui-datepicker .ui-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px; } +.ui-datepicker .ui-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; } +.ui-datepicker .ui-datepicker-title select { font-size:1em; margin:1px 0; } +.ui-datepicker select.ui-datepicker-month-year {width: 100%;} +.ui-datepicker select.ui-datepicker-month, +.ui-datepicker select.ui-datepicker-year { width: 49%;} +.ui-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; } +.ui-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0; } +.ui-datepicker td { border: 0; padding: 1px; } +.ui-datepicker td span, .ui-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; } +.ui-datepicker .ui-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; } +.ui-datepicker .ui-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; } +.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { float:left; } + +/* with multiple calendars */ +.ui-datepicker.ui-datepicker-multi { width:auto; } +.ui-datepicker-multi .ui-datepicker-group { float:left; } +.ui-datepicker-multi .ui-datepicker-group table { width:95%; margin:0 auto .4em; } +.ui-datepicker-multi-2 .ui-datepicker-group { width:50%; } +.ui-datepicker-multi-3 .ui-datepicker-group { width:33.3%; } +.ui-datepicker-multi-4 .ui-datepicker-group { width:25%; } +.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { border-left-width:0; } +.ui-datepicker-multi .ui-datepicker-buttonpane { clear:left; } +.ui-datepicker-row-break { clear:both; width:100%; font-size:0em; } + +/* RTL support */ +.ui-datepicker-rtl { direction: rtl; } +.ui-datepicker-rtl .ui-datepicker-prev { right: 2px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next { left: 2px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-prev:hover { right: 1px; left: auto; } +.ui-datepicker-rtl .ui-datepicker-next:hover { left: 1px; right: auto; } +.ui-datepicker-rtl .ui-datepicker-buttonpane { clear:right; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button { float: left; } +.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current { float:right; } +.ui-datepicker-rtl .ui-datepicker-group { float:right; } +.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header { border-right-width:0; border-left-width:1px; } +.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { border-right-width:0; border-left-width:1px; } + +/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */ +.ui-datepicker-cover { + display: none; /*sorry for IE5*/ + display/**/: block; /*sorry for IE5*/ + position: absolute; /*must have*/ + z-index: -1; /*must have*/ + filter: mask(); /*must have*/ + top: -4px; /*must have*/ + left: -4px; /*must have*/ + width: 200px; /*must have*/ + height: 200px; /*must have*/ +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.dialog.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.dialog.css new file mode 100644 index 0000000..ac039f0 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.dialog.css @@ -0,0 +1,21 @@ +/*! + * jQuery UI Dialog 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Dialog#theming + */ +.ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } +.ui-dialog .ui-dialog-titlebar { padding: .4em 1em; position: relative; } +.ui-dialog .ui-dialog-title { float: left; margin: .1em 16px .1em 0; } +.ui-dialog .ui-dialog-titlebar-close { position: absolute; right: .3em; top: 50%; width: 19px; margin: -10px 0 0 0; padding: 1px; height: 18px; } +.ui-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } +.ui-dialog .ui-dialog-titlebar-close:hover, .ui-dialog .ui-dialog-titlebar-close:focus { padding: 0; } +.ui-dialog .ui-dialog-content { position: relative; border: 0; padding: .5em 1em; background: none; overflow: auto; zoom: 1; } +.ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } +.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } +.ui-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } +.ui-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } +.ui-draggable .ui-dialog-titlebar { cursor: move; } diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.progressbar.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.progressbar.css new file mode 100644 index 0000000..f6fc5df --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.progressbar.css @@ -0,0 +1,11 @@ +/*! + * jQuery UI Progressbar 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Progressbar#theming + */ +.ui-progressbar { height:2em; text-align: left; overflow: hidden; } +.ui-progressbar .ui-progressbar-value {margin: -1px; height:100%; }
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.resizable.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.resizable.css new file mode 100644 index 0000000..6a55fe7 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.resizable.css @@ -0,0 +1,20 @@ +/*! + * jQuery UI Resizable 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Resizable#theming + */ +.ui-resizable { position: relative;} +.ui-resizable-handle { position: absolute;font-size: 0.1px; display: block; } +.ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } +.ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } +.ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } +.ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } +.ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } +.ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } +.ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } +.ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } +.ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.selectable.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.selectable.css new file mode 100644 index 0000000..3baebf8 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.selectable.css @@ -0,0 +1,10 @@ +/*! + * jQuery UI Selectable 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Selectable#theming + */ +.ui-selectable-helper { position: absolute; z-index: 100; border:1px dotted black; } diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.slider.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.slider.css new file mode 100644 index 0000000..9b36d77 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.slider.css @@ -0,0 +1,24 @@ +/*! + * jQuery UI Slider 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Slider#theming + */ +.ui-slider { position: relative; text-align: left; } +.ui-slider .ui-slider-handle { position: absolute; z-index: 2; width: 1.2em; height: 1.2em; cursor: default; } +.ui-slider .ui-slider-range { position: absolute; z-index: 1; font-size: .7em; display: block; border: 0; background-position: 0 0; } + +.ui-slider-horizontal { height: .8em; } +.ui-slider-horizontal .ui-slider-handle { top: -.3em; margin-left: -.6em; } +.ui-slider-horizontal .ui-slider-range { top: 0; height: 100%; } +.ui-slider-horizontal .ui-slider-range-min { left: 0; } +.ui-slider-horizontal .ui-slider-range-max { right: 0; } + +.ui-slider-vertical { width: .8em; height: 100px; } +.ui-slider-vertical .ui-slider-handle { left: -.3em; margin-left: 0; margin-bottom: -.6em; } +.ui-slider-vertical .ui-slider-range { left: 0; width: 100%; } +.ui-slider-vertical .ui-slider-range-min { bottom: 0; } +.ui-slider-vertical .ui-slider-range-max { top: 0; }
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.tabs.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.tabs.css new file mode 100644 index 0000000..2e78303 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.tabs.css @@ -0,0 +1,18 @@ +/*! + * jQuery UI Tabs 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Tabs#theming + */ +.ui-tabs { position: relative; padding: .2em; zoom: 1; } /* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ +.ui-tabs .ui-tabs-nav { margin: 0; padding: .2em .2em 0; } +.ui-tabs .ui-tabs-nav li { list-style: none; float: left; position: relative; top: 1px; margin: 0 .2em 1px 0; border-bottom: 0 !important; padding: 0; white-space: nowrap; } +.ui-tabs .ui-tabs-nav li a { float: left; padding: .5em 1em; text-decoration: none; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected { margin-bottom: 0; padding-bottom: 1px; } +.ui-tabs .ui-tabs-nav li.ui-tabs-selected a, .ui-tabs .ui-tabs-nav li.ui-state-disabled a, .ui-tabs .ui-tabs-nav li.ui-state-processing a { cursor: text; } +.ui-tabs .ui-tabs-nav li a, .ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a { cursor: pointer; } /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ +.ui-tabs .ui-tabs-panel { display: block; border-width: 0; padding: 1em 1.4em; background: none; } +.ui-tabs .ui-tabs-hide { display: none !important; } diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.theme.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.theme.css new file mode 100644 index 0000000..a58368a --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/jquery.ui.theme.css @@ -0,0 +1,247 @@ +/*! + * jQuery UI CSS Framework 1.8.20 + * + * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) + * Licensed under the MIT license. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Theming/API + * + * To view and modify this theme, visit http://jqueryui.com/themeroller/ + */ + + +/* Component containers +----------------------------------*/ +.ui-widget { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1.1em/*{fsDefault}*/; } +.ui-widget .ui-widget { font-size: 1em; } +.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: Verdana,Arial,sans-serif/*{ffDefault}*/; font-size: 1em; } +.ui-widget-content { border: 1px solid #aaaaaa/*{borderColorContent}*/; background: #ffffff/*{bgColorContent}*/ url(images/ui-bg_flat_75_ffffff_40x100.png)/*{bgImgUrlContent}*/ 50%/*{bgContentXPos}*/ 50%/*{bgContentYPos}*/ repeat-x/*{bgContentRepeat}*/; color: #222222/*{fcContent}*/; } +.ui-widget-content a { color: #222222/*{fcContent}*/; } +.ui-widget-header { border: 1px solid #aaaaaa/*{borderColorHeader}*/; background: #cccccc/*{bgColorHeader}*/ url(images/ui-bg_highlight-soft_75_cccccc_1x100.png)/*{bgImgUrlHeader}*/ 50%/*{bgHeaderXPos}*/ 50%/*{bgHeaderYPos}*/ repeat-x/*{bgHeaderRepeat}*/; color: #222222/*{fcHeader}*/; font-weight: bold; } +.ui-widget-header a { color: #222222/*{fcHeader}*/; } + +/* Interaction states +----------------------------------*/ +.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #d3d3d3/*{borderColorDefault}*/; background: #e6e6e6/*{bgColorDefault}*/ url(images/ui-bg_glass_75_e6e6e6_1x400.png)/*{bgImgUrlDefault}*/ 50%/*{bgDefaultXPos}*/ 50%/*{bgDefaultYPos}*/ repeat-x/*{bgDefaultRepeat}*/; font-weight: normal/*{fwDefault}*/; color: #555555/*{fcDefault}*/; } +.ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited { color: #555555/*{fcDefault}*/; text-decoration: none; } +.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus { border: 1px solid #999999/*{borderColorHover}*/; background: #dadada/*{bgColorHover}*/ url(images/ui-bg_glass_75_dadada_1x400.png)/*{bgImgUrlHover}*/ 50%/*{bgHoverXPos}*/ 50%/*{bgHoverYPos}*/ repeat-x/*{bgHoverRepeat}*/; font-weight: normal/*{fwDefault}*/; color: #212121/*{fcHover}*/; } +.ui-state-hover a, .ui-state-hover a:hover { color: #212121/*{fcHover}*/; text-decoration: none; } +.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { border: 1px solid #aaaaaa/*{borderColorActive}*/; background: #ffffff/*{bgColorActive}*/ url(images/ui-bg_glass_65_ffffff_1x400.png)/*{bgImgUrlActive}*/ 50%/*{bgActiveXPos}*/ 50%/*{bgActiveYPos}*/ repeat-x/*{bgActiveRepeat}*/; font-weight: normal/*{fwDefault}*/; color: #212121/*{fcActive}*/; } +.ui-state-active a, .ui-state-active a:link, .ui-state-active a:visited { color: #212121/*{fcActive}*/; text-decoration: none; } +.ui-widget :active { outline: none; } + +/* Interaction Cues +----------------------------------*/ +.ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-widget-header .ui-state-highlight {border: 1px solid #fcefa1/*{borderColorHighlight}*/; background: #fbf9ee/*{bgColorHighlight}*/ url(images/ui-bg_glass_55_fbf9ee_1x400.png)/*{bgImgUrlHighlight}*/ 50%/*{bgHighlightXPos}*/ 50%/*{bgHighlightYPos}*/ repeat-x/*{bgHighlightRepeat}*/; color: #363636/*{fcHighlight}*/; } +.ui-state-highlight a, .ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a { color: #363636/*{fcHighlight}*/; } +.ui-state-error, .ui-widget-content .ui-state-error, .ui-widget-header .ui-state-error {border: 1px solid #cd0a0a/*{borderColorError}*/; background: #fef1ec/*{bgColorError}*/ url(images/ui-bg_glass_95_fef1ec_1x400.png)/*{bgImgUrlError}*/ 50%/*{bgErrorXPos}*/ 50%/*{bgErrorYPos}*/ repeat-x/*{bgErrorRepeat}*/; color: #cd0a0a/*{fcError}*/; } +.ui-state-error a, .ui-widget-content .ui-state-error a, .ui-widget-header .ui-state-error a { color: #cd0a0a/*{fcError}*/; } +.ui-state-error-text, .ui-widget-content .ui-state-error-text, .ui-widget-header .ui-state-error-text { color: #cd0a0a/*{fcError}*/; } +.ui-priority-primary, .ui-widget-content .ui-priority-primary, .ui-widget-header .ui-priority-primary { font-weight: bold; } +.ui-priority-secondary, .ui-widget-content .ui-priority-secondary, .ui-widget-header .ui-priority-secondary { opacity: .7; filter:Alpha(Opacity=70); font-weight: normal; } +.ui-state-disabled, .ui-widget-content .ui-state-disabled, .ui-widget-header .ui-state-disabled { opacity: .35; filter:Alpha(Opacity=35); background-image: none; } + +/* Icons +----------------------------------*/ + +/* states and images */ +.ui-icon { width: 16px; height: 16px; background-image: url(images/ui-icons_222222_256x240.png)/*{iconsContent}*/; } +.ui-widget-content .ui-icon {background-image: url(images/ui-icons_222222_256x240.png)/*{iconsContent}*/; } +.ui-widget-header .ui-icon {background-image: url(images/ui-icons_222222_256x240.png)/*{iconsHeader}*/; } +.ui-state-default .ui-icon { background-image: url(images/ui-icons_888888_256x240.png)/*{iconsDefault}*/; } +.ui-state-hover .ui-icon, .ui-state-focus .ui-icon {background-image: url(images/ui-icons_454545_256x240.png)/*{iconsHover}*/; } +.ui-state-active .ui-icon {background-image: url(images/ui-icons_454545_256x240.png)/*{iconsActive}*/; } +.ui-state-highlight .ui-icon {background-image: url(images/ui-icons_2e83ff_256x240.png)/*{iconsHighlight}*/; } +.ui-state-error .ui-icon, .ui-state-error-text .ui-icon {background-image: url(images/ui-icons_cd0a0a_256x240.png)/*{iconsError}*/; } + +/* positioning */ +.ui-icon-carat-1-n { background-position: 0 0; } +.ui-icon-carat-1-ne { background-position: -16px 0; } +.ui-icon-carat-1-e { background-position: -32px 0; } +.ui-icon-carat-1-se { background-position: -48px 0; } +.ui-icon-carat-1-s { background-position: -64px 0; } +.ui-icon-carat-1-sw { background-position: -80px 0; } +.ui-icon-carat-1-w { background-position: -96px 0; } +.ui-icon-carat-1-nw { background-position: -112px 0; } +.ui-icon-carat-2-n-s { background-position: -128px 0; } +.ui-icon-carat-2-e-w { background-position: -144px 0; } +.ui-icon-triangle-1-n { background-position: 0 -16px; } +.ui-icon-triangle-1-ne { background-position: -16px -16px; } +.ui-icon-triangle-1-e { background-position: -32px -16px; } +.ui-icon-triangle-1-se { background-position: -48px -16px; } +.ui-icon-triangle-1-s { background-position: -64px -16px; } +.ui-icon-triangle-1-sw { background-position: -80px -16px; } +.ui-icon-triangle-1-w { background-position: -96px -16px; } +.ui-icon-triangle-1-nw { background-position: -112px -16px; } +.ui-icon-triangle-2-n-s { background-position: -128px -16px; } +.ui-icon-triangle-2-e-w { background-position: -144px -16px; } +.ui-icon-arrow-1-n { background-position: 0 -32px; } +.ui-icon-arrow-1-ne { background-position: -16px -32px; } +.ui-icon-arrow-1-e { background-position: -32px -32px; } +.ui-icon-arrow-1-se { background-position: -48px -32px; } +.ui-icon-arrow-1-s { background-position: -64px -32px; } +.ui-icon-arrow-1-sw { background-position: -80px -32px; } +.ui-icon-arrow-1-w { background-position: -96px -32px; } +.ui-icon-arrow-1-nw { background-position: -112px -32px; } +.ui-icon-arrow-2-n-s { background-position: -128px -32px; } +.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } +.ui-icon-arrow-2-e-w { background-position: -160px -32px; } +.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } +.ui-icon-arrowstop-1-n { background-position: -192px -32px; } +.ui-icon-arrowstop-1-e { background-position: -208px -32px; } +.ui-icon-arrowstop-1-s { background-position: -224px -32px; } +.ui-icon-arrowstop-1-w { background-position: -240px -32px; } +.ui-icon-arrowthick-1-n { background-position: 0 -48px; } +.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } +.ui-icon-arrowthick-1-e { background-position: -32px -48px; } +.ui-icon-arrowthick-1-se { background-position: -48px -48px; } +.ui-icon-arrowthick-1-s { background-position: -64px -48px; } +.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } +.ui-icon-arrowthick-1-w { background-position: -96px -48px; } +.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } +.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } +.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } +.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } +.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } +.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } +.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } +.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } +.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } +.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } +.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } +.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } +.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } +.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } +.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } +.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } +.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } +.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } +.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } +.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } +.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } +.ui-icon-arrow-4 { background-position: 0 -80px; } +.ui-icon-arrow-4-diag { background-position: -16px -80px; } +.ui-icon-extlink { background-position: -32px -80px; } +.ui-icon-newwin { background-position: -48px -80px; } +.ui-icon-refresh { background-position: -64px -80px; } +.ui-icon-shuffle { background-position: -80px -80px; } +.ui-icon-transfer-e-w { background-position: -96px -80px; } +.ui-icon-transferthick-e-w { background-position: -112px -80px; } +.ui-icon-folder-collapsed { background-position: 0 -96px; } +.ui-icon-folder-open { background-position: -16px -96px; } +.ui-icon-document { background-position: -32px -96px; } +.ui-icon-document-b { background-position: -48px -96px; } +.ui-icon-note { background-position: -64px -96px; } +.ui-icon-mail-closed { background-position: -80px -96px; } +.ui-icon-mail-open { background-position: -96px -96px; } +.ui-icon-suitcase { background-position: -112px -96px; } +.ui-icon-comment { background-position: -128px -96px; } +.ui-icon-person { background-position: -144px -96px; } +.ui-icon-print { background-position: -160px -96px; } +.ui-icon-trash { background-position: -176px -96px; } +.ui-icon-locked { background-position: -192px -96px; } +.ui-icon-unlocked { background-position: -208px -96px; } +.ui-icon-bookmark { background-position: -224px -96px; } +.ui-icon-tag { background-position: -240px -96px; } +.ui-icon-home { background-position: 0 -112px; } +.ui-icon-flag { background-position: -16px -112px; } +.ui-icon-calendar { background-position: -32px -112px; } +.ui-icon-cart { background-position: -48px -112px; } +.ui-icon-pencil { background-position: -64px -112px; } +.ui-icon-clock { background-position: -80px -112px; } +.ui-icon-disk { background-position: -96px -112px; } +.ui-icon-calculator { background-position: -112px -112px; } +.ui-icon-zoomin { background-position: -128px -112px; } +.ui-icon-zoomout { background-position: -144px -112px; } +.ui-icon-search { background-position: -160px -112px; } +.ui-icon-wrench { background-position: -176px -112px; } +.ui-icon-gear { background-position: -192px -112px; } +.ui-icon-heart { background-position: -208px -112px; } +.ui-icon-star { background-position: -224px -112px; } +.ui-icon-link { background-position: -240px -112px; } +.ui-icon-cancel { background-position: 0 -128px; } +.ui-icon-plus { background-position: -16px -128px; } +.ui-icon-plusthick { background-position: -32px -128px; } +.ui-icon-minus { background-position: -48px -128px; } +.ui-icon-minusthick { background-position: -64px -128px; } +.ui-icon-close { background-position: -80px -128px; } +.ui-icon-closethick { background-position: -96px -128px; } +.ui-icon-key { background-position: -112px -128px; } +.ui-icon-lightbulb { background-position: -128px -128px; } +.ui-icon-scissors { background-position: -144px -128px; } +.ui-icon-clipboard { background-position: -160px -128px; } +.ui-icon-copy { background-position: -176px -128px; } +.ui-icon-contact { background-position: -192px -128px; } +.ui-icon-image { background-position: -208px -128px; } +.ui-icon-video { background-position: -224px -128px; } +.ui-icon-script { background-position: -240px -128px; } +.ui-icon-alert { background-position: 0 -144px; } +.ui-icon-info { background-position: -16px -144px; } +.ui-icon-notice { background-position: -32px -144px; } +.ui-icon-help { background-position: -48px -144px; } +.ui-icon-check { background-position: -64px -144px; } +.ui-icon-bullet { background-position: -80px -144px; } +.ui-icon-radio-off { background-position: -96px -144px; } +.ui-icon-radio-on { background-position: -112px -144px; } +.ui-icon-pin-w { background-position: -128px -144px; } +.ui-icon-pin-s { background-position: -144px -144px; } +.ui-icon-play { background-position: 0 -160px; } +.ui-icon-pause { background-position: -16px -160px; } +.ui-icon-seek-next { background-position: -32px -160px; } +.ui-icon-seek-prev { background-position: -48px -160px; } +.ui-icon-seek-end { background-position: -64px -160px; } +.ui-icon-seek-start { background-position: -80px -160px; } +/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ +.ui-icon-seek-first { background-position: -80px -160px; } +.ui-icon-stop { background-position: -96px -160px; } +.ui-icon-eject { background-position: -112px -160px; } +.ui-icon-volume-off { background-position: -128px -160px; } +.ui-icon-volume-on { background-position: -144px -160px; } +.ui-icon-power { background-position: 0 -176px; } +.ui-icon-signal-diag { background-position: -16px -176px; } +.ui-icon-signal { background-position: -32px -176px; } +.ui-icon-battery-0 { background-position: -48px -176px; } +.ui-icon-battery-1 { background-position: -64px -176px; } +.ui-icon-battery-2 { background-position: -80px -176px; } +.ui-icon-battery-3 { background-position: -96px -176px; } +.ui-icon-circle-plus { background-position: 0 -192px; } +.ui-icon-circle-minus { background-position: -16px -192px; } +.ui-icon-circle-close { background-position: -32px -192px; } +.ui-icon-circle-triangle-e { background-position: -48px -192px; } +.ui-icon-circle-triangle-s { background-position: -64px -192px; } +.ui-icon-circle-triangle-w { background-position: -80px -192px; } +.ui-icon-circle-triangle-n { background-position: -96px -192px; } +.ui-icon-circle-arrow-e { background-position: -112px -192px; } +.ui-icon-circle-arrow-s { background-position: -128px -192px; } +.ui-icon-circle-arrow-w { background-position: -144px -192px; } +.ui-icon-circle-arrow-n { background-position: -160px -192px; } +.ui-icon-circle-zoomin { background-position: -176px -192px; } +.ui-icon-circle-zoomout { background-position: -192px -192px; } +.ui-icon-circle-check { background-position: -208px -192px; } +.ui-icon-circlesmall-plus { background-position: 0 -208px; } +.ui-icon-circlesmall-minus { background-position: -16px -208px; } +.ui-icon-circlesmall-close { background-position: -32px -208px; } +.ui-icon-squaresmall-plus { background-position: -48px -208px; } +.ui-icon-squaresmall-minus { background-position: -64px -208px; } +.ui-icon-squaresmall-close { background-position: -80px -208px; } +.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } +.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } +.ui-icon-grip-solid-vertical { background-position: -32px -224px; } +.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } +.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } +.ui-icon-grip-diagonal-se { background-position: -80px -224px; } + + +/* Misc visuals +----------------------------------*/ + +/* Corner radius */ +.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px/*{cornerRadius}*/; -webkit-border-top-left-radius: 4px/*{cornerRadius}*/; -khtml-border-top-left-radius: 4px/*{cornerRadius}*/; border-top-left-radius: 4px/*{cornerRadius}*/; } +.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr { -moz-border-radius-topright: 4px/*{cornerRadius}*/; -webkit-border-top-right-radius: 4px/*{cornerRadius}*/; -khtml-border-top-right-radius: 4px/*{cornerRadius}*/; border-top-right-radius: 4px/*{cornerRadius}*/; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl { -moz-border-radius-bottomleft: 4px/*{cornerRadius}*/; -webkit-border-bottom-left-radius: 4px/*{cornerRadius}*/; -khtml-border-bottom-left-radius: 4px/*{cornerRadius}*/; border-bottom-left-radius: 4px/*{cornerRadius}*/; } +.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br { -moz-border-radius-bottomright: 4px/*{cornerRadius}*/; -webkit-border-bottom-right-radius: 4px/*{cornerRadius}*/; -khtml-border-bottom-right-radius: 4px/*{cornerRadius}*/; border-bottom-right-radius: 4px/*{cornerRadius}*/; } + +/* Overlays */ +.ui-widget-overlay { background: #aaaaaa/*{bgColorOverlay}*/ url(images/ui-bg_flat_0_aaaaaa_40x100.png)/*{bgImgUrlOverlay}*/ 50%/*{bgOverlayXPos}*/ 50%/*{bgOverlayYPos}*/ repeat-x/*{bgOverlayRepeat}*/; opacity: .3;filter:Alpha(Opacity=30)/*{opacityOverlay}*/; } +.ui-widget-shadow { margin: -8px/*{offsetTopShadow}*/ 0 0 -8px/*{offsetLeftShadow}*/; padding: 8px/*{thicknessShadow}*/; background: #aaaaaa/*{bgColorShadow}*/ url(images/ui-bg_flat_0_aaaaaa_40x100.png)/*{bgImgUrlShadow}*/ 50%/*{bgShadowXPos}*/ 50%/*{bgShadowYPos}*/ repeat-x/*{bgShadowRepeat}*/; opacity: .3;filter:Alpha(Opacity=30)/*{opacityShadow}*/; -moz-border-radius: 8px/*{cornerRadiusShadow}*/; -khtml-border-radius: 8px/*{cornerRadiusShadow}*/; -webkit-border-radius: 8px/*{cornerRadiusShadow}*/; border-radius: 8px/*{cornerRadiusShadow}*/; }
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_flat_0_aaaaaa_40x100.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_flat_0_aaaaaa_40x100.png Binary files differnew file mode 100644 index 0000000..5b5dab2 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_flat_0_aaaaaa_40x100.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_flat_75_ffffff_40x100.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_flat_75_ffffff_40x100.png Binary files differnew file mode 100644 index 0000000..ac8b229 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_flat_75_ffffff_40x100.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_55_fbf9ee_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_55_fbf9ee_1x400.png Binary files differnew file mode 100644 index 0000000..ad3d634 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_55_fbf9ee_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_65_ffffff_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_65_ffffff_1x400.png Binary files differnew file mode 100644 index 0000000..42ccba2 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_65_ffffff_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_75_dadada_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_75_dadada_1x400.png Binary files differnew file mode 100644 index 0000000..5a46b47 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_75_dadada_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_75_e6e6e6_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_75_e6e6e6_1x400.png Binary files differnew file mode 100644 index 0000000..86c2baa --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_75_e6e6e6_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_95_fef1ec_1x400.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_95_fef1ec_1x400.png Binary files differnew file mode 100644 index 0000000..4443fdc --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_glass_95_fef1ec_1x400.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_highlight-soft_75_cccccc_1x100.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_highlight-soft_75_cccccc_1x100.png Binary files differnew file mode 100644 index 0000000..7c9fa6c --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-bg_highlight-soft_75_cccccc_1x100.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_222222_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_222222_256x240.png Binary files differnew file mode 100644 index 0000000..ee039dc --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_222222_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_2e83ff_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_2e83ff_256x240.png Binary files differnew file mode 100644 index 0000000..45e8928 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_2e83ff_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_454545_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_454545_256x240.png Binary files differnew file mode 100644 index 0000000..7ec70d1 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_454545_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_888888_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_888888_256x240.png Binary files differnew file mode 100644 index 0000000..5ba708c --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_888888_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_cd0a0a_256x240.png b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_cd0a0a_256x240.png Binary files differnew file mode 100644 index 0000000..7930a55 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/images/ui-icons_cd0a0a_256x240.png diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery-ui.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery-ui.min.css new file mode 100644 index 0000000..1e76dbc --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery-ui.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.core.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.progressbar.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.slider.css, jquery.ui.tabs.css, jquery.ui.theme.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-helper-hidden{display:none}.ui-helper-hidden-accessible{position:absolute!important;clip:rect(1px);clip:rect(1px,1px,1px,1px)}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table}.ui-helper-clearfix:after{clear:both}.ui-helper-clearfix{zoom:1}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-state-disabled{cursor:default!important}.ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-overlay{position:absolute;top:0;left:0;width:100%;height:100%}.ui-accordion{width:100%}.ui-accordion .ui-accordion-header{cursor:pointer;position:relative;margin-top:1px;zoom:1}.ui-accordion .ui-accordion-li-fix{display:inline}.ui-accordion .ui-accordion-header-active{border-bottom:0!important}.ui-accordion .ui-accordion-header a{display:block;font-size:1em;padding:.5em .5em .5em .7em}.ui-accordion-icons .ui-accordion-header a{padding-left:2.2em}.ui-accordion .ui-accordion-header .ui-icon{position:absolute;left:.5em;top:50%;margin-top:-8px}.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;margin-top:-2px;position:relative;top:1px;margin-bottom:2px;overflow:auto;display:none;zoom:1}.ui-accordion .ui-accordion-content-active{display:block}.ui-autocomplete{position:absolute;cursor:default}* html .ui-autocomplete{width:1px}.ui-menu{list-style:none;padding:2px;margin:0;display:block;float:left}.ui-menu .ui-menu{margin-top:-3px}.ui-menu .ui-menu-item{margin:0;padding:0;zoom:1;float:left;clear:left;width:100%}.ui-menu .ui-menu-item a{text-decoration:none;display:block;padding:.2em .4em;line-height:1.5;zoom:1}.ui-menu .ui-menu-item a.ui-state-hover,.ui-menu .ui-menu-item a.ui-state-active{font-weight:normal;margin:-1px}.ui-button{display:inline-block;position:relative;padding:0;margin-right:.1em;text-decoration:none!important;cursor:pointer;text-align:center;zoom:1;overflow:visible}.ui-button-icon-only{width:2.2em}button.ui-button-icon-only{width:2.4em}.ui-button-icons-only{width:3.4em}button.ui-button-icons-only{width:3.7em}.ui-button .ui-button-text{display:block;line-height:1.4}.ui-button-text-only .ui-button-text{padding:.4em 1em}.ui-button-icon-only .ui-button-text,.ui-button-icons-only .ui-button-text{padding:.4em;text-indent:-9999999px}.ui-button-text-icon-primary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 1em .4em 2.1em}.ui-button-text-icon-secondary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 2.1em .4em 1em}.ui-button-text-icons .ui-button-text{padding-left:2.1em;padding-right:2.1em}input.ui-button{padding:.4em 1em}.ui-button-icon-only .ui-icon,.ui-button-text-icon-primary .ui-icon,.ui-button-text-icon-secondary .ui-icon,.ui-button-text-icons .ui-icon,.ui-button-icons-only .ui-icon{position:absolute;top:50%;margin-top:-8px}.ui-button-icon-only .ui-icon{left:50%;margin-left:-8px}.ui-button-text-icon-primary .ui-button-icon-primary,.ui-button-text-icons .ui-button-icon-primary,.ui-button-icons-only .ui-button-icon-primary{left:.5em}.ui-button-text-icon-secondary .ui-button-icon-secondary,.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-buttonset{margin-right:7px}.ui-buttonset .ui-button{margin-left:0;margin-right:-.3em}button.ui-button::-moz-focus-inner{border:0;padding:0}.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month-year{width:100%}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepicker-year{width:49%}.ui-datepicker table{width:100%;font-size:.9em;border-collapse:collapse;margin:0 0 .4em}.ui-datepicker th{padding:.7em .3em;text-align:center;font-weight:bold;border:0}.ui-datepicker td{border:0;padding:1px}.ui-datepicker td span,.ui-datepicker td a{display:block;padding:.2em;text-align:right;text-decoration:none}.ui-datepicker .ui-datepicker-buttonpane{background-image:none;margin:.7em 0 0 0;padding:0 .2em;border-left:0;border-right:0;border-bottom:0}.ui-datepicker .ui-datepicker-buttonpane button{float:right;margin:.5em .2em .4em;cursor:pointer;padding:.2em .6em .3em .6em;width:auto;overflow:visible}.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current{float:left}.ui-datepicker.ui-datepicker-multi{width:auto}.ui-datepicker-multi .ui-datepicker-group{float:left}.ui-datepicker-multi .ui-datepicker-group table{width:95%;margin:0 auto .4em}.ui-datepicker-multi-2 .ui-datepicker-group{width:50%}.ui-datepicker-multi-3 .ui-datepicker-group{width:33.3%}.ui-datepicker-multi-4 .ui-datepicker-group{width:25%}.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-buttonpane{clear:left}.ui-datepicker-row-break{clear:both;width:100%;font-size:0em}.ui-datepicker-rtl{direction:rtl}.ui-datepicker-rtl .ui-datepicker-prev{right:2px;left:auto}.ui-datepicker-rtl .ui-datepicker-next{left:2px;right:auto}.ui-datepicker-rtl .ui-datepicker-prev:hover{right:1px;left:auto}.ui-datepicker-rtl .ui-datepicker-next:hover{left:1px;right:auto}.ui-datepicker-rtl .ui-datepicker-buttonpane{clear:right}.ui-datepicker-rtl .ui-datepicker-buttonpane button{float:left}.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current{float:right}.ui-datepicker-rtl .ui-datepicker-group{float:right}.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker-cover{display:none;display position:absolute;z-index:-1;filter:mask();top:-4px;left:-4px;width:200px;height:200px}.ui-dialog{position:absolute;padding:.2em;width:300px;overflow:hidden}.ui-dialog .ui-dialog-titlebar{padding:.4em 1em;position:relative}.ui-dialog .ui-dialog-title{float:left;margin:.1em 16px .1em 0}.ui-dialog .ui-dialog-titlebar-close{position:absolute;right:.3em;top:50%;width:19px;margin:-10px 0 0 0;padding:1px;height:18px}.ui-dialog .ui-dialog-titlebar-close span{display:block;margin:1px}.ui-dialog .ui-dialog-titlebar-close:hover,.ui-dialog .ui-dialog-titlebar-close:focus{padding:0}.ui-dialog .ui-dialog-content{position:relative;border:0;padding:.5em 1em;background:none;overflow:auto;zoom:1}.ui-dialog .ui-dialog-buttonpane{text-align:left;border-width:1px 0 0 0;background-image:none;margin:.5em 0 0 0;padding:.3em 1em .5em .4em}.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset{float:right}.ui-dialog .ui-dialog-buttonpane button{margin:.5em .4em .5em 0;cursor:pointer}.ui-dialog .ui-resizable-se{width:14px;height:14px;right:3px;bottom:3px}.ui-draggable .ui-dialog-titlebar{cursor:move}.ui-progressbar{height:2em;text-align:left;overflow:hidden}.ui-progressbar .ui-progressbar-value{margin:-1px;height:100%}.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}.ui-slider{position:relative;text-align:left}.ui-slider .ui-slider-handle{position:absolute;z-index:2;width:1.2em;height:1.2em;cursor:default}.ui-slider .ui-slider-range{position:absolute;z-index:1;font-size:.7em;display:block;border:0;background-position:0 0}.ui-slider-horizontal{height:.8em}.ui-slider-horizontal .ui-slider-handle{top:-.3em;margin-left:-.6em}.ui-slider-horizontal .ui-slider-range{top:0;height:100%}.ui-slider-horizontal .ui-slider-range-min{left:0}.ui-slider-horizontal .ui-slider-range-max{right:0}.ui-slider-vertical{width:.8em;height:100px}.ui-slider-vertical .ui-slider-handle{left:-.3em;margin-left:0;margin-bottom:-.6em}.ui-slider-vertical .ui-slider-range{left:0;width:100%}.ui-slider-vertical .ui-slider-range-min{bottom:0}.ui-slider-vertical .ui-slider-range-max{top:0}.ui-tabs{position:relative;padding:.2em;zoom:1}.ui-tabs .ui-tabs-nav{margin:0;padding:.2em .2em 0}.ui-tabs .ui-tabs-nav li{list-style:none;float:left;position:relative;top:1px;margin:0 .2em 1px 0;border-bottom:0!important;padding:0;white-space:nowrap}.ui-tabs .ui-tabs-nav li a{float:left;padding:.5em 1em;text-decoration:none}.ui-tabs .ui-tabs-nav li.ui-tabs-selected{margin-bottom:0;padding-bottom:1px}.ui-tabs .ui-tabs-nav li.ui-tabs-selected a,.ui-tabs .ui-tabs-nav li.ui-state-disabled a,.ui-tabs .ui-tabs-nav li.ui-state-processing a{cursor:text}.ui-tabs .ui-tabs-nav li a,.ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a{cursor:pointer}.ui-tabs .ui-tabs-panel{display:block;border-width:0;padding:1em 1.4em;background:none}.ui-tabs .ui-tabs-hide{display:none!important}.ui-widget{font-family:Verdana,Arial,sans-serif;font-size:1.1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Verdana,Arial,sans-serif;font-size:1em}.ui-widget-content{border:1px solid #aaa;background:#fff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;color:#222}.ui-widget-content a{color:#222}.ui-widget-header{border:1px solid #aaa;background:#ccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x;color:#222;font-weight:bold}.ui-widget-header a{color:#222}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default{border:1px solid #d3d3d3;background:#e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#555}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited{color:#555;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus{border:1px solid #999;background:#dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-state-hover a,.ui-state-hover a:hover{color:#212121;text-decoration:none}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active{border:1px solid #aaa;background:#fff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#212121;text-decoration:none}.ui-widget:active{outline:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #fcefa1;background:#fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x;color:#363636}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#363636}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #cd0a0a;background:#fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x;color:#cd0a0a}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#cd0a0a}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#cd0a0a}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-icon{width:16px;height:16px;background-image:url(images/ui-icons_222222_256x240.png)}.ui-widget-content .ui-icon{background-image:url(images/ui-icons_222222_256x240.png)}.ui-widget-header .ui-icon{background-image:url(images/ui-icons_222222_256x240.png)}.ui-state-default .ui-icon{background-image:url(images/ui-icons_888888_256x240.png)}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon{background-image:url(images/ui-icons_454545_256x240.png)}.ui-state-active .ui-icon{background-image:url(images/ui-icons_454545_256x240.png)}.ui-state-highlight .ui-icon{background-image:url(images/ui-icons_2e83ff_256x240.png)}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url(images/ui-icons_cd0a0a_256x240.png)}.ui-icon-carat-1-n{background-position:0 0}.ui-icon-carat-1-ne{background-position:-16px 0}.ui-icon-carat-1-e{background-position:-32px 0}.ui-icon-carat-1-se{background-position:-48px 0}.ui-icon-carat-1-s{background-position:-64px 0}.ui-icon-carat-1-sw{background-position:-80px 0}.ui-icon-carat-1-w{background-position:-96px 0}.ui-icon-carat-1-nw{background-position:-112px 0}.ui-icon-carat-2-n-s{background-position:-128px 0}.ui-icon-carat-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-64px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-64px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:0 -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-off{background-position:-96px -144px}.ui-icon-radio-on{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{-moz-border-radius-topleft:4px;-webkit-border-top-left-radius:4px;-khtml-border-top-left-radius:4px;border-top-left-radius:4px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{-moz-border-radius-topright:4px;-webkit-border-top-right-radius:4px;-khtml-border-top-right-radius:4px;border-top-right-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{-moz-border-radius-bottomleft:4px;-webkit-border-bottom-left-radius:4px;-khtml-border-bottom-left-radius:4px;border-bottom-left-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{-moz-border-radius-bottomright:4px;-webkit-border-bottom-right-radius:4px;-khtml-border-bottom-right-radius:4px;border-bottom-right-radius:4px}.ui-widget-overlay{background:#aaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;opacity:.3;filter:Alpha(Opacity=30)}.ui-widget-shadow{margin:-8px 0 0 -8px;padding:8px;background:#aaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;opacity:.3;filter:Alpha(Opacity=30);-moz-border-radius:8px;-khtml-border-radius:8px;-webkit-border-radius:8px;border-radius:8px}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.accordion.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.accordion.min.css new file mode 100644 index 0000000..3f59045 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.accordion.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.accordion.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-accordion{width:100%}.ui-accordion .ui-accordion-header{cursor:pointer;position:relative;margin-top:1px;zoom:1}.ui-accordion .ui-accordion-li-fix{display:inline}.ui-accordion .ui-accordion-header-active{border-bottom:0!important}.ui-accordion .ui-accordion-header a{display:block;font-size:1em;padding:.5em .5em .5em .7em}.ui-accordion-icons .ui-accordion-header a{padding-left:2.2em}.ui-accordion .ui-accordion-header .ui-icon{position:absolute;left:.5em;top:50%;margin-top:-8px}.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;margin-top:-2px;position:relative;top:1px;margin-bottom:2px;overflow:auto;display:none;zoom:1}.ui-accordion .ui-accordion-content-active{display:block}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.autocomplete.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.autocomplete.min.css new file mode 100644 index 0000000..631b8bc --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.autocomplete.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.autocomplete.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-autocomplete{position:absolute;cursor:default}* html .ui-autocomplete{width:1px}.ui-menu{list-style:none;padding:2px;margin:0;display:block;float:left}.ui-menu .ui-menu{margin-top:-3px}.ui-menu .ui-menu-item{margin:0;padding:0;zoom:1;float:left;clear:left;width:100%}.ui-menu .ui-menu-item a{text-decoration:none;display:block;padding:.2em .4em;line-height:1.5;zoom:1}.ui-menu .ui-menu-item a.ui-state-hover,.ui-menu .ui-menu-item a.ui-state-active{font-weight:normal;margin:-1px}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.button.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.button.min.css new file mode 100644 index 0000000..9148a97 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.button.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.button.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-button{display:inline-block;position:relative;padding:0;margin-right:.1em;text-decoration:none!important;cursor:pointer;text-align:center;zoom:1;overflow:visible}.ui-button-icon-only{width:2.2em}button.ui-button-icon-only{width:2.4em}.ui-button-icons-only{width:3.4em}button.ui-button-icons-only{width:3.7em}.ui-button .ui-button-text{display:block;line-height:1.4}.ui-button-text-only .ui-button-text{padding:.4em 1em}.ui-button-icon-only .ui-button-text,.ui-button-icons-only .ui-button-text{padding:.4em;text-indent:-9999999px}.ui-button-text-icon-primary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 1em .4em 2.1em}.ui-button-text-icon-secondary .ui-button-text,.ui-button-text-icons .ui-button-text{padding:.4em 2.1em .4em 1em}.ui-button-text-icons .ui-button-text{padding-left:2.1em;padding-right:2.1em}input.ui-button{padding:.4em 1em}.ui-button-icon-only .ui-icon,.ui-button-text-icon-primary .ui-icon,.ui-button-text-icon-secondary .ui-icon,.ui-button-text-icons .ui-icon,.ui-button-icons-only .ui-icon{position:absolute;top:50%;margin-top:-8px}.ui-button-icon-only .ui-icon{left:50%;margin-left:-8px}.ui-button-text-icon-primary .ui-button-icon-primary,.ui-button-text-icons .ui-button-icon-primary,.ui-button-icons-only .ui-button-icon-primary{left:.5em}.ui-button-text-icon-secondary .ui-button-icon-secondary,.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-button-text-icons .ui-button-icon-secondary,.ui-button-icons-only .ui-button-icon-secondary{right:.5em}.ui-buttonset{margin-right:7px}.ui-buttonset .ui-button{margin-left:0;margin-right:-.3em}button.ui-button::-moz-focus-inner{border:0;padding:0}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.core.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.core.min.css new file mode 100644 index 0000000..644b714 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.core.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.core.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-helper-hidden{display:none}.ui-helper-hidden-accessible{position:absolute!important;clip:rect(1px);clip:rect(1px,1px,1px,1px)}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table}.ui-helper-clearfix:after{clear:both}.ui-helper-clearfix{zoom:1}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-state-disabled{cursor:default!important}.ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-overlay{position:absolute;top:0;left:0;width:100%;height:100%}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.datepicker.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.datepicker.min.css new file mode 100644 index 0000000..7bd6969 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.datepicker.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.datepicker.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month-year{width:100%}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepicker-year{width:49%}.ui-datepicker table{width:100%;font-size:.9em;border-collapse:collapse;margin:0 0 .4em}.ui-datepicker th{padding:.7em .3em;text-align:center;font-weight:bold;border:0}.ui-datepicker td{border:0;padding:1px}.ui-datepicker td span,.ui-datepicker td a{display:block;padding:.2em;text-align:right;text-decoration:none}.ui-datepicker .ui-datepicker-buttonpane{background-image:none;margin:.7em 0 0 0;padding:0 .2em;border-left:0;border-right:0;border-bottom:0}.ui-datepicker .ui-datepicker-buttonpane button{float:right;margin:.5em .2em .4em;cursor:pointer;padding:.2em .6em .3em .6em;width:auto;overflow:visible}.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current{float:left}.ui-datepicker.ui-datepicker-multi{width:auto}.ui-datepicker-multi .ui-datepicker-group{float:left}.ui-datepicker-multi .ui-datepicker-group table{width:95%;margin:0 auto .4em}.ui-datepicker-multi-2 .ui-datepicker-group{width:50%}.ui-datepicker-multi-3 .ui-datepicker-group{width:33.3%}.ui-datepicker-multi-4 .ui-datepicker-group{width:25%}.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-buttonpane{clear:left}.ui-datepicker-row-break{clear:both;width:100%;font-size:0em}.ui-datepicker-rtl{direction:rtl}.ui-datepicker-rtl .ui-datepicker-prev{right:2px;left:auto}.ui-datepicker-rtl .ui-datepicker-next{left:2px;right:auto}.ui-datepicker-rtl .ui-datepicker-prev:hover{right:1px;left:auto}.ui-datepicker-rtl .ui-datepicker-next:hover{left:1px;right:auto}.ui-datepicker-rtl .ui-datepicker-buttonpane{clear:right}.ui-datepicker-rtl .ui-datepicker-buttonpane button{float:left}.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current{float:right}.ui-datepicker-rtl .ui-datepicker-group{float:right}.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker-cover{display:none;display position:absolute;z-index:-1;filter:mask();top:-4px;left:-4px;width:200px;height:200px}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.dialog.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.dialog.min.css new file mode 100644 index 0000000..97b6c44 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.dialog.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.dialog.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-dialog{position:absolute;padding:.2em;width:300px;overflow:hidden}.ui-dialog .ui-dialog-titlebar{padding:.4em 1em;position:relative}.ui-dialog .ui-dialog-title{float:left;margin:.1em 16px .1em 0}.ui-dialog .ui-dialog-titlebar-close{position:absolute;right:.3em;top:50%;width:19px;margin:-10px 0 0 0;padding:1px;height:18px}.ui-dialog .ui-dialog-titlebar-close span{display:block;margin:1px}.ui-dialog .ui-dialog-titlebar-close:hover,.ui-dialog .ui-dialog-titlebar-close:focus{padding:0}.ui-dialog .ui-dialog-content{position:relative;border:0;padding:.5em 1em;background:none;overflow:auto;zoom:1}.ui-dialog .ui-dialog-buttonpane{text-align:left;border-width:1px 0 0 0;background-image:none;margin:.5em 0 0 0;padding:.3em 1em .5em .4em}.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset{float:right}.ui-dialog .ui-dialog-buttonpane button{margin:.5em .4em .5em 0;cursor:pointer}.ui-dialog .ui-resizable-se{width:14px;height:14px;right:3px;bottom:3px}.ui-draggable .ui-dialog-titlebar{cursor:move}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.progressbar.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.progressbar.min.css new file mode 100644 index 0000000..7ac8e04 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.progressbar.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.progressbar.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-progressbar{height:2em;text-align:left;overflow:hidden}.ui-progressbar .ui-progressbar-value{margin:-1px;height:100%}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.resizable.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.resizable.min.css new file mode 100644 index 0000000..1085d30 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.resizable.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.resizable.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.selectable.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.selectable.min.css new file mode 100644 index 0000000..ce3e674 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.selectable.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.selectable.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.slider.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.slider.min.css new file mode 100644 index 0000000..322578a --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.slider.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.slider.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-slider{position:relative;text-align:left}.ui-slider .ui-slider-handle{position:absolute;z-index:2;width:1.2em;height:1.2em;cursor:default}.ui-slider .ui-slider-range{position:absolute;z-index:1;font-size:.7em;display:block;border:0;background-position:0 0}.ui-slider-horizontal{height:.8em}.ui-slider-horizontal .ui-slider-handle{top:-.3em;margin-left:-.6em}.ui-slider-horizontal .ui-slider-range{top:0;height:100%}.ui-slider-horizontal .ui-slider-range-min{left:0}.ui-slider-horizontal .ui-slider-range-max{right:0}.ui-slider-vertical{width:.8em;height:100px}.ui-slider-vertical .ui-slider-handle{left:-.3em;margin-left:0;margin-bottom:-.6em}.ui-slider-vertical .ui-slider-range{left:0;width:100%}.ui-slider-vertical .ui-slider-range-min{bottom:0}.ui-slider-vertical .ui-slider-range-max{top:0}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.tabs.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.tabs.min.css new file mode 100644 index 0000000..11fb82b --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.tabs.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.tabs.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-tabs{position:relative;padding:.2em;zoom:1}.ui-tabs .ui-tabs-nav{margin:0;padding:.2em .2em 0}.ui-tabs .ui-tabs-nav li{list-style:none;float:left;position:relative;top:1px;margin:0 .2em 1px 0;border-bottom:0!important;padding:0;white-space:nowrap}.ui-tabs .ui-tabs-nav li a{float:left;padding:.5em 1em;text-decoration:none}.ui-tabs .ui-tabs-nav li.ui-tabs-selected{margin-bottom:0;padding-bottom:1px}.ui-tabs .ui-tabs-nav li.ui-tabs-selected a,.ui-tabs .ui-tabs-nav li.ui-state-disabled a,.ui-tabs .ui-tabs-nav li.ui-state-processing a{cursor:text}.ui-tabs .ui-tabs-nav li a,.ui-tabs.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-selected a{cursor:pointer}.ui-tabs .ui-tabs-panel{display:block;border-width:0;padding:1em 1.4em;background:none}.ui-tabs .ui-tabs-hide{display:none!important}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.theme.min.css b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.theme.min.css new file mode 100644 index 0000000..8875d98 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Content/themes/base/minified/jquery.ui.theme.min.css @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.theme.css +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +.ui-widget{font-family:Verdana,Arial,sans-serif;font-size:1.1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Verdana,Arial,sans-serif;font-size:1em}.ui-widget-content{border:1px solid #aaa;background:#fff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x;color:#222}.ui-widget-content a{color:#222}.ui-widget-header{border:1px solid #aaa;background:#ccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x;color:#222;font-weight:bold}.ui-widget-header a{color:#222}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default{border:1px solid #d3d3d3;background:#e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#555}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited{color:#555;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus{border:1px solid #999;background:#dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-state-hover a,.ui-state-hover a:hover{color:#212121;text-decoration:none}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active{border:1px solid #aaa;background:#fff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x;font-weight:normal;color:#212121}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#212121;text-decoration:none}.ui-widget:active{outline:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #fcefa1;background:#fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x;color:#363636}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#363636}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #cd0a0a;background:#fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x;color:#cd0a0a}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#cd0a0a}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#cd0a0a}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-icon{width:16px;height:16px;background-image:url(images/ui-icons_222222_256x240.png)}.ui-widget-content .ui-icon{background-image:url(images/ui-icons_222222_256x240.png)}.ui-widget-header .ui-icon{background-image:url(images/ui-icons_222222_256x240.png)}.ui-state-default .ui-icon{background-image:url(images/ui-icons_888888_256x240.png)}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon{background-image:url(images/ui-icons_454545_256x240.png)}.ui-state-active .ui-icon{background-image:url(images/ui-icons_454545_256x240.png)}.ui-state-highlight .ui-icon{background-image:url(images/ui-icons_2e83ff_256x240.png)}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url(images/ui-icons_cd0a0a_256x240.png)}.ui-icon-carat-1-n{background-position:0 0}.ui-icon-carat-1-ne{background-position:-16px 0}.ui-icon-carat-1-e{background-position:-32px 0}.ui-icon-carat-1-se{background-position:-48px 0}.ui-icon-carat-1-s{background-position:-64px 0}.ui-icon-carat-1-sw{background-position:-80px 0}.ui-icon-carat-1-w{background-position:-96px 0}.ui-icon-carat-1-nw{background-position:-112px 0}.ui-icon-carat-2-n-s{background-position:-128px 0}.ui-icon-carat-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-64px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-64px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:0 -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-off{background-position:-96px -144px}.ui-icon-radio-on{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{-moz-border-radius-topleft:4px;-webkit-border-top-left-radius:4px;-khtml-border-top-left-radius:4px;border-top-left-radius:4px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{-moz-border-radius-topright:4px;-webkit-border-top-right-radius:4px;-khtml-border-top-right-radius:4px;border-top-right-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{-moz-border-radius-bottomleft:4px;-webkit-border-bottom-left-radius:4px;-khtml-border-bottom-left-radius:4px;border-bottom-left-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{-moz-border-radius-bottomright:4px;-webkit-border-bottom-right-radius:4px;-khtml-border-bottom-right-radius:4px;border-bottom-right-radius:4px}.ui-widget-overlay{background:#aaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;opacity:.3;filter:Alpha(Opacity=30)}.ui-widget-shadow{margin:-8px 0 0 -8px;padding:8px;background:#aaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;opacity:.3;filter:Alpha(Opacity=30);-moz-border-radius:8px;-khtml-border-radius:8px;-webkit-border-radius:8px;border-radius:8px}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Controllers/HomeController.cs b/samples/OAuth2ProtectedWebApi/Controllers/HomeController.cs new file mode 100644 index 0000000..3244000 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Controllers/HomeController.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; + +namespace OAuth2ProtectedWebApi.Controllers { + public class HomeController : Controller { + public ActionResult Index() { + return View(); + } + } +} diff --git a/samples/OAuth2ProtectedWebApi/Controllers/TokenController.cs b/samples/OAuth2ProtectedWebApi/Controllers/TokenController.cs new file mode 100644 index 0000000..a6ecf32 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Controllers/TokenController.cs @@ -0,0 +1,17 @@ +namespace OAuth2ProtectedWebApi.Controllers { + using System.Net.Http; + using System.Threading.Tasks; + using System.Web.Http; + + using DotNetOpenAuth.OAuth2; + + using OAuth2ProtectedWebApi.Code; + + public class TokenController : ApiController { + // POST /api/token + public Task<HttpResponseMessage> Post(HttpRequestMessage request) { + var authServer = new AuthorizationServer(new AuthorizationServerHost()); + return authServer.HandleTokenRequestAsync(request); + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Controllers/UserController.cs b/samples/OAuth2ProtectedWebApi/Controllers/UserController.cs new file mode 100644 index 0000000..e627dc2 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Controllers/UserController.cs @@ -0,0 +1,76 @@ +namespace OAuth2ProtectedWebApi.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Security.Principal; + using System.Threading.Tasks; + using System.Web; + using System.Web.Mvc; + using System.Web.Security; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2; + using DotNetOpenAuth.OAuth2.Messages; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.RelyingParty; + using OAuth2ProtectedWebApi.Code; + + public class UserController : Controller { + [Authorize] + [HttpGet] + [HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking + public async Task<ActionResult> Authorize() { + var authServer = new AuthorizationServer(new AuthorizationServerHost()); + var authRequest = await authServer.ReadAuthorizationRequestAsync(this.Request); + this.ViewData["scope"] = authRequest.Scope; + this.ViewData["request"] = this.Request.Url; + return View(); + } + + [Authorize] + [HttpPost, ValidateAntiForgeryToken] + public async Task<ActionResult> Respond(string request, bool approval) { + var authServer = new AuthorizationServer(new AuthorizationServerHost()); + var authRequest = await authServer.ReadAuthorizationRequestAsync(new Uri(request)); + IProtocolMessage responseMessage; + if (approval) { + var grantedResponse = authServer.PrepareApproveAuthorizationRequest( + authRequest, this.User.Identity.Name, authRequest.Scope); + responseMessage = grantedResponse; + } else { + var rejectionResponse = authServer.PrepareRejectAuthorizationRequest(authRequest); + rejectionResponse.Error = Protocol.EndUserAuthorizationRequestErrorCodes.AccessDenied; + responseMessage = rejectionResponse; + } + + var response = await authServer.Channel.PrepareResponseAsync(responseMessage); + return response.AsActionResult(); + } + + public async Task<ActionResult> Login(string returnUrl) { + var rp = new OpenIdRelyingParty(null); + Realm officialWebSiteHome = Realm.AutoDetect; + Uri returnTo = new Uri(this.Request.Url, this.Url.Action("Authenticate")); + var request = await rp.CreateRequestAsync(WellKnownProviders.Google, officialWebSiteHome, returnTo); + if (returnUrl != null) { + request.SetUntrustedCallbackArgument("returnUrl", returnUrl); + } + + var redirectingResponse = await request.GetRedirectingResponseAsync(); + return redirectingResponse.AsActionResult(); + } + + public async Task<ActionResult> Authenticate() { + var rp = new OpenIdRelyingParty(null); + var response = await rp.GetResponseAsync(this.Request); + if (response != null) { + if (response.Status == AuthenticationStatus.Authenticated) { + FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false); + return this.Redirect(FormsAuthentication.GetRedirectUrl(response.ClaimedIdentifier, false)); + } + } + + return this.RedirectToAction("Index", "Home"); + } + } +} diff --git a/samples/OAuth2ProtectedWebApi/Controllers/ValuesController.cs b/samples/OAuth2ProtectedWebApi/Controllers/ValuesController.cs new file mode 100644 index 0000000..1c84c99 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Controllers/ValuesController.cs @@ -0,0 +1,33 @@ +namespace OAuth2ProtectedWebApi.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Web.Http; + + [Authorize(Roles = "Values")] + public class ValuesController : ApiController { + // GET api/values + public IEnumerable<string> Get() { + return new string[] { "value1", this.User.Identity.Name, "value2" }; + } + + // GET api/values/5 + public string Get(int id) { + return "value"; + } + + // POST api/values + public void Post([FromBody]string value) { + } + + // PUT api/values/5 + public void Put(int id, [FromBody]string value) { + } + + // DELETE api/values/5 + public void Delete(int id) { + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Global.asax b/samples/OAuth2ProtectedWebApi/Global.asax new file mode 100644 index 0000000..87e66de --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Global.asax @@ -0,0 +1 @@ +<%@ Application Codebehind="Global.asax.cs" Inherits="OAuth2ProtectedWebApi.WebApiApplication" Language="C#" %> diff --git a/samples/OAuth2ProtectedWebApi/Global.asax.cs b/samples/OAuth2ProtectedWebApi/Global.asax.cs new file mode 100644 index 0000000..0f71597 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Global.asax.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Http; +using System.Web.Mvc; +using System.Web.Optimization; +using System.Web.Routing; + +namespace OAuth2ProtectedWebApi { + // Note: For instructions on enabling IIS6 or IIS7 classic mode, + // visit http://go.microsoft.com/?LinkId=9394801 + + public class WebApiApplication : System.Web.HttpApplication { + protected void Application_Start() { + AreaRegistration.RegisterAllAreas(); + + WebApiConfig.Register(GlobalConfiguration.Configuration); + FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); + RouteConfig.RegisterRoutes(RouteTable.Routes); + BundleConfig.RegisterBundles(BundleTable.Bundles); + } + } +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Images/accent.png b/samples/OAuth2ProtectedWebApi/Images/accent.png Binary files differnew file mode 100644 index 0000000..cd07580 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/accent.png diff --git a/samples/OAuth2ProtectedWebApi/Images/bullet.png b/samples/OAuth2ProtectedWebApi/Images/bullet.png Binary files differnew file mode 100644 index 0000000..d3824c1 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/bullet.png diff --git a/samples/OAuth2ProtectedWebApi/Images/heroAccent.png b/samples/OAuth2ProtectedWebApi/Images/heroAccent.png Binary files differnew file mode 100644 index 0000000..14ea59b --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/heroAccent.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList0.png b/samples/OAuth2ProtectedWebApi/Images/orderedList0.png Binary files differnew file mode 100644 index 0000000..7a4ea25 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList0.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList1.png b/samples/OAuth2ProtectedWebApi/Images/orderedList1.png Binary files differnew file mode 100644 index 0000000..523c24d --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList1.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList2.png b/samples/OAuth2ProtectedWebApi/Images/orderedList2.png Binary files differnew file mode 100644 index 0000000..553a2da --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList2.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList3.png b/samples/OAuth2ProtectedWebApi/Images/orderedList3.png Binary files differnew file mode 100644 index 0000000..0714981 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList3.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList4.png b/samples/OAuth2ProtectedWebApi/Images/orderedList4.png Binary files differnew file mode 100644 index 0000000..ce91e8f --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList4.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList5.png b/samples/OAuth2ProtectedWebApi/Images/orderedList5.png Binary files differnew file mode 100644 index 0000000..c073485 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList5.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList6.png b/samples/OAuth2ProtectedWebApi/Images/orderedList6.png Binary files differnew file mode 100644 index 0000000..3b9aa05 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList6.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList7.png b/samples/OAuth2ProtectedWebApi/Images/orderedList7.png Binary files differnew file mode 100644 index 0000000..f99c609 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList7.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList8.png b/samples/OAuth2ProtectedWebApi/Images/orderedList8.png Binary files differnew file mode 100644 index 0000000..127596d --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList8.png diff --git a/samples/OAuth2ProtectedWebApi/Images/orderedList9.png b/samples/OAuth2ProtectedWebApi/Images/orderedList9.png Binary files differnew file mode 100644 index 0000000..39cfdcf --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Images/orderedList9.png diff --git a/samples/OAuth2ProtectedWebApi/OAuth2ProtectedWebApi.csproj b/samples/OAuth2ProtectedWebApi/OAuth2ProtectedWebApi.csproj new file mode 100644 index 0000000..9c54bcd --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/OAuth2ProtectedWebApi.csproj @@ -0,0 +1,313 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion> + </ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{58A3721F-5B5C-4CA7-BE39-91640B5B4924}</ProjectGuid> + <ProjectTypeGuids>{E3E379DF-F4C6-4180-9B81-6769533ABE47};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>OAuth2ProtectedWebApi</RootNamespace> + <AssemblyName>OAuth2ProtectedWebApi</AssemblyName> + <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <MvcBuildViews>false</MvcBuildViews> + <UseIISExpress>true</UseIISExpress> + <IISExpressSSLPort /> + <IISExpressAnonymousAuthentication /> + <IISExpressWindowsAuthentication /> + <IISExpressUseClassicPipelineMode /> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\src\</SolutionDir> + <RestorePackages>true</RestorePackages> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System" /> + <Reference Include="System.Data" /> + <Reference Include="System.Data.Entity" /> + <Reference Include="System.Drawing" /> + <Reference Include="System.ServiceModel" /> + <Reference Include="System.Web.Entity" /> + <Reference Include="System.Web.ApplicationServices" /> + <Reference Include="System.ComponentModel.DataAnnotations" /> + <Reference Include="System.Core" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Web" /> + <Reference Include="System.Web.Abstractions" /> + <Reference Include="System.Web.Routing" /> + <Reference Include="System.Xml" /> + <Reference Include="System.Configuration" /> + <Reference Include="EntityFramework"> + <HintPath>..\..\src\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll</HintPath> + </Reference> + <Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath> + </Reference> + <Reference Include="Newtonsoft.Json"> + <HintPath>..\..\src\packages\Newtonsoft.Json.4.5.6\lib\net40\Newtonsoft.Json.dll</HintPath> + </Reference> + <Reference Include="System.Net.Http"> + </Reference> + <Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebApi.Client.4.0.20710.0\lib\net40\System.Net.Http.Formatting.dll</HintPath> + </Reference> + <Reference Include="System.Net.Http.WebRequest"> + </Reference> + <Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.Helpers.dll</HintPath> + </Reference> + <Reference Include="System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebApi.Core.4.0.20710.0\lib\net40\System.Web.Http.dll</HintPath> + </Reference> + <Reference Include="System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebApi.WebHost.4.0.20710.0\lib\net40\System.Web.Http.WebHost.dll</HintPath> + </Reference> + <Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Mvc.4.0.20710.0\lib\net40\System.Web.Mvc.dll</HintPath> + </Reference> + <Reference Include="System.Web.Optimization"> + <HintPath>..\..\src\packages\Microsoft.AspNet.Web.Optimization.1.0.0\lib\net40\System.Web.Optimization.dll</HintPath> + </Reference> + <Reference Include="System.Web.Providers"> + <HintPath>..\..\src\packages\Microsoft.AspNet.Providers.Core.1.1\lib\net40\System.Web.Providers.dll</HintPath> + </Reference> + <Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Razor.2.0.20710.0\lib\net40\System.Web.Razor.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath> + </Reference> + <Reference Include="WebGrease"> + <Private>True</Private> + <HintPath>..\..\src\packages\WebGrease.1.1.0\lib\WebGrease.dll</HintPath> + </Reference> + <Reference Include="Antlr3.Runtime"> + <Private>True</Private> + <HintPath>..\..\src\packages\WebGrease.1.1.0\lib\Antlr3.Runtime.dll</HintPath> + </Reference> + </ItemGroup> + <ItemGroup> + <Compile Include="App_Start\BundleConfig.cs" /> + <Compile Include="App_Start\FilterConfig.cs" /> + <Compile Include="App_Start\RouteConfig.cs" /> + <Compile Include="App_Start\WebApiConfig.cs" /> + <Compile Include="Code\AuthorizationServerHost.cs" /> + <Compile Include="Code\BearerTokenHandler.cs" /> + <Compile Include="Code\HttpHeaderAttribute.cs" /> + <Compile Include="Controllers\HomeController.cs" /> + <Compile Include="Controllers\TokenController.cs" /> + <Compile Include="Controllers\UserController.cs" /> + <Compile Include="Controllers\ValuesController.cs" /> + <Compile Include="Global.asax.cs"> + <DependentUpon>Global.asax</DependentUpon> + </Compile> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <Content Include="Content\themes\base\images\ui-bg_flat_0_aaaaaa_40x100.png" /> + <Content Include="Content\themes\base\images\ui-bg_flat_75_ffffff_40x100.png" /> + <Content Include="Content\themes\base\images\ui-bg_glass_55_fbf9ee_1x400.png" /> + <Content Include="Content\themes\base\images\ui-bg_glass_65_ffffff_1x400.png" /> + <Content Include="Content\themes\base\images\ui-bg_glass_75_dadada_1x400.png" /> + <Content Include="Content\themes\base\images\ui-bg_glass_75_e6e6e6_1x400.png" /> + <Content Include="Content\themes\base\images\ui-bg_glass_95_fef1ec_1x400.png" /> + <Content Include="Content\themes\base\images\ui-bg_highlight-soft_75_cccccc_1x100.png" /> + <Content Include="Content\themes\base\images\ui-icons_222222_256x240.png" /> + <Content Include="Content\themes\base\images\ui-icons_2e83ff_256x240.png" /> + <Content Include="Content\themes\base\images\ui-icons_454545_256x240.png" /> + <Content Include="Content\themes\base\images\ui-icons_888888_256x240.png" /> + <Content Include="Content\themes\base\images\ui-icons_cd0a0a_256x240.png" /> + <Content Include="Content\themes\base\jquery-ui.css" /> + <Content Include="Content\themes\base\jquery.ui.accordion.css" /> + <Content Include="Content\themes\base\jquery.ui.all.css" /> + <Content Include="Content\themes\base\jquery.ui.autocomplete.css" /> + <Content Include="Content\themes\base\jquery.ui.base.css" /> + <Content Include="Content\themes\base\jquery.ui.button.css" /> + <Content Include="Content\themes\base\jquery.ui.core.css" /> + <Content Include="Content\themes\base\jquery.ui.datepicker.css" /> + <Content Include="Content\themes\base\jquery.ui.dialog.css" /> + <Content Include="Content\themes\base\jquery.ui.progressbar.css" /> + <Content Include="Content\themes\base\jquery.ui.resizable.css" /> + <Content Include="Content\themes\base\jquery.ui.selectable.css" /> + <Content Include="Content\themes\base\jquery.ui.slider.css" /> + <Content Include="Content\themes\base\jquery.ui.tabs.css" /> + <Content Include="Content\themes\base\jquery.ui.theme.css" /> + <Content Include="Content\themes\base\minified\images\ui-bg_flat_0_aaaaaa_40x100.png" /> + <Content Include="Content\themes\base\minified\images\ui-bg_flat_75_ffffff_40x100.png" /> + <Content Include="Content\themes\base\minified\images\ui-bg_glass_55_fbf9ee_1x400.png" /> + <Content Include="Content\themes\base\minified\images\ui-bg_glass_65_ffffff_1x400.png" /> + <Content Include="Content\themes\base\minified\images\ui-bg_glass_75_dadada_1x400.png" /> + <Content Include="Content\themes\base\minified\images\ui-bg_glass_75_e6e6e6_1x400.png" /> + <Content Include="Content\themes\base\minified\images\ui-bg_glass_95_fef1ec_1x400.png" /> + <Content Include="Content\themes\base\minified\images\ui-bg_highlight-soft_75_cccccc_1x100.png" /> + <Content Include="Content\themes\base\minified\images\ui-icons_222222_256x240.png" /> + <Content Include="Content\themes\base\minified\images\ui-icons_2e83ff_256x240.png" /> + <Content Include="Content\themes\base\minified\images\ui-icons_454545_256x240.png" /> + <Content Include="Content\themes\base\minified\images\ui-icons_888888_256x240.png" /> + <Content Include="Content\themes\base\minified\images\ui-icons_cd0a0a_256x240.png" /> + <Content Include="Content\themes\base\minified\jquery-ui.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.accordion.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.autocomplete.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.button.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.core.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.datepicker.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.dialog.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.progressbar.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.resizable.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.selectable.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.slider.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.tabs.min.css" /> + <Content Include="Content\themes\base\minified\jquery.ui.theme.min.css" /> + <Content Include="favicon.ico" /> + <Content Include="Global.asax" /> + <None Include="Scripts\jquery-1.7.1.intellisense.js" /> + <Content Include="Scripts\jquery-1.7.1.js" /> + <Content Include="Scripts\jquery-1.7.1.min.js" /> + <None Include="Scripts\jquery.validate-vsdoc.js" /> + <Content Include="Scripts\jquery-ui-1.8.20.js" /> + <Content Include="Scripts\jquery-ui-1.8.20.min.js" /> + <Content Include="Scripts\jquery.unobtrusive-ajax.js" /> + <Content Include="Scripts\jquery.unobtrusive-ajax.min.js" /> + <Content Include="Scripts\jquery.validate.js" /> + <Content Include="Scripts\jquery.validate.min.js" /> + <Content Include="Scripts\jquery.validate.unobtrusive.js" /> + <Content Include="Scripts\jquery.validate.unobtrusive.min.js" /> + <Content Include="Scripts\knockout-2.1.0.debug.js" /> + <Content Include="Scripts\knockout-2.1.0.js" /> + <Content Include="Scripts\modernizr-2.5.3.js" /> + <Content Include="Web.config" /> + <Content Include="Web.Debug.config"> + <DependentUpon>Web.config</DependentUpon> + </Content> + <Content Include="Web.Release.config"> + <DependentUpon>Web.config</DependentUpon> + </Content> + <Content Include="Content\Site.css" /> + <Content Include="Images\accent.png" /> + <Content Include="Images\bullet.png" /> + <Content Include="Images\heroAccent.png" /> + <Content Include="Images\orderedList0.png" /> + <Content Include="Images\orderedList1.png" /> + <Content Include="Images\orderedList2.png" /> + <Content Include="Images\orderedList3.png" /> + <Content Include="Images\orderedList4.png" /> + <Content Include="Images\orderedList5.png" /> + <Content Include="Images\orderedList6.png" /> + <Content Include="Images\orderedList7.png" /> + <Content Include="Images\orderedList8.png" /> + <Content Include="Images\orderedList9.png" /> + <Content Include="Scripts\_references.js" /> + <Content Include="Views\Web.config" /> + <Content Include="Views\_ViewStart.cshtml" /> + <Content Include="Views\Home\Index.cshtml" /> + <Content Include="Views\Shared\Error.cshtml" /> + <Content Include="Views\Shared\_Layout.cshtml" /> + <Content Include="Views\User\Authorize.cshtml" /> + </ItemGroup> + <ItemGroup> + <Folder Include="App_Data\" /> + <Folder Include="Models\" /> + </ItemGroup> + <ItemGroup> + <Content Include="packages.config" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\..\src\DotNetOpenAuth.Core\DotNetOpenAuth.Core.csproj"> + <Project>{60426312-6ae5-4835-8667-37edea670222}</Project> + <Name>DotNetOpenAuth.Core</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth2.AuthorizationServer\DotNetOpenAuth.OAuth2.AuthorizationServer.csproj"> + <Project>{99bb7543-ea16-43ee-a7bc-d7a25a3b22f6}</Project> + <Name>DotNetOpenAuth.OAuth2.AuthorizationServer</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth2.ClientAuthorization\DotNetOpenAuth.OAuth2.ClientAuthorization.csproj"> + <Project>{ccf3728a-b3d7-404a-9bc6-75197135f2d7}</Project> + <Name>DotNetOpenAuth.OAuth2.ClientAuthorization</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth2.ResourceServer\DotNetOpenAuth.OAuth2.ResourceServer.csproj"> + <Project>{a1a3150a-7b0e-4a34-8e35-045296cd3c76}</Project> + <Name>DotNetOpenAuth.OAuth2.ResourceServer</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj"> + <Project>{56459a6c-6ba2-4bac-a9c0-27e3bd961fa6}</Project> + <Name>DotNetOpenAuth.OAuth2</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OpenId.RelyingParty\DotNetOpenAuth.OpenId.RelyingParty.csproj"> + <Project>{f458ab60-ba1c-43d9-8cef-ec01b50be87b}</Project> + <Name>DotNetOpenAuth.OpenId.RelyingParty</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj"> + <Project>{3896a32a-e876-4c23-b9b8-78e17d134cd3}</Project> + <Name>DotNetOpenAuth.OpenId</Name> + </ProjectReference> + </ItemGroup> + <PropertyGroup> + <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> + <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath> + </PropertyGroup> + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> + <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> + <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /> + <Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'"> + <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" /> + </Target> + <ProjectExtensions> + <VisualStudio> + <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"> + <WebProjectProperties> + <UseIIS>True</UseIIS> + <AutoAssignPort>True</AutoAssignPort> + <DevelopmentServerPort>11473</DevelopmentServerPort> + <DevelopmentServerVPath>/</DevelopmentServerVPath> + <IISUrl>http://localhost:23603/</IISUrl> + <NTLMAuthentication>False</NTLMAuthentication> + <UseCustomServer>False</UseCustomServer> + <CustomServerUrl> + </CustomServerUrl> + <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile> + </WebProjectProperties> + </FlavorProperties> + </VisualStudio> + </ProjectExtensions> + <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> --> +</Project>
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Properties/AssemblyInfo.cs b/samples/OAuth2ProtectedWebApi/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..085e1be --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("OAuth2ProtectedWebApi")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("OAuth2ProtectedWebApi")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8c6f3cfe-891a-44f1-8fe6-ef407834ebaf")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/samples/OAuth2ProtectedWebApi/Scripts/_references.js b/samples/OAuth2ProtectedWebApi/Scripts/_references.js Binary files differnew file mode 100644 index 0000000..2ff8876 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/_references.js diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.intellisense.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.intellisense.js new file mode 100644 index 0000000..35a9a25 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.intellisense.js @@ -0,0 +1,2521 @@ +/*! + * Documentation Content + * Copyright (c) 2009 Packt Publishing, http://packtpub.com/ + * Copyright (c) 2012 jQuery Foundation, http://jquery.org/ + * + * This software consists of voluntary contributions made by many + * individuals. For exact contribution history, see the revision history + * and logs, available at http://github.com/jquery/api.jquery.com + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +intellisense.annotate(jQuery, { + 'ajax': function() { + /// <signature> + /// <summary>Perform an asynchronous HTTP (Ajax) request.</summary> + /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> + /// <param name="settings" type="Object">A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings.</param> + /// <returns type="jqXHR" /> + /// </signature> + /// <signature> + /// <summary>Perform an asynchronous HTTP (Ajax) request.</summary> + /// <param name="settings" type="Object">A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().</param> + /// <returns type="jqXHR" /> + /// </signature> + }, + 'ajaxPrefilter': function() { + /// <signature> + /// <summary>Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().</summary> + /// <param name="dataTypes" type="String">An optional string containing one or more space-separated dataTypes</param> + /// <param name="handler(options, originalOptions, jqXHR)" type="Function">A handler to set default values for future Ajax requests.</param> + /// </signature> + }, + 'ajaxSetup': function() { + /// <signature> + /// <summary>Set default values for future Ajax requests.</summary> + /// <param name="options" type="Object">A set of key/value pairs that configure the default Ajax request. All options are optional.</param> + /// </signature> + }, + 'boxModel': function() { + /// <summary>Deprecated in jQuery 1.3 (see jQuery.support). States if the current page, in the user's browser, is being rendered using the W3C CSS Box Model.</summary> + /// <returns type="Boolean" /> + }, + 'browser': function() { + /// <summary>Contains flags for the useragent, read from navigator.userAgent. We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.</summary> + /// <returns type="Map" /> + }, + 'browser.version': function() { + /// <summary>The version number of the rendering engine for the user's browser.</summary> + /// <returns type="String" /> + }, + 'Callbacks': function() { + /// <signature> + /// <summary>A multi-purpose callbacks list object that provides a powerful way to manage callback lists.</summary> + /// <param name="flags" type="String">An optional list of space-separated flags that change how the callback list behaves.</param> + /// </signature> + }, + 'contains': function() { + /// <signature> + /// <summary>Check to see if a DOM element is within another DOM element.</summary> + /// <param name="container" type="Element">The DOM element that may contain the other element.</param> + /// <param name="contained" type="Element">The DOM element that may be contained by the other element.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'cssHooks': function() { + /// <summary>Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties.</summary> + /// <returns type="Object" /> + }, + 'data': function() { + /// <signature> + /// <summary>Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.</summary> + /// <param name="element" type="Element">The DOM element to query for the data.</param> + /// <param name="key" type="String">Name of the data stored.</param> + /// <returns type="Object" /> + /// </signature> + /// <signature> + /// <summary>Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.</summary> + /// <param name="element" type="Element">The DOM element to query for the data.</param> + /// <returns type="Object" /> + /// </signature> + }, + 'dequeue': function() { + /// <signature> + /// <summary>Execute the next function on the queue for the matched element.</summary> + /// <param name="element" type="Element">A DOM element from which to remove and execute a queued function.</param> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'each': function() { + /// <signature> + /// <summary>A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.</summary> + /// <param name="collection" type="Object">The object or array to iterate over.</param> + /// <param name="callback(indexInArray, valueOfElement)" type="Function">The function that will be executed on every object.</param> + /// <returns type="Object" /> + /// </signature> + }, + 'error': function() { + /// <signature> + /// <summary>Takes a string and throws an exception containing it.</summary> + /// <param name="message" type="String">The message to send out.</param> + /// </signature> + }, + 'extend': function() { + /// <signature> + /// <summary>Merge the contents of two or more objects together into the first object.</summary> + /// <param name="target" type="Object">An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument.</param> + /// <param name="object1" type="Object">An object containing additional properties to merge in.</param> + /// <param name="objectN" type="Object">Additional objects containing properties to merge in.</param> + /// <returns type="Object" /> + /// </signature> + /// <signature> + /// <summary>Merge the contents of two or more objects together into the first object.</summary> + /// <param name="deep" type="Boolean">If true, the merge becomes recursive (aka. deep copy).</param> + /// <param name="target" type="Object">The object to extend. It will receive the new properties.</param> + /// <param name="object1" type="Object">An object containing additional properties to merge in.</param> + /// <param name="objectN" type="Object">Additional objects containing properties to merge in.</param> + /// <returns type="Object" /> + /// </signature> + }, + 'get': function() { + /// <signature> + /// <summary>Load data from the server using a HTTP GET request.</summary> + /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> + /// <param name="data" type="String">A map or string that is sent to the server with the request.</param> + /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> + /// <param name="dataType" type="String">The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).</param> + /// <returns type="jqXHR" /> + /// </signature> + }, + 'getJSON': function() { + /// <signature> + /// <summary>Load JSON-encoded data from the server using a GET HTTP request.</summary> + /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> + /// <param name="data" type="Object">A map or string that is sent to the server with the request.</param> + /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> + /// <returns type="jqXHR" /> + /// </signature> + }, + 'getScript': function() { + /// <signature> + /// <summary>Load a JavaScript file from the server using a GET HTTP request, then execute it.</summary> + /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> + /// <param name="success(script, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> + /// <returns type="jqXHR" /> + /// </signature> + }, + 'globalEval': function() { + /// <signature> + /// <summary>Execute some JavaScript code globally.</summary> + /// <param name="code" type="String">The JavaScript code to execute.</param> + /// </signature> + }, + 'grep': function() { + /// <signature> + /// <summary>Finds the elements of an array which satisfy a filter function. The original array is not affected.</summary> + /// <param name="array" type="Array">The array to search through.</param> + /// <param name="function(elementOfArray, indexInArray)" type="Function">The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object.</param> + /// <param name="invert" type="Boolean">If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false.</param> + /// <returns type="Array" /> + /// </signature> + }, + 'hasData': function() { + /// <signature> + /// <summary>Determine whether an element has any jQuery data associated with it.</summary> + /// <param name="element" type="Element">A DOM element to be checked for data.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'holdReady': function() { + /// <signature> + /// <summary>Holds or releases the execution of jQuery's ready event.</summary> + /// <param name="hold" type="Boolean">Indicates whether the ready hold is being requested or released</param> + /// </signature> + }, + 'inArray': function() { + /// <signature> + /// <summary>Search for a specified value within an array and return its index (or -1 if not found).</summary> + /// <param name="value" type="Object">The value to search for.</param> + /// <param name="array" type="Array">An array through which to search.</param> + /// <param name="fromIndex" type="Number">The index of the array at which to begin the search. The default is 0, which will search the whole array.</param> + /// <returns type="Number" /> + /// </signature> + }, + 'isArray': function() { + /// <signature> + /// <summary>Determine whether the argument is an array.</summary> + /// <param name="obj" type="Object">Object to test whether or not it is an array.</param> + /// <returns type="boolean" /> + /// </signature> + }, + 'isEmptyObject': function() { + /// <signature> + /// <summary>Check to see if an object is empty (contains no properties).</summary> + /// <param name="object" type="Object">The object that will be checked to see if it's empty.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'isFunction': function() { + /// <signature> + /// <summary>Determine if the argument passed is a Javascript function object.</summary> + /// <param name="obj" type="Object">Object to test whether or not it is a function.</param> + /// <returns type="boolean" /> + /// </signature> + }, + 'isNumeric': function() { + /// <signature> + /// <summary>Determines whether its argument is a number.</summary> + /// <param name="value" type="Object">The value to be tested.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'isPlainObject': function() { + /// <signature> + /// <summary>Check to see if an object is a plain object (created using "{}" or "new Object").</summary> + /// <param name="object" type="Object">The object that will be checked to see if it's a plain object.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'isWindow': function() { + /// <signature> + /// <summary>Determine whether the argument is a window.</summary> + /// <param name="obj" type="Object">Object to test whether or not it is a window.</param> + /// <returns type="boolean" /> + /// </signature> + }, + 'isXMLDoc': function() { + /// <signature> + /// <summary>Check to see if a DOM node is within an XML document (or is an XML document).</summary> + /// <param name="node" type="Element">The DOM node that will be checked to see if it's in an XML document.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'makeArray': function() { + /// <signature> + /// <summary>Convert an array-like object into a true JavaScript array.</summary> + /// <param name="obj" type="Object">Any object to turn into a native Array.</param> + /// <returns type="Array" /> + /// </signature> + }, + 'map': function() { + /// <signature> + /// <summary>Translate all items in an array or object to new array of items.</summary> + /// <param name="array" type="Array">The Array to translate.</param> + /// <param name="callback(elementOfArray, indexInArray)" type="Function">The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object.</param> + /// <returns type="Array" /> + /// </signature> + /// <signature> + /// <summary>Translate all items in an array or object to new array of items.</summary> + /// <param name="arrayOrObject" type="Object">The Array or Object to translate.</param> + /// <param name="callback( value, indexOrKey )" type="Function">The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.</param> + /// <returns type="Array" /> + /// </signature> + }, + 'merge': function() { + /// <signature> + /// <summary>Merge the contents of two arrays together into the first array.</summary> + /// <param name="first" type="Array">The first array to merge, the elements of second added.</param> + /// <param name="second" type="Array">The second array to merge into the first, unaltered.</param> + /// <returns type="Array" /> + /// </signature> + }, + 'noConflict': function() { + /// <signature> + /// <summary>Relinquish jQuery's control of the $ variable.</summary> + /// <param name="removeAll" type="Boolean">A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).</param> + /// <returns type="Object" /> + /// </signature> + }, + 'noop': function() { + /// <summary>An empty function.</summary> + /// <returns type="Function" /> + }, + 'now': function() { + /// <summary>Return a number representing the current time.</summary> + /// <returns type="Number" /> + }, + 'param': function() { + /// <signature> + /// <summary>Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.</summary> + /// <param name="obj" type="Object">An array or object to serialize.</param> + /// <returns type="String" /> + /// </signature> + /// <signature> + /// <summary>Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.</summary> + /// <param name="obj" type="Object">An array or object to serialize.</param> + /// <param name="traditional" type="Boolean">A Boolean indicating whether to perform a traditional "shallow" serialization.</param> + /// <returns type="String" /> + /// </signature> + }, + 'parseJSON': function() { + /// <signature> + /// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary> + /// <param name="json" type="String">The JSON string to parse.</param> + /// <returns type="Object" /> + /// </signature> + }, + 'parseXML': function() { + /// <signature> + /// <summary>Parses a string into an XML document.</summary> + /// <param name="data" type="String">a well-formed XML string to be parsed</param> + /// <returns type="XMLDocument" /> + /// </signature> + }, + 'post': function() { + /// <signature> + /// <summary>Load data from the server using a HTTP POST request.</summary> + /// <param name="url" type="String">A string containing the URL to which the request is sent.</param> + /// <param name="data" type="String">A map or string that is sent to the server with the request.</param> + /// <param name="success(data, textStatus, jqXHR)" type="Function">A callback function that is executed if the request succeeds.</param> + /// <param name="dataType" type="String">The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).</param> + /// <returns type="jqXHR" /> + /// </signature> + }, + 'proxy': function() { + /// <signature> + /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> + /// <param name="function" type="Function">The function whose context will be changed.</param> + /// <param name="context" type="Object">The object to which the context (this) of the function should be set.</param> + /// <returns type="Function" /> + /// </signature> + /// <signature> + /// <summary>Takes a function and returns a new one that will always have a particular context.</summary> + /// <param name="context" type="Object">The object to which the context of the function should be set.</param> + /// <param name="name" type="String">The name of the function whose context will be changed (should be a property of the context object).</param> + /// <returns type="Function" /> + /// </signature> + }, + 'queue': function() { + /// <signature> + /// <summary>Manipulate the queue of functions to be executed on the matched element.</summary> + /// <param name="element" type="Element">A DOM element where the array of queued functions is attached.</param> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <param name="newQueue" type="Array">An array of functions to replace the current queue contents.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Manipulate the queue of functions to be executed on the matched element.</summary> + /// <param name="element" type="Element">A DOM element on which to add a queued function.</param> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <param name="callback()" type="Function">The new function to add to the queue.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'removeData': function() { + /// <signature> + /// <summary>Remove a previously-stored piece of data.</summary> + /// <param name="element" type="Element">A DOM element from which to remove data.</param> + /// <param name="name" type="String">A string naming the piece of data to remove.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'sub': function() { + /// <summary>Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.</summary> + /// <returns type="jQuery" /> + }, + 'support': function() { + /// <summary>A collection of properties that represent the presence of different browser features or bugs. Primarily intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance.</summary> + /// <returns type="Object" /> + }, + 'trim': function() { + /// <signature> + /// <summary>Remove the whitespace from the beginning and end of a string.</summary> + /// <param name="str" type="String">The string to trim.</param> + /// <returns type="String" /> + /// </signature> + }, + 'type': function() { + /// <signature> + /// <summary>Determine the internal JavaScript [[Class]] of an object.</summary> + /// <param name="obj" type="Object">Object to get the internal JavaScript [[Class]] of.</param> + /// <returns type="String" /> + /// </signature> + }, + 'unique': function() { + /// <signature> + /// <summary>Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.</summary> + /// <param name="array" type="Array">The Array of DOM elements.</param> + /// <returns type="Array" /> + /// </signature> + }, + 'when': function() { + /// <signature> + /// <summary>Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.</summary> + /// <param name="deferreds" type="Deferred">One or more Deferred objects, or plain JavaScript objects.</param> + /// <returns type="Promise" /> + /// </signature> + }, +}); + +var _1228819969 = jQuery.Callbacks; +jQuery.Callbacks = function(flags) { +var _object = _1228819969(flags); +intellisense.annotate(_object, { + 'add': function() { + /// <signature> + /// <summary>Add a callback or a collection of callbacks to a callback list.</summary> + /// <param name="callbacks" type="Function">A function, or array of functions, that are to be added to the callback list.</param> + /// </signature> + }, + 'disable': function() { + /// <summary>Disable a callback list from doing anything more.</summary> + }, + 'empty': function() { + /// <summary>Remove all of the callbacks from a list.</summary> + }, + 'fire': function() { + /// <signature> + /// <summary>Call all of the callbacks with the given arguments</summary> + /// <param name="arguments" type="">The argument or list of arguments to pass back to the callback list.</param> + /// </signature> + }, + 'fired': function() { + /// <summary>Determine if the callbacks have already been called at least once.</summary> + /// <returns type="Boolean" /> + }, + 'fireWith': function() { + /// <signature> + /// <summary>Call all callbacks in a list with the given context and arguments.</summary> + /// <param name="context" type="">A reference to the context in which the callbacks in the list should be fired.</param> + /// <param name="args" type="">An argument, or array of arguments, to pass to the callbacks in the list.</param> + /// </signature> + }, + 'has': function() { + /// <signature> + /// <summary>Determine whether a supplied callback is in a list</summary> + /// <param name="callback" type="Function">The callback to search for.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'lock': function() { + /// <summary>Lock a callback list in its current state.</summary> + }, + 'locked': function() { + /// <summary>Determine if the callbacks list has been locked.</summary> + /// <returns type="Boolean" /> + }, + 'remove': function() { + /// <signature> + /// <summary>Remove a callback or a collection of callbacks from a callback list.</summary> + /// <param name="callbacks" type="Function">A function, or array of functions, that are to be removed from the callback list.</param> + /// </signature> + }, +}); + +return _object; +}; + +var _731531622 = jQuery.Deferred; +jQuery.Deferred = function(func) { +var _object = _731531622(func); +intellisense.annotate(_object, { + 'always': function() { + /// <signature> + /// <summary>Add handlers to be called when the Deferred object is either resolved or rejected.</summary> + /// <param name="alwaysCallbacks" type="Function">A function, or array of functions, that is called when the Deferred is resolved or rejected.</param> + /// <param name="alwaysCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'done': function() { + /// <signature> + /// <summary>Add handlers to be called when the Deferred object is resolved.</summary> + /// <param name="doneCallbacks" type="Function">A function, or array of functions, that are called when the Deferred is resolved.</param> + /// <param name="doneCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is resolved.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'fail': function() { + /// <signature> + /// <summary>Add handlers to be called when the Deferred object is rejected.</summary> + /// <param name="failCallbacks" type="Function">A function, or array of functions, that are called when the Deferred is rejected.</param> + /// <param name="failCallbacks" type="Function">Optional additional functions, or arrays of functions, that are called when the Deferred is rejected.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'isRejected': function() { + /// <summary>Determine whether a Deferred object has been rejected.</summary> + /// <returns type="Boolean" /> + }, + 'isResolved': function() { + /// <summary>Determine whether a Deferred object has been resolved.</summary> + /// <returns type="Boolean" /> + }, + 'notify': function() { + /// <signature> + /// <summary>Call the progressCallbacks on a Deferred object with the given args.</summary> + /// <param name="args" type="Object">Optional arguments that are passed to the progressCallbacks.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'notifyWith': function() { + /// <signature> + /// <summary>Call the progressCallbacks on a Deferred object with the given context and args.</summary> + /// <param name="context" type="Object">Context passed to the progressCallbacks as the this object.</param> + /// <param name="args" type="Object">Optional arguments that are passed to the progressCallbacks.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'pipe': function() { + /// <signature> + /// <summary>Utility method to filter and/or chain Deferreds.</summary> + /// <param name="doneFilter" type="Function">An optional function that is called when the Deferred is resolved.</param> + /// <param name="failFilter" type="Function">An optional function that is called when the Deferred is rejected.</param> + /// <returns type="Promise" /> + /// </signature> + /// <signature> + /// <summary>Utility method to filter and/or chain Deferreds.</summary> + /// <param name="doneFilter" type="Function">An optional function that is called when the Deferred is resolved.</param> + /// <param name="failFilter" type="Function">An optional function that is called when the Deferred is rejected.</param> + /// <param name="progressFilter" type="Function">An optional function that is called when progress notifications are sent to the Deferred.</param> + /// <returns type="Promise" /> + /// </signature> + }, + 'progress': function() { + /// <signature> + /// <summary>Add handlers to be called when the Deferred object generates progress notifications.</summary> + /// <param name="progressCallbacks" type="Function">A function, or array of functions, that is called when the Deferred generates progress notifications.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'promise': function() { + /// <signature> + /// <summary>Return a Deferred's Promise object.</summary> + /// <param name="target" type="Object">Object onto which the promise methods have to be attached</param> + /// <returns type="Promise" /> + /// </signature> + }, + 'reject': function() { + /// <signature> + /// <summary>Reject a Deferred object and call any failCallbacks with the given args.</summary> + /// <param name="args" type="Object">Optional arguments that are passed to the failCallbacks.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'rejectWith': function() { + /// <signature> + /// <summary>Reject a Deferred object and call any failCallbacks with the given context and args.</summary> + /// <param name="context" type="Object">Context passed to the failCallbacks as the this object.</param> + /// <param name="args" type="Array">An optional array of arguments that are passed to the failCallbacks.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'resolve': function() { + /// <signature> + /// <summary>Resolve a Deferred object and call any doneCallbacks with the given args.</summary> + /// <param name="args" type="Object">Optional arguments that are passed to the doneCallbacks.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'resolveWith': function() { + /// <signature> + /// <summary>Resolve a Deferred object and call any doneCallbacks with the given context and args.</summary> + /// <param name="context" type="Object">Context passed to the doneCallbacks as the this object.</param> + /// <param name="args" type="Array">An optional array of arguments that are passed to the doneCallbacks.</param> + /// <returns type="Deferred" /> + /// </signature> + }, + 'state': function() { + /// <summary>Determine the current state of a Deferred object.</summary> + /// <returns type="String" /> + }, + 'then': function() { + /// <signature> + /// <summary>Add handlers to be called when the Deferred object is resolved or rejected.</summary> + /// <param name="doneCallbacks" type="Function">A function, or array of functions, called when the Deferred is resolved.</param> + /// <param name="failCallbacks" type="Function">A function, or array of functions, called when the Deferred is rejected.</param> + /// <returns type="Deferred" /> + /// </signature> + /// <signature> + /// <summary>Add handlers to be called when the Deferred object is resolved or rejected.</summary> + /// <param name="doneCallbacks" type="Function">A function, or array of functions, called when the Deferred is resolved.</param> + /// <param name="failCallbacks" type="Function">A function, or array of functions, called when the Deferred is rejected.</param> + /// <param name="progressCallbacks" type="Function">A function, or array of functions, called when the Deferred notifies progress.</param> + /// <returns type="Deferred" /> + /// </signature> + }, +}); + +return _object; +}; + +intellisense.annotate(jQuery.Event.prototype, { + 'currentTarget': function() { + /// <summary>The current DOM element within the event bubbling phase.</summary> + /// <returns type="Element" /> + }, + 'data': function() { + /// <summary>An optional data map passed to an event method when the current executing handler is bound.</summary> + }, + 'delegateTarget': function() { + /// <summary>The element where the currently-called jQuery event handler was attached.</summary> + /// <returns type="Element" /> + }, + 'isDefaultPrevented': function() { + /// <summary>Returns whether event.preventDefault() was ever called on this event object.</summary> + /// <returns type="Boolean" /> + }, + 'isImmediatePropagationStopped': function() { + /// <summary>Returns whether event.stopImmediatePropagation() was ever called on this event object.</summary> + /// <returns type="Boolean" /> + }, + 'isPropagationStopped': function() { + /// <summary>Returns whether event.stopPropagation() was ever called on this event object.</summary> + /// <returns type="Boolean" /> + }, + 'namespace': function() { + /// <summary>The namespace specified when the event was triggered.</summary> + /// <returns type="String" /> + }, + 'pageX': function() { + /// <summary>The mouse position relative to the left edge of the document.</summary> + /// <returns type="Number" /> + }, + 'pageY': function() { + /// <summary>The mouse position relative to the top edge of the document.</summary> + /// <returns type="Number" /> + }, + 'preventDefault': function() { + /// <summary>If this method is called, the default action of the event will not be triggered.</summary> + }, + 'relatedTarget': function() { + /// <summary>The other DOM element involved in the event, if any.</summary> + /// <returns type="Element" /> + }, + 'result': function() { + /// <summary>The last value returned by an event handler that was triggered by this event, unless the value was undefined.</summary> + /// <returns type="Object" /> + }, + 'stopImmediatePropagation': function() { + /// <summary>Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.</summary> + }, + 'stopPropagation': function() { + /// <summary>Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.</summary> + }, + 'target': function() { + /// <summary>The DOM element that initiated the event.</summary> + /// <returns type="Element" /> + }, + 'timeStamp': function() { + /// <summary>The difference in milliseconds between the time the browser created the event and January 1, 1970.</summary> + /// <returns type="Number" /> + }, + 'type': function() { + /// <summary>Describes the nature of the event.</summary> + /// <returns type="String" /> + }, + 'which': function() { + /// <summary>For key or mouse events, this property indicates the specific key or button that was pressed.</summary> + /// <returns type="Number" /> + }, +}); + +intellisense.annotate(jQuery.fn, { + 'add': function() { + /// <signature> + /// <summary>Add elements to the set of matched elements.</summary> + /// <param name="selector" type="String">A string representing a selector expression to find additional elements to add to the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add elements to the set of matched elements.</summary> + /// <param name="elements" type="Array">One or more elements to add to the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add elements to the set of matched elements.</summary> + /// <param name="html" type="String">An HTML fragment to add to the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add elements to the set of matched elements.</summary> + /// <param name="jQuery object" type="jQuery object ">An existing jQuery object to add to the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add elements to the set of matched elements.</summary> + /// <param name="selector" type="String">A string representing a selector expression to find additional elements to add to the set of matched elements.</param> + /// <param name="context" type="Element">The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'addClass': function() { + /// <signature> + /// <summary>Adds the specified class(es) to each of the set of matched elements.</summary> + /// <param name="className" type="String">One or more class names to be added to the class attribute of each matched element.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Adds the specified class(es) to each of the set of matched elements.</summary> + /// <param name="function(index, currentClass)" type="Function">A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'after': function() { + /// <signature> + /// <summary>Insert content, specified by the parameter, after each element in the set of matched elements.</summary> + /// <param name="content" type="jQuery">HTML string, DOM element, or jQuery object to insert after each element in the set of matched elements.</param> + /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Insert content, specified by the parameter, after each element in the set of matched elements.</summary> + /// <param name="function(index)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'ajaxComplete': function() { + /// <signature> + /// <summary>Register a handler to be called when Ajax requests complete. This is an Ajax Event.</summary> + /// <param name="handler(event, XMLHttpRequest, ajaxOptions)" type="Function">The function to be invoked.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'ajaxError': function() { + /// <signature> + /// <summary>Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.</summary> + /// <param name="handler(event, jqXHR, ajaxSettings, thrownError)" type="Function">The function to be invoked.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'ajaxSend': function() { + /// <signature> + /// <summary>Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.</summary> + /// <param name="handler(event, jqXHR, ajaxOptions)" type="Function">The function to be invoked.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'ajaxStart': function() { + /// <signature> + /// <summary>Register a handler to be called when the first Ajax request begins. This is an Ajax Event.</summary> + /// <param name="handler()" type="Function">The function to be invoked.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'ajaxStop': function() { + /// <signature> + /// <summary>Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.</summary> + /// <param name="handler()" type="Function">The function to be invoked.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'ajaxSuccess': function() { + /// <signature> + /// <summary>Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.</summary> + /// <param name="handler(event, XMLHttpRequest, ajaxOptions)" type="Function">The function to be invoked.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'all': function() { + /// <summary>Selects all elements.</summary> + }, + 'andSelf': function() { + /// <summary>Add the previous set of elements on the stack to the current set.</summary> + /// <returns type="jQuery" /> + }, + 'animate': function() { + /// <signature> + /// <summary>Perform a custom animation of a set of CSS properties.</summary> + /// <param name="properties" type="Object">A map of CSS properties that the animation will move toward.</param> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="complete" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Perform a custom animation of a set of CSS properties.</summary> + /// <param name="properties" type="Object">A map of CSS properties that the animation will move toward.</param> + /// <param name="options" type="Object">A map of additional options to pass to the method. Supported keys: duration: A string or number determining how long the animation will run.easing: A string indicating which easing function to use for the transition.complete: A function to call once the animation is complete.step: A function to be called after each step of the animation.queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string.specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions (added 1.4).</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'animated': function() { + /// <summary>Select all elements that are in the progress of an animation at the time the selector is run.</summary> + }, + 'append': function() { + /// <signature> + /// <summary>Insert content, specified by the parameter, to the end of each element in the set of matched elements.</summary> + /// <param name="content" type="jQuery">DOM element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param> + /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Insert content, specified by the parameter, to the end of each element in the set of matched elements.</summary> + /// <param name="function(index, html)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'appendTo': function() { + /// <signature> + /// <summary>Insert every element in the set of matched elements to the end of the target.</summary> + /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'attr': function() { + /// <signature> + /// <summary>Set one or more attributes for the set of matched elements.</summary> + /// <param name="attributeName" type="String">The name of the attribute to set.</param> + /// <param name="value" type="Number">A value to set for the attribute.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set one or more attributes for the set of matched elements.</summary> + /// <param name="map" type="Object">A map of attribute-value pairs to set.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set one or more attributes for the set of matched elements.</summary> + /// <param name="attributeName" type="String">The name of the attribute to set.</param> + /// <param name="function(index, attr)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'attributeContains': function() { + /// <signature> + /// <summary>Selects elements that have the specified attribute with a value containing the a given substring.</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> + /// </signature> + }, + 'attributeContainsPrefix': function() { + /// <signature> + /// <summary>Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> + /// </signature> + }, + 'attributeContainsWord': function() { + /// <signature> + /// <summary>Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> + /// </signature> + }, + 'attributeEndsWith': function() { + /// <signature> + /// <summary>Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> + /// </signature> + }, + 'attributeEquals': function() { + /// <signature> + /// <summary>Selects elements that have the specified attribute with a value exactly equal to a certain value.</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> + /// </signature> + }, + 'attributeHas': function() { + /// <signature> + /// <summary>Selects elements that have the specified attribute, with any value.</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// </signature> + }, + 'attributeMultiple': function() { + /// <signature> + /// <summary>Matches elements that match all of the specified attribute filters.</summary> + /// <param name="attributeFilter1" type="String">An attribute filter.</param> + /// <param name="attributeFilter2" type="String">Another attribute filter, reducing the selection even more</param> + /// <param name="attributeFilterN" type="String">As many more attribute filters as necessary</param> + /// </signature> + }, + 'attributeNotEqual': function() { + /// <signature> + /// <summary>Select elements that either don't have the specified attribute, or do have the specified attribute but not with a certain value.</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> + /// </signature> + }, + 'attributeStartsWith': function() { + /// <signature> + /// <summary>Selects elements that have the specified attribute with a value beginning exactly with a given string.</summary> + /// <param name="attribute" type="String">An attribute name.</param> + /// <param name="value" type="String">An attribute value. Can be either an unquoted single word or a quoted string.</param> + /// </signature> + }, + 'before': function() { + /// <signature> + /// <summary>Insert content, specified by the parameter, before each element in the set of matched elements.</summary> + /// <param name="content" type="jQuery">HTML string, DOM element, or jQuery object to insert before each element in the set of matched elements.</param> + /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Insert content, specified by the parameter, before each element in the set of matched elements.</summary> + /// <param name="function" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'bind': function() { + /// <signature> + /// <summary>Attach a handler to an event for the elements.</summary> + /// <param name="eventType" type="String">A string containing one or more DOM event types, such as "click" or "submit," or custom event names.</param> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach a handler to an event for the elements.</summary> + /// <param name="eventType" type="String">A string containing one or more DOM event types, such as "click" or "submit," or custom event names.</param> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="preventBubble" type="Boolean">Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach a handler to an event for the elements.</summary> + /// <param name="events" type="Object">A map of one or more DOM event types and functions to execute for them.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'blur': function() { + /// <signature> + /// <summary>Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "blur" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'button': function() { + /// <summary>Selects all button elements and elements of type button.</summary> + }, + 'change': function() { + /// <signature> + /// <summary>Bind an event handler to the "change" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "change" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'checkbox': function() { + /// <summary>Selects all elements of type checkbox.</summary> + }, + 'checked': function() { + /// <summary>Matches all elements that are checked.</summary> + }, + 'child': function() { + /// <signature> + /// <summary>Selects all direct child elements specified by "child" of elements specified by "parent".</summary> + /// <param name="parent" type="String">Any valid selector.</param> + /// <param name="child" type="String">A selector to filter the child elements.</param> + /// </signature> + }, + 'children': function() { + /// <signature> + /// <summary>Get the children of each element in the set of matched elements, optionally filtered by a selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'class': function() { + /// <signature> + /// <summary>Selects all elements with the given class.</summary> + /// <param name="class" type="String">A class to search for. An element can have multiple classes; only one of them must match.</param> + /// </signature> + }, + 'clearQueue': function() { + /// <signature> + /// <summary>Remove from the queue all items that have not yet been run.</summary> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'click': function() { + /// <signature> + /// <summary>Bind an event handler to the "click" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "click" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'clone': function() { + /// <signature> + /// <summary>Create a deep copy of the set of matched elements.</summary> + /// <param name="withDataAndEvents" type="Boolean">A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Create a deep copy of the set of matched elements.</summary> + /// <param name="withDataAndEvents" type="Boolean">A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back to false in 1.5.1 and up.</param> + /// <param name="deepWithDataAndEvents" type="Boolean">A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'closest': function() { + /// <signature> + /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <param name="context" type="Element">A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> + /// <param name="jQuery object" type="jQuery">A jQuery object to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</summary> + /// <param name="element" type="Element">An element to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'contains': function() { + /// <signature> + /// <summary>Select all elements that contain the specified text.</summary> + /// <param name="text" type="String">A string of text to look for. It's case sensitive.</param> + /// </signature> + }, + 'contents': function() { + /// <summary>Get the children of each element in the set of matched elements, including text and comment nodes.</summary> + /// <returns type="jQuery" /> + }, + 'context': function() { + /// <summary>The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document.</summary> + /// <returns type="Element" /> + }, + 'css': function() { + /// <signature> + /// <summary>Set one or more CSS properties for the set of matched elements.</summary> + /// <param name="propertyName" type="String">A CSS property name.</param> + /// <param name="value" type="Number">A value to set for the property.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set one or more CSS properties for the set of matched elements.</summary> + /// <param name="propertyName" type="String">A CSS property name.</param> + /// <param name="function(index, value)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set one or more CSS properties for the set of matched elements.</summary> + /// <param name="map" type="Object">A map of property-value pairs to set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'data': function() { + /// <signature> + /// <summary>Store arbitrary data associated with the matched elements.</summary> + /// <param name="key" type="String">A string naming the piece of data to set.</param> + /// <param name="value" type="Object">The new data value; it can be any Javascript type including Array or Object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Store arbitrary data associated with the matched elements.</summary> + /// <param name="obj" type="Object">An object of key-value pairs of data to update.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'dblclick': function() { + /// <signature> + /// <summary>Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'delay': function() { + /// <signature> + /// <summary>Set a timer to delay execution of subsequent items in the queue.</summary> + /// <param name="duration" type="Number">An integer indicating the number of milliseconds to delay execution of the next item in the queue.</param> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'delegate': function() { + /// <signature> + /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> + /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> + /// <param name="eventType" type="String">A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> + /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> + /// <param name="eventType" type="String">A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.</param> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.</summary> + /// <param name="selector" type="String">A selector to filter the elements that trigger the event.</param> + /// <param name="events" type="Object">A map of one or more event types and functions to execute for them.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'dequeue': function() { + /// <signature> + /// <summary>Execute the next function on the queue for the matched elements.</summary> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'descendant': function() { + /// <signature> + /// <summary>Selects all elements that are descendants of a given ancestor.</summary> + /// <param name="ancestor" type="String">Any valid selector.</param> + /// <param name="descendant" type="String">A selector to filter the descendant elements.</param> + /// </signature> + }, + 'detach': function() { + /// <signature> + /// <summary>Remove the set of matched elements from the DOM.</summary> + /// <param name="selector" type="String">A selector expression that filters the set of matched elements to be removed.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'die': function() { + /// <signature> + /// <summary>Remove an event handler previously attached using .live() from the elements.</summary> + /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or keydown.</param> + /// <param name="handler" type="String">The function that is no longer to be executed.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove an event handler previously attached using .live() from the elements.</summary> + /// <param name="eventTypes" type="Object">A map of one or more event types, such as click or keydown and their corresponding functions that are no longer to be executed.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'disabled': function() { + /// <summary>Selects all elements that are disabled.</summary> + }, + 'each': function() { + /// <signature> + /// <summary>Iterate over a jQuery object, executing a function for each matched element.</summary> + /// <param name="function(index, Element)" type="Function">A function to execute for each matched element.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'element': function() { + /// <signature> + /// <summary>Selects all elements with the given tag name.</summary> + /// <param name="element" type="String">An element to search for. Refers to the tagName of DOM nodes.</param> + /// </signature> + }, + 'empty': function() { + /// <summary>Select all elements that have no children (including text nodes).</summary> + }, + 'enabled': function() { + /// <summary>Selects all elements that are enabled.</summary> + }, + 'end': function() { + /// <summary>End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.</summary> + /// <returns type="jQuery" /> + }, + 'eq': function() { + /// <signature> + /// <summary>Reduce the set of matched elements to the one at the specified index.</summary> + /// <param name="index" type="Number">An integer indicating the 0-based position of the element.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Reduce the set of matched elements to the one at the specified index.</summary> + /// <param name="-index" type="Number">An integer indicating the position of the element, counting backwards from the last element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'error': function() { + /// <signature> + /// <summary>Bind an event handler to the "error" JavaScript event.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "error" JavaScript event.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'even': function() { + /// <summary>Selects even elements, zero-indexed. See also odd.</summary> + }, + 'fadeIn': function() { + /// <signature> + /// <summary>Display the matched elements by fading them to opaque.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Display the matched elements by fading them to opaque.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'fadeOut': function() { + /// <signature> + /// <summary>Hide the matched elements by fading them to transparent.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Hide the matched elements by fading them to transparent.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'fadeTo': function() { + /// <signature> + /// <summary>Adjust the opacity of the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="opacity" type="Number">A number between 0 and 1 denoting the target opacity.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Adjust the opacity of the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="opacity" type="Number">A number between 0 and 1 denoting the target opacity.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'fadeToggle': function() { + /// <signature> + /// <summary>Display or hide the matched elements by animating their opacity.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'file': function() { + /// <summary>Selects all elements of type file.</summary> + }, + 'filter': function() { + /// <signature> + /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match the current set of elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> + /// <param name="function(index)" type="Function">A function used as a test for each element in the set. this is the current DOM element.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> + /// <param name="element" type="Element">An element to match the current set of elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Reduce the set of matched elements to those that match the selector or pass the function's test.</summary> + /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'find': function() { + /// <signature> + /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> + /// <param name="jQuery object" type="Object">A jQuery object to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.</summary> + /// <param name="element" type="Element">An element to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'first': function() { + /// <summary>Selects the first matched element.</summary> + }, + 'first-child': function() { + /// <summary>Selects all elements that are the first child of their parent.</summary> + }, + 'focus': function() { + /// <signature> + /// <summary>Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'focusin': function() { + /// <signature> + /// <summary>Bind an event handler to the "focusin" event.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "focusin" event.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'focusout': function() { + /// <signature> + /// <summary>Bind an event handler to the "focusout" JavaScript event.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "focusout" JavaScript event.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'get': function() { + /// <signature> + /// <summary>Retrieve the DOM elements matched by the jQuery object.</summary> + /// <param name="index" type="Number">A zero-based integer indicating which element to retrieve.</param> + /// <returns type="Element, Array" /> + /// </signature> + }, + 'gt': function() { + /// <signature> + /// <summary>Select all elements at an index greater than index within the matched set.</summary> + /// <param name="index" type="Number">Zero-based index.</param> + /// </signature> + }, + 'has': function() { + /// <signature> + /// <summary>Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.</summary> + /// <param name="contained" type="Element">A DOM element to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'hasClass': function() { + /// <signature> + /// <summary>Determine whether any of the matched elements are assigned the given class.</summary> + /// <param name="className" type="String">The class name to search for.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'header': function() { + /// <summary>Selects all elements that are headers, like h1, h2, h3 and so on.</summary> + }, + 'height': function() { + /// <signature> + /// <summary>Set the CSS height of every matched element.</summary> + /// <param name="value" type="Number">An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set the CSS height of every matched element.</summary> + /// <param name="function(index, height)" type="Function">A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'hidden': function() { + /// <summary>Selects all elements that are hidden.</summary> + }, + 'hide': function() { + /// <signature> + /// <summary>Hide the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Hide the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'hover': function() { + /// <signature> + /// <summary>Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.</summary> + /// <param name="handlerIn(eventObject)" type="Function">A function to execute when the mouse pointer enters the element.</param> + /// <param name="handlerOut(eventObject)" type="Function">A function to execute when the mouse pointer leaves the element.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'html': function() { + /// <signature> + /// <summary>Set the HTML contents of each element in the set of matched elements.</summary> + /// <param name="htmlString" type="String">A string of HTML to set as the content of each matched element.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set the HTML contents of each element in the set of matched elements.</summary> + /// <param name="function(index, oldhtml)" type="Function">A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'id': function() { + /// <signature> + /// <summary>Selects a single element with the given id attribute.</summary> + /// <param name="id" type="String">An ID to search for, specified via the id attribute of an element.</param> + /// </signature> + }, + 'image': function() { + /// <summary>Selects all elements of type image.</summary> + }, + 'index': function() { + /// <signature> + /// <summary>Search for a given element from among the matched elements.</summary> + /// <param name="selector" type="String">A selector representing a jQuery collection in which to look for an element.</param> + /// <returns type="Number" /> + /// </signature> + /// <signature> + /// <summary>Search for a given element from among the matched elements.</summary> + /// <param name="element" type="jQuery">The DOM element or first element within the jQuery object to look for.</param> + /// <returns type="Number" /> + /// </signature> + }, + 'init': function() { + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="selector" type="String">A string containing a selector expression</param> + /// <param name="context" type="jQuery">A DOM Element, Document, or jQuery to use as context</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="element" type="Element">A DOM element to wrap in a jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="object" type="Object">A plain object to wrap in a jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="elementArray" type="Array">An array containing a set of DOM elements to wrap in a jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="jQuery object" type="Object">An existing jQuery object to clone.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'innerHeight': function() { + /// <summary>Get the current computed height for the first element in the set of matched elements, including padding but not border.</summary> + /// <returns type="Integer" /> + }, + 'innerWidth': function() { + /// <summary>Get the current computed width for the first element in the set of matched elements, including padding but not border.</summary> + /// <returns type="Integer" /> + }, + 'input': function() { + /// <summary>Selects all input, textarea, select and button elements.</summary> + }, + 'insertAfter': function() { + /// <signature> + /// <summary>Insert every element in the set of matched elements after the target.</summary> + /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'insertBefore': function() { + /// <signature> + /// <summary>Insert every element in the set of matched elements before the target.</summary> + /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'is': function() { + /// <signature> + /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="Boolean" /> + /// </signature> + /// <signature> + /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> + /// <param name="function(index)" type="Function">A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element.</param> + /// <returns type="Boolean" /> + /// </signature> + /// <signature> + /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> + /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> + /// <returns type="Boolean" /> + /// </signature> + /// <signature> + /// <summary>Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.</summary> + /// <param name="element" type="Element">An element to match the current set of elements against.</param> + /// <returns type="Boolean" /> + /// </signature> + }, + 'jquery': function() { + /// <summary>A string containing the jQuery version number.</summary> + /// <returns type="String" /> + }, + 'keydown': function() { + /// <signature> + /// <summary>Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'keypress': function() { + /// <signature> + /// <summary>Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'keyup': function() { + /// <signature> + /// <summary>Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'last': function() { + /// <summary>Selects the last matched element.</summary> + }, + 'last-child': function() { + /// <summary>Selects all elements that are the last child of their parent.</summary> + }, + 'length': function() { + /// <summary>The number of elements in the jQuery object.</summary> + /// <returns type="Number" /> + }, + 'live': function() { + /// <signature> + /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> + /// <param name="events" type="String">A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> + /// <param name="events" type="String">A string containing a JavaScript event type, such as "click" or "keydown." As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names.</param> + /// <param name="data" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach an event handler for all elements which match the current selector, now and in the future.</summary> + /// <param name="events-map" type="Object">A map of one or more JavaScript event types and functions to execute for them.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'load': function() { + /// <signature> + /// <summary>Bind an event handler to the "load" JavaScript event.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "load" JavaScript event.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'lt': function() { + /// <signature> + /// <summary>Select all elements at an index less than index within the matched set.</summary> + /// <param name="index" type="Number">Zero-based index.</param> + /// </signature> + }, + 'map': function() { + /// <signature> + /// <summary>Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.</summary> + /// <param name="callback(index, domElement)" type="Function">A function object that will be invoked for each element in the current set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'mousedown': function() { + /// <signature> + /// <summary>Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'mouseenter': function() { + /// <signature> + /// <summary>Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'mouseleave': function() { + /// <signature> + /// <summary>Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'mousemove': function() { + /// <signature> + /// <summary>Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'mouseout': function() { + /// <signature> + /// <summary>Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'mouseover': function() { + /// <signature> + /// <summary>Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'mouseup': function() { + /// <signature> + /// <summary>Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'multiple': function() { + /// <signature> + /// <summary>Selects the combined results of all the specified selectors.</summary> + /// <param name="selector1" type="String">Any valid selector.</param> + /// <param name="selector2" type="String">Another valid selector.</param> + /// <param name="selectorN" type="String">As many more valid selectors as you like.</param> + /// </signature> + }, + 'next': function() { + /// <signature> + /// <summary>Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'next adjacent': function() { + /// <signature> + /// <summary>Selects all next elements matching "next" that are immediately preceded by a sibling "prev".</summary> + /// <param name="prev" type="String">Any valid selector.</param> + /// <param name="next" type="String">A selector to match the element that is next to the first selector.</param> + /// </signature> + }, + 'next siblings': function() { + /// <signature> + /// <summary>Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.</summary> + /// <param name="prev" type="String">Any valid selector.</param> + /// <param name="siblings" type="String">A selector to filter elements that are the following siblings of the first selector.</param> + /// </signature> + }, + 'nextAll': function() { + /// <signature> + /// <summary>Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'nextUntil': function() { + /// <signature> + /// <summary>Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.</summary> + /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching following sibling elements.</param> + /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.</summary> + /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching following sibling elements.</param> + /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'not': function() { + /// <signature> + /// <summary>Remove elements from the set of matched elements.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove elements from the set of matched elements.</summary> + /// <param name="elements" type="Array">One or more DOM elements to remove from the matched set.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove elements from the set of matched elements.</summary> + /// <param name="function(index)" type="Function">A function used as a test for each element in the set. this is the current DOM element.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove elements from the set of matched elements.</summary> + /// <param name="jQuery object" type="Object">An existing jQuery object to match the current set of elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'nth-child': function() { + /// <signature> + /// <summary>Selects all elements that are the nth-child of their parent.</summary> + /// <param name="index" type="String">The index of each child to match, starting with 1, the string even or odd, or an equation ( eg. :nth-child(even), :nth-child(4n) )</param> + /// </signature> + }, + 'odd': function() { + /// <summary>Selects odd elements, zero-indexed. See also even.</summary> + }, + 'off': function() { + /// <signature> + /// <summary>Remove an event handler.</summary> + /// <param name="events" type="String">One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".</param> + /// <param name="selector" type="String">A selector which should match the one originally passed to .on() when attaching event handlers.</param> + /// <param name="handler(eventObject)" type="Function">A handler function previously attached for the event(s), or the special value false.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove an event handler.</summary> + /// <param name="events-map" type="Object">A map where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s).</param> + /// <param name="selector" type="String">A selector which should match the one originally passed to .on() when attaching event handlers.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'offset': function() { + /// <signature> + /// <summary>Set the current coordinates of every element in the set of matched elements, relative to the document.</summary> + /// <param name="coordinates" type="Object">An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set the current coordinates of every element in the set of matched elements, relative to the document.</summary> + /// <param name="function(index, coords)" type="Function">A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'offsetParent': function() { + /// <summary>Get the closest ancestor element that is positioned.</summary> + /// <returns type="jQuery" /> + }, + 'on': function() { + /// <signature> + /// <summary>Attach an event handler function for one or more events to the selected elements.</summary> + /// <param name="events" type="String">One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".</param> + /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.</param> + /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event is triggered.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach an event handler function for one or more events to the selected elements.</summary> + /// <param name="events-map" type="Object">A map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).</param> + /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.</param> + /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event occurs.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'one': function() { + /// <signature> + /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> + /// <param name="events" type="String">A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.</param> + /// <param name="data" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> + /// <param name="events" type="String">One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".</param> + /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.</param> + /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event is triggered.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Attach a handler to an event for the elements. The handler is executed at most once per element.</summary> + /// <param name="events-map" type="Object">A map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).</param> + /// <param name="selector" type="String">A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.</param> + /// <param name="data" type="Anything">Data to be passed to the handler in event.data when an event occurs.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'only-child': function() { + /// <summary>Selects all elements that are the only child of their parent.</summary> + }, + 'outerHeight': function() { + /// <signature> + /// <summary>Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements.</summary> + /// <param name="includeMargin" type="Boolean">A Boolean indicating whether to include the element's margin in the calculation.</param> + /// <returns type="Integer" /> + /// </signature> + }, + 'outerWidth': function() { + /// <signature> + /// <summary>Get the current computed width for the first element in the set of matched elements, including padding and border.</summary> + /// <param name="includeMargin" type="Boolean">A Boolean indicating whether to include the element's margin in the calculation.</param> + /// <returns type="Integer" /> + /// </signature> + }, + 'parent': function() { + /// <signature> + /// <summary>Get the parent of each element in the current set of matched elements, optionally filtered by a selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'parents': function() { + /// <signature> + /// <summary>Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'parentsUntil': function() { + /// <signature> + /// <summary>Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> + /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching ancestor elements.</param> + /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> + /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching ancestor elements.</param> + /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'password': function() { + /// <summary>Selects all elements of type password.</summary> + }, + 'position': function() { + /// <summary>Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.</summary> + /// <returns type="Object" /> + }, + 'prepend': function() { + /// <signature> + /// <summary>Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.</summary> + /// <param name="content" type="jQuery">DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.</param> + /// <param name="content" type="jQuery">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.</summary> + /// <param name="function(index, html)" type="Function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'prependTo': function() { + /// <signature> + /// <summary>Insert every element in the set of matched elements to the beginning of the target.</summary> + /// <param name="target" type="jQuery">A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'prev': function() { + /// <signature> + /// <summary>Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'prevAll': function() { + /// <signature> + /// <summary>Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'prevUntil': function() { + /// <signature> + /// <summary>Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> + /// <param name="selector" type="String">A string containing a selector expression to indicate where to stop matching preceding sibling elements.</param> + /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.</summary> + /// <param name="element" type="Element">A DOM node or jQuery object indicating where to stop matching preceding sibling elements.</param> + /// <param name="filter" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'promise': function() { + /// <signature> + /// <summary>Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.</summary> + /// <param name="type" type="String">The type of queue that needs to be observed.</param> + /// <param name="target" type="Object">Object onto which the promise methods have to be attached</param> + /// <returns type="Promise" /> + /// </signature> + }, + 'prop': function() { + /// <signature> + /// <summary>Set one or more properties for the set of matched elements.</summary> + /// <param name="propertyName" type="String">The name of the property to set.</param> + /// <param name="value" type="Boolean">A value to set for the property.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set one or more properties for the set of matched elements.</summary> + /// <param name="map" type="Object">A map of property-value pairs to set.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set one or more properties for the set of matched elements.</summary> + /// <param name="propertyName" type="String">The name of the property to set.</param> + /// <param name="function(index, oldPropertyValue)" type="Function">A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'pushStack': function() { + /// <signature> + /// <summary>Add a collection of DOM elements onto the jQuery stack.</summary> + /// <param name="elements" type="Array">An array of elements to push onto the stack and make into a new jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add a collection of DOM elements onto the jQuery stack.</summary> + /// <param name="elements" type="Array">An array of elements to push onto the stack and make into a new jQuery object.</param> + /// <param name="name" type="String">The name of a jQuery method that generated the array of elements.</param> + /// <param name="arguments" type="Array">The arguments that were passed in to the jQuery method (for serialization).</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'queue': function() { + /// <signature> + /// <summary>Manipulate the queue of functions to be executed on the matched elements.</summary> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <param name="newQueue" type="Array">An array of functions to replace the current queue contents.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Manipulate the queue of functions to be executed on the matched elements.</summary> + /// <param name="queueName" type="String">A string containing the name of the queue. Defaults to fx, the standard effects queue.</param> + /// <param name="callback( next )" type="Function">The new function to add to the queue, with a function to call that will dequeue the next item.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'radio': function() { + /// <summary>Selects all elements of type radio.</summary> + }, + 'ready': function() { + /// <signature> + /// <summary>Specify a function to execute when the DOM is fully loaded.</summary> + /// <param name="handler" type="Function">A function to execute after the DOM is ready.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'remove': function() { + /// <signature> + /// <summary>Remove the set of matched elements from the DOM.</summary> + /// <param name="selector" type="String">A selector expression that filters the set of matched elements to be removed.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'removeAttr': function() { + /// <signature> + /// <summary>Remove an attribute from each element in the set of matched elements.</summary> + /// <param name="attributeName" type="String">An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'removeClass': function() { + /// <signature> + /// <summary>Remove a single class, multiple classes, or all classes from each element in the set of matched elements.</summary> + /// <param name="className" type="String">One or more space-separated classes to be removed from the class attribute of each matched element.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove a single class, multiple classes, or all classes from each element in the set of matched elements.</summary> + /// <param name="function(index, class)" type="Function">A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'removeData': function() { + /// <signature> + /// <summary>Remove a previously-stored piece of data.</summary> + /// <param name="name" type="String">A string naming the piece of data to delete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove a previously-stored piece of data.</summary> + /// <param name="list" type="String">An array or space-separated string naming the pieces of data to delete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'removeProp': function() { + /// <signature> + /// <summary>Remove a property for the set of matched elements.</summary> + /// <param name="propertyName" type="String">The name of the property to set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'replaceAll': function() { + /// <signature> + /// <summary>Replace each target element with the set of matched elements.</summary> + /// <param name="target" type="String">A selector expression indicating which element(s) to replace.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'replaceWith': function() { + /// <signature> + /// <summary>Replace each element in the set of matched elements with the provided new content.</summary> + /// <param name="newContent" type="jQuery">The content to insert. May be an HTML string, DOM element, or jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Replace each element in the set of matched elements with the provided new content.</summary> + /// <param name="function" type="Function">A function that returns content with which to replace the set of matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'reset': function() { + /// <summary>Selects all elements of type reset.</summary> + }, + 'resize': function() { + /// <signature> + /// <summary>Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "resize" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'scroll': function() { + /// <signature> + /// <summary>Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'scrollLeft': function() { + /// <signature> + /// <summary>Set the current horizontal position of the scroll bar for each of the set of matched elements.</summary> + /// <param name="value" type="Number">An integer indicating the new position to set the scroll bar to.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'scrollTop': function() { + /// <signature> + /// <summary>Set the current vertical position of the scroll bar for each of the set of matched elements.</summary> + /// <param name="value" type="Number">An integer indicating the new position to set the scroll bar to.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'select': function() { + /// <signature> + /// <summary>Bind an event handler to the "select" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "select" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'selected': function() { + /// <summary>Selects all elements that are selected.</summary> + }, + 'serialize': function() { + /// <summary>Encode a set of form elements as a string for submission.</summary> + /// <returns type="String" /> + }, + 'serializeArray': function() { + /// <summary>Encode a set of form elements as an array of names and values.</summary> + /// <returns type="Array" /> + }, + 'show': function() { + /// <signature> + /// <summary>Display the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Display the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'siblings': function() { + /// <signature> + /// <summary>Get the siblings of each element in the set of matched elements, optionally filtered by a selector.</summary> + /// <param name="selector" type="String">A string containing a selector expression to match elements against.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'size': function() { + /// <summary>Return the number of elements in the jQuery object.</summary> + /// <returns type="Number" /> + }, + 'slice': function() { + /// <signature> + /// <summary>Reduce the set of matched elements to a subset specified by a range of indices.</summary> + /// <param name="start" type="Number">An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.</param> + /// <param name="end" type="Number">An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'slideDown': function() { + /// <signature> + /// <summary>Display the matched elements with a sliding motion.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Display the matched elements with a sliding motion.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'slideToggle': function() { + /// <signature> + /// <summary>Display or hide the matched elements with a sliding motion.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Display or hide the matched elements with a sliding motion.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'slideUp': function() { + /// <signature> + /// <summary>Hide the matched elements with a sliding motion.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Hide the matched elements with a sliding motion.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'stop': function() { + /// <signature> + /// <summary>Stop the currently-running animation on the matched elements.</summary> + /// <param name="clearQueue" type="Boolean">A Boolean indicating whether to remove queued animation as well. Defaults to false.</param> + /// <param name="jumpToEnd" type="Boolean">A Boolean indicating whether to complete the current animation immediately. Defaults to false.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Stop the currently-running animation on the matched elements.</summary> + /// <param name="queue" type="String">The name of the queue in which to stop animations.</param> + /// <param name="clearQueue" type="Boolean">A Boolean indicating whether to remove queued animation as well. Defaults to false.</param> + /// <param name="jumpToEnd" type="Boolean">A Boolean indicating whether to complete the current animation immediately. Defaults to false.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'submit': function() { + /// <signature> + /// <summary>Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "submit" JavaScript event, or trigger that event on an element.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'text': function() { + /// <signature> + /// <summary>Set the content of each element in the set of matched elements to the specified text.</summary> + /// <param name="textString" type="String">A string of text to set as the content of each matched element.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set the content of each element in the set of matched elements to the specified text.</summary> + /// <param name="function(index, text)" type="Function">A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'toArray': function() { + /// <summary>Retrieve all the DOM elements contained in the jQuery set, as an array.</summary> + /// <returns type="Array" /> + }, + 'toggle': function() { + /// <signature> + /// <summary>Display or hide the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Display or hide the matched elements.</summary> + /// <param name="duration" type="Number">A string or number determining how long the animation will run.</param> + /// <param name="easing" type="String">A string indicating which easing function to use for the transition.</param> + /// <param name="callback" type="Function">A function to call once the animation is complete.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Display or hide the matched elements.</summary> + /// <param name="showOrHide" type="Boolean">A Boolean indicating whether to show or hide the elements.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'toggleClass': function() { + /// <signature> + /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> + /// <param name="className" type="String">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> + /// <param name="className" type="String">One or more class names (separated by spaces) to be toggled for each element in the matched set.</param> + /// <param name="switch" type="Boolean">A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> + /// <param name="switch" type="Boolean">A boolean value to determine whether the class should be added or removed.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.</summary> + /// <param name="function(index, class, switch)" type="Function">A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.</param> + /// <param name="switch" type="Boolean">A boolean value to determine whether the class should be added or removed.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'trigger': function() { + /// <signature> + /// <summary>Execute all handlers and behaviors attached to the matched elements for the given event type.</summary> + /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> + /// <param name="extraParameters" type="Object">Additional parameters to pass along to the event handler.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Execute all handlers and behaviors attached to the matched elements for the given event type.</summary> + /// <param name="event" type="Event">A jQuery.Event object.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'triggerHandler': function() { + /// <signature> + /// <summary>Execute all handlers attached to an element for an event.</summary> + /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> + /// <param name="extraParameters" type="Array">An array of additional parameters to pass along to the event handler.</param> + /// <returns type="Object" /> + /// </signature> + }, + 'unbind': function() { + /// <signature> + /// <summary>Remove a previously-attached event handler from the elements.</summary> + /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> + /// <param name="handler(eventObject)" type="Function">The function that is to be no longer executed.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove a previously-attached event handler from the elements.</summary> + /// <param name="eventType" type="String">A string containing a JavaScript event type, such as click or submit.</param> + /// <param name="false" type="Boolean">Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ).</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove a previously-attached event handler from the elements.</summary> + /// <param name="event" type="Object">A JavaScript event object as passed to an event handler.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'undelegate': function() { + /// <signature> + /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> + /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> + /// <param name="eventType" type="String">A string containing a JavaScript event type, such as "click" or "keydown"</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> + /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> + /// <param name="eventType" type="String">A string containing a JavaScript event type, such as "click" or "keydown"</param> + /// <param name="handler(eventObject)" type="Function">A function to execute at the time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> + /// <param name="selector" type="String">A selector which will be used to filter the event results.</param> + /// <param name="events" type="Object">A map of one or more event types and previously bound functions to unbind from them.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.</summary> + /// <param name="namespace" type="String">A string containing a namespace to unbind all events from.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'unload': function() { + /// <signature> + /// <summary>Bind an event handler to the "unload" JavaScript event.</summary> + /// <param name="handler(eventObject)" type="Function">A function to execute when the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Bind an event handler to the "unload" JavaScript event.</summary> + /// <param name="eventData" type="Object">A map of data that will be passed to the event handler.</param> + /// <param name="handler(eventObject)" type="Function">A function to execute each time the event is triggered.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'unwrap': function() { + /// <summary>Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.</summary> + /// <returns type="jQuery" /> + }, + 'val': function() { + /// <signature> + /// <summary>Set the value of each element in the set of matched elements.</summary> + /// <param name="value" type="String">A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set the value of each element in the set of matched elements.</summary> + /// <param name="function(index, value)" type="Function">A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'visible': function() { + /// <summary>Selects all elements that are visible.</summary> + }, + 'width': function() { + /// <signature> + /// <summary>Set the CSS width of each element in the set of matched elements.</summary> + /// <param name="value" type="Number">An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Set the CSS width of each element in the set of matched elements.</summary> + /// <param name="function(index, width)" type="Function">A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'wrap': function() { + /// <signature> + /// <summary>Wrap an HTML structure around each element in the set of matched elements.</summary> + /// <param name="wrappingElement" type="jQuery">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Wrap an HTML structure around each element in the set of matched elements.</summary> + /// <param name="function(index)" type="Function">A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'wrapAll': function() { + /// <signature> + /// <summary>Wrap an HTML structure around all elements in the set of matched elements.</summary> + /// <param name="wrappingElement" type="jQuery">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + }, + 'wrapInner': function() { + /// <signature> + /// <summary>Wrap an HTML structure around the content of each element in the set of matched elements.</summary> + /// <param name="wrappingElement" type="String">An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Wrap an HTML structure around the content of each element in the set of matched elements.</summary> + /// <param name="function(index)" type="Function">A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.</param> + /// <returns type="jQuery" /> + /// </signature> + }, +}); + +intellisense.annotate(window, { + '$': function() { + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="selector" type="String">A string containing a selector expression</param> + /// <param name="context" type="jQuery">A DOM Element, Document, or jQuery to use as context</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="element" type="Element">A DOM element to wrap in a jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="object" type="Object">A plain object to wrap in a jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="elementArray" type="Array">An array containing a set of DOM elements to wrap in a jQuery object.</param> + /// <returns type="jQuery" /> + /// </signature> + /// <signature> + /// <summary>Accepts a string containing a CSS selector which is then used to match a set of elements.</summary> + /// <param name="jQuery object" type="Object">An existing jQuery object to clone.</param> + /// <returns type="jQuery" /> + /// </signature> + }, +}); + diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.js new file mode 100644 index 0000000..b4ec7f8 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.js @@ -0,0 +1,9266 @@ +/*! + * jQuery JavaScript Library v1.7.1 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Released under the the MIT License. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT and BSD Licenses. + * + * Date: Mon Nov 21 21:11:03 2011 -0500 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document, + navigator = window.navigator, + location = window.location; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // The deferred used on DOM ready + readyList, + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = quickExpr.exec( selector ); + } + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context ? context.ownerDocument || context : document ); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.7.1", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.add( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.fireWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).off( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyList ) { + return; + } + + readyList = jQuery.Callbacks( "once memory" ); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array, i ) { + var len; + + if ( array ) { + if ( indexOf ) { + return indexOf.call( array, elem, i ); + } + + len = array.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in array && array[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function() { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return ( new Date() ).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; + }, + + browser: {} +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +return jQuery; + +})(); + + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( flags ) { + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Add one or several callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // Add if not in unique mode and callback is not in + if ( !flags.unique || !self.has( elem ) ) { + list.push( elem ); + } + } + } + }, + // Fire callbacks + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + self.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + self.disable(); + } else { + list = []; + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + var length = list.length; + add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { + firingStart = length; + fire( memory[ 0 ], memory[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } + } + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique ) { + break; + } + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory || memory === true ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( stack ) { + if ( firing ) { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { + fire( context, args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return self; +}; + + + + +var // Static reference to slice + sliceDeferred = [].slice; + +jQuery.extend({ + + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + state = "pending", + lists = { + resolve: doneList, + reject: failList, + notify: progressList + }, + promise = { + done: doneList.add, + fail: failList.add, + progress: progressList.add, + + state: function() { + return state; + }, + + // Deprecated + isResolved: doneList.fired, + isRejected: failList.fired, + + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); + return this; + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "notify" ] + }, function( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ](function() { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + }); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + }); + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + obj = promise; + } else { + for ( var key in promise ) { + obj[ key ] = promise[ key ]; + } + } + return obj; + } + }, + deferred = promise.promise({}), + key; + + for ( key in lists ) { + deferred[ key ] = lists[ key ].fire; + deferred[ key + "With" ] = lists[ key ].fireWith; + } + + // Handle state + deferred.done( function() { + state = "resolved"; + }, failList.disable, progressList.lock ).fail( function() { + state = "rejected"; + }, doneList.disable, progressList.lock ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( firstParam ) { + var args = sliceDeferred.call( arguments, 0 ), + i = 0, + length = args.length, + pValues = new Array( length ), + count = length, + pCount = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(), + promise = deferred.promise(); + function resolveFunc( i ) { + return function( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + deferred.notifyWith( promise, pValues ); + }; + } + if ( length > 1 ) { + for ( ; i < length; i++ ) { + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return promise; + } +}); + + + + +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + marginDiv, + fragment, + tds, + events, + eventName, + i, + isSupported, + div = document.createElement( "div" ), + documentElement = document.documentElement; + + // Preliminary tests + div.setAttribute("className", "t"); + div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute("type", "radio"); + support.radioValue = input.value === "t"; + + input.setAttribute("checked", "checked"); + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + div.innerHTML = ""; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( window.getComputedStyle ) { + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.style.width = "2px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for( i in { + submit: 1, + change: 1, + focusin: 1 + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + fragment.removeChild( div ); + + // Null elements to avoid leaks in IE + fragment = select = opt = marginDiv = div = input = null; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, outer, inner, table, td, offsetSupport, + conMarginTop, ptlm, vb, style, html, + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + conMarginTop = 1; + ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; + vb = "visibility:hidden;border:0;"; + style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; + html = "<div " + style + "><div></div></div>" + + "<table " + style + " cellpadding='0' cellspacing='0'>" + + "<tr><td></td></tr></table>"; + + container = document.createElement("div"); + container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; + tds = div.getElementsByTagName( "td" ); + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Figure out if the W3C box model works as expected + div.innerHTML = ""; + div.style.width = div.style.paddingLeft = "1px"; + jQuery.boxModel = support.boxModel = div.offsetWidth === 2; + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "<div style='width:4px;'></div>"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); + } + + div.style.cssText = ptlm + vb; + div.innerHTML = html; + + outer = div.firstChild; + inner = outer.firstChild; + td = outer.nextSibling.firstChild.firstChild; + + offsetSupport = { + doesNotAddBorder: ( inner.offsetTop !== 5 ), + doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) + }; + + inner.style.position = "fixed"; + inner.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); + inner.style.position = inner.style.top = ""; + + outer.style.overflow = "hidden"; + outer.style.position = "relative"; + + offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); + offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + + body.removeChild( container ); + div = container = null; + + jQuery.extend( support, offsetSupport ); + }); + + return support; +})(); + + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var privateCache, thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, + isEvents = name === "events"; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = ++jQuery.uuid; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + privateCache = thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Users should not attempt to inspect the internal events object using jQuery.data, + // it is undocumented and subject to change. But does anyone listen? No. + if ( isEvents && !thisCache[ name ] ) { + return privateCache.events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ internalKey ] : internalKey; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the cache and need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ internalKey ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + } else { + elem[ internalKey ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, attr, name, + data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { + attr = this[0].attributes; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( this[0], name, data[ name ] ); + } + } + jQuery._data( this[0], "parsedAttrs", true ); + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var self = jQuery( this ), + args = [ parts[0], value ]; + + self.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + jQuery.isNumeric( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery._data( elem, deferDataKey ); + if ( defer && + ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && + ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function() { + if ( !jQuery._data( elem, queueDataKey ) && + !jQuery._data( elem, markDataKey ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.fire(); + } + }, 0 ); + } +} + +jQuery.extend({ + + _mark: function( elem, type ) { + if ( elem ) { + type = ( type || "fx" ) + "mark"; + jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); + } + }, + + _unmark: function( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); + if ( count ) { + jQuery._data( elem, key, count ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue: function( elem, type, data ) { + var q; + if ( elem ) { + type = ( type || "fx" ) + "queue"; + q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + hooks = {}; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + jQuery._data( elem, type + ".run", hooks ); + fn.call( elem, function() { + jQuery.dequeue( elem, type ); + }, hooks ); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue " + type + ".run", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function() { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + while( i-- ) { + if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { + count++; + tmp.add( resolve ); + } + } + resolve(); + return defer.promise(); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + nodeHook, boolHook, fixSpecified; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.prop ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = ( value || "" ).split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var self = jQuery(this), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, l, + i = 0; + + if ( value && elem.nodeType === 1 ) { + attrNames = value.toLowerCase().split( rspace ); + l = attrNames.length; + + for ( ; i < l; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + + // See #9699 for explanation of this approach (setting first, then removal) + jQuery.attr( elem, name, "" ); + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( rboolean.test( name ) && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) +jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? + ret.nodeValue : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.nodeValue = value + "" ); + } + }; + + // Apply the nodeHook to tabindex + jQuery.attrHooks.tabindex.set = nodeHook.set; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); + + + + +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, + rhoverHack = /\bhover(\.\S+)?\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, + quickParse = function( selector ) { + var quick = rquickIs.exec( selector ); + if ( quick ) { + // 0 1 2 3 + // [ _, tag, id, class ] + quick[1] = ( quick[1] || "" ).toLowerCase(); + quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); + } + return quick; + }, + quickIs = function( elem, m ) { + var attrs = elem.attributes || {}; + return ( + (!m[1] || elem.nodeName.toLowerCase() === m[1]) && + (!m[2] || (attrs.id || {}).value === m[2]) && + (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) + ); + }, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, quick, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + quick: quickParse( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + t, tns, type, origType, namespaces, origCount, + j, events, special, handle, eventType, handleObj; + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, [ "events", "handle" ], true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var type = event.type || event, + namespaces = [], + cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + old = null; + for ( ; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old && old === elem.ownerDocument ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments, 0 ), + run_all = !event.exclusive && !event.namespace, + handlerQueue = [], + i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Determine handlers that should run if there are delegated events + // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { + + // Pregenerate a single jQuery object for reuse with .is() + jqcur = jQuery(this); + jqcur.context = this.ownerDocument || this; + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + selMatch = {}; + matches = []; + jqcur[0] = cur; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = ( + handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) + ); + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) + if ( event.metaKey === undefined ) { + event.metaKey = event.ctrlKey; + } + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady + }, + + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector, + ret; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !form._submit_attached ) { + jQuery.event.add( form, "submit._submit", function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + }); + form._submit_attached = true; + } + }); + // return undefined since we don't need an event listener + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + jQuery.event.simulate( "change", this, event, true ); + } + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + elem._change_attached = true; + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on.call( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( var type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); + + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + expando = "sizcache" + (Math.random() + '').replace('.', ''), + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rReturn = /\r\n/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context, seed ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set, seed ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set, i, len, match, type, left; + + if ( !expr ) { + return []; + } + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + type, found, item, filter, left, + i, pass, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + filter = Expr.filter[ type ]; + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + pass = not ^ found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Utility function for retreiving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +var getText = Sizzle.getText = function( elem ) { + var i, node, + nodeType = elem.nodeType, + ret = ""; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 ) { + // Use textContent || innerText for elements + if ( typeof elem.textContent === 'string' ) { + return elem.textContent; + } else if ( typeof elem.innerText === 'string' ) { + // Replace IE's carriage returns + return elem.innerText.replace( rReturn, '' ); + } else { + // Traverse it's children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + } else { + + // If no nodeType, this is expected to be an array + for ( i = 0; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + if ( node.nodeType !== 8 ) { + ret += getText( node ); + } + } + } + return ret; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus: function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var first, last, + doneName, parent, cache, + count, diff, + type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + first = match[2]; + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + doneName = match[0]; + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { + count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent[ expando ] = doneName; + } + + diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Sizzle.attr ? + Sizzle.attr( elem, name ) : + Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + !type && Sizzle.attr ? + result != null : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = "<a name='" + id + "'/>"; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = "<a href='#'></a>"; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "<p class='TEST'></p>"; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "<div class='test e'></div><div class='test'></div>"; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context, seed ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet, seed ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +Sizzle.selectors.attrMap = {}; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var self = this, + i, l; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + POS.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array (deprecated as of jQuery 1.7) + if ( jQuery.isArray( selectors ) ) { + var level = 1; + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( i = 0; i < selectors.length; i++ ) { + + if ( jQuery( cur ).is( selectors[ i ] ) ) { + ret.push({ selector: selectors[ i ], elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} + + + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /<tbody/i, + rhtml = /<|&#?\w+;/, + rnoInnerhtml = /<(?:script|style)/i, + rnocache = /<(?:script|object|embed|option|style)/i, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"), + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /\/(java|ecma)script/i, + rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, + wrapMap = { + option: [ 1, "<select multiple='multiple'>", "</select>" ], + legend: [ 1, "<fieldset>", "</fieldset>" ], + thead: [ 1, "<table>", "</table>" ], + tr: [ 2, "<table><tbody>", "</tbody></table>" ], + td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], + col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], + area: [ 1, "<map>", "</map>" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize <link> and <script> tags normally +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "div<div>", "</div>" ]; +} + +jQuery.fn.extend({ + text: function( text ) { + if ( jQuery.isFunction(text) ) { + return this.each(function(i) { + var self = jQuery( this ); + + self.text( text.call(this, i, self.text()) ); + }); + } + + if ( typeof text !== "object" && text !== undefined ) { + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + } + + return jQuery.text( this ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function(i) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } else if ( arguments.length ) { + var set = jQuery.clean( arguments ); + set.push.apply( set, this.toArray() ); + return this.pushStack( set, "before", arguments ); + } + }, + + after: function() { + if ( this[0] && this[0].parentNode ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } else if ( arguments.length ) { + var set = this.pushStack( this, "after", arguments ); + set.push.apply( set, jQuery.clean(arguments) ); + return set; + } + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + jQuery.cleanData( [ elem ] ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + for ( var i = 0, elem; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + if ( value === undefined ) { + return this[0] && this[0].nodeType === 1 ? + this[0].innerHTML.replace(rinlinejQuery, "") : + null; + + // See if we can take a shortcut and just use innerHTML + } else if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && + !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { + + value = value.replace(rxhtmlTag, "<$1></$2>"); + + try { + for ( var i = 0, l = this.length; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + if ( this[i].nodeType === 1 ) { + jQuery.cleanData( this[i].getElementsByTagName("*") ); + this[i].innerHTML = value; + } + } + + // If using innerHTML throws an exception, use the fallback method + } catch(e) { + this.empty().append( value ); + } + + } else if ( jQuery.isFunction( value ) ) { + this.each(function(i){ + var self = jQuery( this ); + + self.html( value.call(this, i, self.html()) ); + }); + + } else { + this.empty().append( value ); + } + + return this; + }, + + replaceWith: function( value ) { + if ( this[0] && this[0].parentNode ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + if ( typeof value !== "string" ) { + value = jQuery( value ).detach(); + } + + return this.each(function() { + var next = this.nextSibling, + parent = this.parentNode; + + jQuery( this ).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } else { + return this.length ? + this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : + this; + } + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + var results, first, fragment, parent, + value = args[0], + scripts = []; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback, true ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call(this, i, table ? self.html() : undefined); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + parent = value && value.parentNode; + + // If we're in a fragment, just use that instead of building a new one + if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { + results = { fragment: parent }; + + } else { + results = jQuery.buildFragment( args, this, scripts ); + } + + fragment = results.fragment; + + if ( fragment.childNodes.length === 1 ) { + first = fragment = fragment.firstChild; + } else { + first = fragment.firstChild; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { + callback.call( + table ? + root(this[i], first) : + this[i], + // Make sure that we do not leak memory by inadvertently discarding + // the original fragment (which might have attached data) instead of + // using it; in addition, use the original fragment object for the last + // item instead of first because it can end up being emptied incorrectly + // in certain situations (Bug #8070). + // Fragments from the fragment cache must always be cloned and never used + // in place. + results.cacheable || ( l > 1 && i < lastIndex ) ? + jQuery.clone( fragment, true, true ) : + fragment + ); + } + } + + if ( scripts.length ) { + jQuery.each( scripts, evalScript ); + } + } + + return this; + } +}); + +function root( elem, cur ) { + return jQuery.nodeName(elem, "table") ? + (elem.getElementsByTagName("tbody")[0] || + elem.appendChild(elem.ownerDocument.createElement("tbody"))) : + elem; +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function cloneFixAttributes( src, dest ) { + var nodeName; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + // clearAttributes removes the attributes, which we don't want, + // but also removes the attachEvent events, which we *do* want + if ( dest.clearAttributes ) { + dest.clearAttributes(); + } + + // mergeAttributes, in contrast, only merges back on the + // original attributes, not the events + if ( dest.mergeAttributes ) { + dest.mergeAttributes( src ); + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 fail to clone children inside object elements that use + // the proprietary classid attribute value (rather than the type + // attribute) to identify the type of content to display + if ( nodeName === "object" ) { + dest.outerHTML = src.outerHTML; + + } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + if ( src.checked ) { + dest.defaultChecked = dest.checked = src.checked; + } + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } + + // Event data gets referenced instead of copied if the expando + // gets copied too + dest.removeAttribute( jQuery.expando ); +} + +jQuery.buildFragment = function( args, nodes, scripts ) { + var fragment, cacheable, cacheresults, doc, + first = args[ 0 ]; + + // nodes may contain either an explicit document object, + // a jQuery collection or context object. + // If nodes[0] contains a valid object to assign to doc + if ( nodes && nodes[0] ) { + doc = nodes[0].ownerDocument || nodes[0]; + } + + // Ensure that an attr object doesn't incorrectly stand in as a document object + // Chrome and Firefox seem to allow this to occur and will throw exception + // Fixes #8950 + if ( !doc.createDocumentFragment ) { + doc = document; + } + + // Only cache "small" (1/2 KB) HTML strings that are associated with the main document + // Cloning options loses the selected state, so don't cache them + // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment + // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache + // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 + if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document && + first.charAt(0) === "<" && !rnocache.test( first ) && + (jQuery.support.checkClone || !rchecked.test( first )) && + (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { + + cacheable = true; + + cacheresults = jQuery.fragments[ first ]; + if ( cacheresults && cacheresults !== 1 ) { + fragment = cacheresults; + } + } + + if ( !fragment ) { + fragment = doc.createDocumentFragment(); + jQuery.clean( args, doc, fragment, scripts ); + } + + if ( cacheable ) { + jQuery.fragments[ first ] = cacheresults ? fragment : 1; + } + + return { fragment: fragment, cacheable: cacheable }; +}; + +jQuery.fragments = {}; + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var ret = [], + insert = jQuery( selector ), + parent = this.length === 1 && this[0].parentNode; + + if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { + insert[ original ]( this[0] ); + return this; + + } else { + for ( var i = 0, l = insert.length; i < l; i++ ) { + var elems = ( i > 0 ? this.clone(true) : this ).get(); + jQuery( insert[i] )[ original ]( elems ); + ret = ret.concat( elems ); + } + + return this.pushStack( ret, name, insert.selector ); + } + }; +}); + +function getAll( elem ) { + if ( typeof elem.getElementsByTagName !== "undefined" ) { + return elem.getElementsByTagName( "*" ); + + } else if ( typeof elem.querySelectorAll !== "undefined" ) { + return elem.querySelectorAll( "*" ); + + } else { + return []; + } +} + +// Used in clean, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( elem.type === "checkbox" || elem.type === "radio" ) { + elem.defaultChecked = elem.checked; + } +} +// Finds all inputs and passes them to fixDefaultChecked +function findInputs( elem ) { + var nodeName = ( elem.nodeName || "" ).toLowerCase(); + if ( nodeName === "input" ) { + fixDefaultChecked( elem ); + // Skip scripts, get other children + } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { + jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); + } +} + +// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js +function shimCloneNode( elem ) { + var div = document.createElement( "div" ); + safeFragment.appendChild( div ); + + div.innerHTML = elem.outerHTML; + return div.firstChild; +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var srcElements, + destElements, + i, + // IE<=8 does not properly clone detached, unknown element nodes + clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ? + elem.cloneNode( true ) : + shimCloneNode( elem ); + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + // IE copies events bound via attachEvent when using cloneNode. + // Calling detachEvent on the clone will also remove the events + // from the original. In order to get around this, we use some + // proprietary methods to clear the events. Thanks to MooTools + // guys for this hotness. + + cloneFixAttributes( elem, clone ); + + // Using Sizzle here is crazy slow, so we use getElementsByTagName instead + srcElements = getAll( elem ); + destElements = getAll( clone ); + + // Weird iteration because IE will replace the length property + // with an element if you are cloning the body and one of the + // elements on the page has a name or id of "length" + for ( i = 0; srcElements[i]; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + cloneFixAttributes( srcElements[i], destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + cloneCopyEvent( elem, clone ); + + if ( deepDataAndEvents ) { + srcElements = getAll( elem ); + destElements = getAll( clone ); + + for ( i = 0; srcElements[i]; ++i ) { + cloneCopyEvent( srcElements[i], destElements[i] ); + } + } + } + + srcElements = destElements = null; + + // Return the cloned set + return clone; + }, + + clean: function( elems, context, fragment, scripts ) { + var checkScriptType; + + context = context || document; + + // !context.createElement fails in IE with an error but returns typeof 'object' + if ( typeof context.createElement === "undefined" ) { + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + } + + var ret = [], j; + + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + continue; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" ) { + if ( !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + } else { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, "<$1></$2>"); + + // Trim whitespace, otherwise indexOf won't work as expected + var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(), + wrap = wrapMap[ tag ] || wrapMap._default, + depth = wrap[0], + div = context.createElement("div"); + + // Append wrapper element to unknown element safe doc fragment + if ( context === document ) { + // Use the fragment we've already created for this document + safeFragment.appendChild( div ); + } else { + // Use a fragment created with the owner document + createSafeFragment( context ).appendChild( div ); + } + + // Go to html and back, then peel off extra wrappers + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted <tbody> from table fragments + if ( !jQuery.support.tbody ) { + + // String was a <table>, *may* have spurious <tbody> + var hasBody = rtbody.test(elem), + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare <thead> or <tfoot> + wrap[1] === "<table>" && !hasBody ? + div.childNodes : + []; + + for ( j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = div.childNodes; + } + } + + // Resets defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + var len; + if ( !jQuery.support.appendChecked ) { + if ( elem[0] && typeof (len = elem.length) === "number" ) { + for ( j = 0; j < len; j++ ) { + findInputs( elem[j] ); + } + } else { + findInputs( elem ); + } + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + ret = jQuery.merge( ret, elem ); + } + } + + if ( fragment ) { + checkScriptType = function( elem ) { + return !elem.type || rscriptType.test( elem.type ); + }; + for ( i = 0; ret[i]; i++ ) { + if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { + scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); + + } else { + if ( ret[i].nodeType === 1 ) { + var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); + + ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); + } + fragment.appendChild( ret[i] ); + } + } + } + + return ret; + }, + + cleanData: function( elems ) { + var data, id, + cache = jQuery.cache, + special = jQuery.event.special, + deleteExpando = jQuery.support.deleteExpando; + + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { + continue; + } + + id = elem[ jQuery.expando ]; + + if ( id ) { + data = cache[ id ]; + + if ( data && data.events ) { + for ( var type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + + // Null the DOM reference to avoid IE6/7/8 leak (#7054) + if ( data.handle ) { + data.handle.elem = null; + } + } + + if ( deleteExpando ) { + delete elem[ jQuery.expando ]; + + } else if ( elem.removeAttribute ) { + elem.removeAttribute( jQuery.expando ); + } + + delete cache[ id ]; + } + } + } +}); + +function evalScript( i, elem ) { + if ( elem.src ) { + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + } else { + jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } +} + + + + +var ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity=([^)]*)/, + // fixed for IE9, see #8346 + rupper = /([A-Z]|^ms)/g, + rnumpx = /^-?\d+(?:px)?$/i, + rnum = /^-?\d/, + rrelNum = /^([\-+])=([\-+.\de]+)/, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssWidth = [ "Left", "Right" ], + cssHeight = [ "Top", "Bottom" ], + curCSS, + + getComputedStyle, + currentStyle; + +jQuery.fn.css = function( name, value ) { + // Setting 'undefined' is a no-op + if ( arguments.length === 2 && value === undefined ) { + return this; + } + + return jQuery.access( this, name, value, true, function( elem, name, value ) { + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }); +}; + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity", "opacity" ); + return ret === "" ? "1" : ret; + + } else { + return elem.style.opacity; + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, origName = jQuery.camelCase( name ), + style = elem.style, hooks = jQuery.cssHooks[ origName ]; + + name = jQuery.cssProps[ origName ] || origName; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) { + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra ) { + var ret, hooks; + + // Make sure that we're working with the right name + name = jQuery.camelCase( name ); + hooks = jQuery.cssHooks[ name ]; + name = jQuery.cssProps[ name ] || name; + + // cssFloat needs a special treatment + if ( name === "cssFloat" ) { + name = "float"; + } + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { + return ret; + + // Otherwise, if a way to get the computed value exists, use that + } else if ( curCSS ) { + return curCSS( elem, name ); + } + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var old = {}; + + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + } +}); + +// DEPRECATED, Use jQuery.css() instead +jQuery.curCSS = jQuery.css; + +jQuery.each(["height", "width"], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + var val; + + if ( computed ) { + if ( elem.offsetWidth !== 0 ) { + return getWH( elem, name, extra ); + } else { + jQuery.swap( elem, cssShow, function() { + val = getWH( elem, name, extra ); + }); + } + + return val; + } + }, + + set: function( elem, value ) { + if ( rnumpx.test( value ) ) { + // ignore negative width and height values #1599 + value = parseFloat( value ); + + if ( value >= 0 ) { + return value + "px"; + } + + } else { + return value; + } + } + }; +}); + +if ( !jQuery.support.opacity ) { + jQuery.cssHooks.opacity = { + get: function( elem, computed ) { + // IE uses filters for opacity + return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? + ( parseFloat( RegExp.$1 ) / 100 ) + "" : + computed ? "1" : ""; + }, + + set: function( elem, value ) { + var style = elem.style, + currentStyle = elem.currentStyle, + opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", + filter = currentStyle && currentStyle.filter || style.filter || ""; + + // IE has trouble with opacity if it does not have layout + // Force it by setting the zoom level + style.zoom = 1; + + // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 + if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) { + + // Setting style.filter to null, "" & " " still leave "filter:" in the cssText + // if "filter:" is present at all, clearType is disabled, we want to avoid this + // style.removeAttribute is IE Only, but so apparently is this code path... + style.removeAttribute( "filter" ); + + // if there there is no filter style applied in a css rule, we are done + if ( currentStyle && !currentStyle.filter ) { + return; + } + } + + // otherwise, set new filter values + style.filter = ralpha.test( filter ) ? + filter.replace( ralpha, opacity ) : + filter + " " + opacity; + } + }; +} + +jQuery(function() { + // This hook cannot be added until DOM ready because the support test + // for it is not run until after DOM ready + if ( !jQuery.support.reliableMarginRight ) { + jQuery.cssHooks.marginRight = { + get: function( elem, computed ) { + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + // Work around by temporarily setting element display to inline-block + var ret; + jQuery.swap( elem, { "display": "inline-block" }, function() { + if ( computed ) { + ret = curCSS( elem, "margin-right", "marginRight" ); + } else { + ret = elem.style.marginRight; + } + }); + return ret; + } + }; + } +}); + +if ( document.defaultView && document.defaultView.getComputedStyle ) { + getComputedStyle = function( elem, name ) { + var ret, defaultView, computedStyle; + + name = name.replace( rupper, "-$1" ).toLowerCase(); + + if ( (defaultView = elem.ownerDocument.defaultView) && + (computedStyle = defaultView.getComputedStyle( elem, null )) ) { + ret = computedStyle.getPropertyValue( name ); + if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { + ret = jQuery.style( elem, name ); + } + } + + return ret; + }; +} + +if ( document.documentElement.currentStyle ) { + currentStyle = function( elem, name ) { + var left, rsLeft, uncomputed, + ret = elem.currentStyle && elem.currentStyle[ name ], + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret === null && style && (uncomputed = style[ name ]) ) { + ret = uncomputed; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { + + // Remember the original values + left = style.left; + rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + elem.runtimeStyle.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ( ret || 0 ); + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + elem.runtimeStyle.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +curCSS = getComputedStyle || currentStyle; + +function getWH( elem, name, extra ) { + + // Start with offset property + var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + which = name === "width" ? cssWidth : cssHeight, + i = 0, + len = which.length; + + if ( val > 0 ) { + if ( extra !== "border" ) { + for ( ; i < len; i++ ) { + if ( !extra ) { + val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; + } + if ( extra === "margin" ) { + val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; + } else { + val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; + } + } + } + + return val + "px"; + } + + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, name ); + if ( val < 0 || val == null ) { + val = elem.style[ name ] || 0; + } + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + + // Add padding, border, margin + if ( extra ) { + for ( ; i < len; i++ ) { + val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0; + if ( extra !== "padding" ) { + val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0; + } + if ( extra === "margin" ) { + val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0; + } + } + } + + return val + "px"; +} + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + var width = elem.offsetWidth, + height = elem.offsetHeight; + + return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} + + + + +var r20 = /%20/g, + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rhash = /#.*$/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL + rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + rquery = /\?/, + rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, + rselectTextarea = /^(?:select|textarea)/i, + rspacesAjax = /\s+/, + rts = /([?&])_=[^&]*/, + rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, + + // Keep a copy of the old load method + _load = jQuery.fn.load, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Document location + ajaxLocation, + + // Document location segments + ajaxLocParts, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = ["*/"] + ["*"]; + +// #8138, IE may throw an exception when accessing +// a field from window.location if document.domain has been set +try { + ajaxLocation = location.href; +} catch( e ) { + // Use the href attribute of an A element + // since IE will modify it given document.location + ajaxLocation = document.createElement( "a" ); + ajaxLocation.href = ""; + ajaxLocation = ajaxLocation.href; +} + +// Segment location into parts +ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + if ( jQuery.isFunction( func ) ) { + var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), + i = 0, + length = dataTypes.length, + dataType, + list, + placeBefore; + + // For each dataType in the dataTypeExpression + for ( ; i < length; i++ ) { + dataType = dataTypes[ i ]; + // We control if we're asked to add before + // any existing element + placeBefore = /^\+/.test( dataType ); + if ( placeBefore ) { + dataType = dataType.substr( 1 ) || "*"; + } + list = structure[ dataType ] = structure[ dataType ] || []; + // then we add to the structure accordingly + list[ placeBefore ? "unshift" : "push" ]( func ); + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, + dataType /* internal */, inspected /* internal */ ) { + + dataType = dataType || options.dataTypes[ 0 ]; + inspected = inspected || {}; + + inspected[ dataType ] = true; + + var list = structure[ dataType ], + i = 0, + length = list ? list.length : 0, + executeOnly = ( structure === prefilters ), + selection; + + for ( ; i < length && ( executeOnly || !selection ); i++ ) { + selection = list[ i ]( options, originalOptions, jqXHR ); + // If we got redirected to another dataType + // we try there if executing only and not done already + if ( typeof selection === "string" ) { + if ( !executeOnly || inspected[ selection ] ) { + selection = undefined; + } else { + options.dataTypes.unshift( selection ); + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, selection, inspected ); + } + } + } + // If we're only executing or nothing was selected + // we try the catchall dataType if not done already + if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, "*", inspected ); + } + // unnecessary when only executing (prefilters) + // but it'll be ignored by the caller in that case + return selection; +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } +} + +jQuery.fn.extend({ + load: function( url, params, callback ) { + if ( typeof url !== "string" && _load ) { + return _load.apply( this, arguments ); + + // Don't do a request if no elements are being requested + } else if ( !this.length ) { + return this; + } + + var off = url.indexOf( " " ); + if ( off >= 0 ) { + var selector = url.slice( off, url.length ); + url = url.slice( 0, off ); + } + + // Default to a GET request + var type = "GET"; + + // If the second parameter was provided + if ( params ) { + // If it's a function + if ( jQuery.isFunction( params ) ) { + // We assume that it's the callback + callback = params; + params = undefined; + + // Otherwise, build a param string + } else if ( typeof params === "object" ) { + params = jQuery.param( params, jQuery.ajaxSettings.traditional ); + type = "POST"; + } + } + + var self = this; + + // Request the remote document + jQuery.ajax({ + url: url, + type: type, + dataType: "html", + data: params, + // Complete callback (responseText is used internally) + complete: function( jqXHR, status, responseText ) { + // Store the response as specified by the jqXHR object + responseText = jqXHR.responseText; + // If successful, inject the HTML into all the matched elements + if ( jqXHR.isResolved() ) { + // #4825: Get the actual response in case + // a dataFilter is present in ajaxSettings + jqXHR.done(function( r ) { + responseText = r; + }); + // See if a selector was specified + self.html( selector ? + // Create a dummy div to hold the results + jQuery("<div>") + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append(responseText.replace(rscript, "")) + + // Locate the specified elements + .find(selector) : + + // If not, just inject the full result + responseText ); + } + + if ( callback ) { + self.each( callback, [ responseText, status, jqXHR ] ); + } + } + }); + + return this; + }, + + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + + serializeArray: function() { + return this.map(function(){ + return this.elements ? jQuery.makeArray( this.elements ) : this; + }) + .filter(function(){ + return this.name && !this.disabled && + ( this.checked || rselectTextarea.test( this.nodeName ) || + rinput.test( this.type ) ); + }) + .map(function( i, elem ){ + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val, i ){ + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }).get(); + } +}); + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ + jQuery.fn[ o ] = function( f ){ + return this.on( o, f ); + }; +}); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + // shift arguments if data argument was omitted + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + return jQuery.ajax({ + type: method, + url: url, + data: data, + success: callback, + dataType: type + }); + }; +}); + +jQuery.extend({ + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + if ( settings ) { + // Building a settings object + ajaxExtend( target, jQuery.ajaxSettings ); + } else { + // Extending ajaxSettings + settings = target; + target = jQuery.ajaxSettings; + } + ajaxExtend( target, settings ); + return target; + }, + + ajaxSettings: { + url: ajaxLocation, + isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded", + processData: true, + async: true, + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + traditional: false, + headers: {}, + */ + + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + text: "text/plain", + json: "application/json, text/javascript", + "*": allTypes + }, + + contents: { + xml: /xml/, + html: /html/, + json: /json/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText" + }, + + // List of data converters + // 1) key format is "source_type destination_type" (a single space in-between) + // 2) the catchall symbol "*" can be used for source_type + converters: { + + // Convert anything to text + "* text": window.String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": jQuery.parseJSON, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + context: true, + url: true + } + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + // Callbacks context + callbackContext = s.context || s, + // Context for global events + // It's the callbackContext if one was provided in the options + // and if it's a DOM node or a jQuery collection + globalEventContext = callbackContext !== s && + ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? + jQuery( callbackContext ) : jQuery.event, + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + // Status-dependent callbacks + statusCode = s.statusCode || {}, + // ifModified key + ifModifiedKey, + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + // Response headers + responseHeadersString, + responseHeaders, + // transport + transport, + // timeout handle + timeoutTimer, + // Cross-domain detection vars + parts, + // The jqXHR state + state = 0, + // To know if global events are to be dispatched + fireGlobals, + // Loop variable + i, + // Fake xhr + jqXHR = { + + readyState: 0, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( !state ) { + var lname = name.toLowerCase(); + name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Raw string + getAllResponseHeaders: function() { + return state === 2 ? responseHeadersString : null; + }, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( state === 2 ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match === undefined ? null : match; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( !state ) { + s.mimeType = type; + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + statusText = statusText || "abort"; + if ( transport ) { + transport.abort( statusText ); + } + done( 0, statusText ); + return this; + } + }; + + // Callback for when everything is done + // It is defined here because jslint complains if it is declared + // at the end of the function (which would be more logical and readable) + function done( status, nativeStatusText, responses, headers ) { + + // Called once + if ( state === 2 ) { + return; + } + + // State is "done" now + state = 2; + + // Clear timeout if it exists + if ( timeoutTimer ) { + clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + var isSuccess, + success, + error, + statusText = nativeStatusText, + response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, + lastModified, + etag; + + // If successful, handle type chaining + if ( status >= 200 && status < 300 || status === 304 ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + + if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { + jQuery.lastModified[ ifModifiedKey ] = lastModified; + } + if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { + jQuery.etag[ ifModifiedKey ] = etag; + } + } + + // If not modified + if ( status === 304 ) { + + statusText = "notmodified"; + isSuccess = true; + + // If we have data + } else { + + try { + success = ajaxConvert( s, response ); + statusText = "success"; + isSuccess = true; + } catch(e) { + // We have a parsererror + statusText = "parsererror"; + error = e; + } + } + } else { + // We extract error from statusText + // then normalize statusText and status for non-aborts + error = statusText; + if ( !statusText || status ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = "" + ( nativeStatusText || statusText ); + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + // Attach deferreds + deferred.promise( jqXHR ); + jqXHR.success = jqXHR.done; + jqXHR.error = jqXHR.fail; + jqXHR.complete = completeDeferred.add; + + // Status-dependent callbacks + jqXHR.statusCode = function( map ) { + if ( map ) { + var tmp; + if ( state < 2 ) { + for ( tmp in map ) { + statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; + } + } else { + tmp = map[ jqXHR.status ]; + jqXHR.then( tmp, tmp ); + } + } + return this; + }; + + // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) + // We also use the url parameter if available + s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); + + // Extract dataTypes list + s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax ); + + // Determine if a cross-domain request is in order + if ( s.crossDomain == null ) { + parts = rurl.exec( s.url.toLowerCase() ); + s.crossDomain = !!( parts && + ( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] || + ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != + ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) + ); + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefiler, stop there + if ( state === 2 ) { + return false; + } + + // We can fire global events as of now if asked to + fireGlobals = s.global; + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // If data is available, append data to url + if ( s.data ) { + s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Get ifModifiedKey before adding the anti-cache parameter + ifModifiedKey = s.url; + + // Add anti-cache in url if needed + if ( s.cache === false ) { + + var ts = jQuery.now(), + // try replacing _= if it is there + ret = s.url.replace( rts, "$1_=" + ts ); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + ifModifiedKey = ifModifiedKey || s.url; + if ( jQuery.lastModified[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); + } + if ( jQuery.etag[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); + } + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? + s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { + // Abort if not done already + jqXHR.abort(); + return false; + + } + + // Install callbacks on deferreds + for ( i in { success: 1, error: 1, complete: 1 } ) { + jqXHR[ i ]( s[ i ] ); + } + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = setTimeout( function(){ + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + state = 1; + transport.send( requestHeaders, done ); + } catch (e) { + // Propagate exception as error if not done + if ( state < 2 ) { + done( -1, e ); + // Simply rethrow otherwise + } else { + throw e; + } + } + } + + return jqXHR; + }, + + // Serialize an array of form elements or a set of + // key/values into a query string + param: function( a, traditional ) { + var s = [], + add = function( key, value ) { + // If value is a function, invoke it and return its value + value = jQuery.isFunction( value ) ? value() : value; + s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); + }; + + // Set traditional to true for jQuery <= 1.3.2 behavior. + if ( traditional === undefined ) { + traditional = jQuery.ajaxSettings.traditional; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + }); + + } else { + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( var prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ).replace( r20, "+" ); + } +}); + +function buildParams( prefix, obj, traditional, add ) { + if ( jQuery.isArray( obj ) ) { + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); + } + }); + + } else if ( !traditional && obj != null && typeof obj === "object" ) { + // Serialize object item. + for ( var name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + // Serialize scalar item. + add( prefix, obj ); + } +} + +// This is still on the jQuery object... for now +// Want to move this to jQuery.ajax some day +jQuery.extend({ + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {} + +}); + +/* Handles responses to an ajax request: + * - sets all responseXXX fields accordingly + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var contents = s.contents, + dataTypes = s.dataTypes, + responseFields = s.responseFields, + ct, + type, + finalDataType, + firstDataType; + + // Fill responseXXX fields + for ( type in responseFields ) { + if ( type in responses ) { + jqXHR[ responseFields[type] ] = responses[ type ]; + } + } + + // Remove auto dataType and get content-type in the process + while( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +// Chain conversions given the request and the original response +function ajaxConvert( s, response ) { + + // Apply the dataFilter if provided + if ( s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + var dataTypes = s.dataTypes, + converters = {}, + i, + key, + length = dataTypes.length, + tmp, + // Current and previous dataTypes + current = dataTypes[ 0 ], + prev, + // Conversion expression + conversion, + // Conversion function + conv, + // Conversion functions (transitive conversion) + conv1, + conv2; + + // For each dataType in the chain + for ( i = 1; i < length; i++ ) { + + // Create converters map + // with lowercased keys + if ( i === 1 ) { + for ( key in s.converters ) { + if ( typeof key === "string" ) { + converters[ key.toLowerCase() ] = s.converters[ key ]; + } + } + } + + // Get the dataTypes + prev = current; + current = dataTypes[ i ]; + + // If current is auto dataType, update it to prev + if ( current === "*" ) { + current = prev; + // If no auto and dataTypes are actually different + } else if ( prev !== "*" && prev !== current ) { + + // Get the converter + conversion = prev + " " + current; + conv = converters[ conversion ] || converters[ "* " + current ]; + + // If there is no direct converter, search transitively + if ( !conv ) { + conv2 = undefined; + for ( conv1 in converters ) { + tmp = conv1.split( " " ); + if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { + conv2 = converters[ tmp[1] + " " + current ]; + if ( conv2 ) { + conv1 = converters[ conv1 ]; + if ( conv1 === true ) { + conv = conv2; + } else if ( conv2 === true ) { + conv = conv1; + } + break; + } + } + } + } + // If we found no converter, dispatch an error + if ( !( conv || conv2 ) ) { + jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); + } + // If found converter is not an equivalence + if ( conv !== true ) { + // Convert with 1 or 2 converters accordingly + response = conv ? conv( response ) : conv2( conv1(response) ); + } + } + } + return response; +} + + + + +var jsc = jQuery.now(), + jsre = /(\=)\?(&|$)|\?\?/i; + +// Default jsonp settings +jQuery.ajaxSetup({ + jsonp: "callback", + jsonpCallback: function() { + return jQuery.expando + "_" + ( jsc++ ); + } +}); + +// Detect, normalize options and install callbacks for jsonp requests +jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { + + var inspectData = s.contentType === "application/x-www-form-urlencoded" && + ( typeof s.data === "string" ); + + if ( s.dataTypes[ 0 ] === "jsonp" || + s.jsonp !== false && ( jsre.test( s.url ) || + inspectData && jsre.test( s.data ) ) ) { + + var responseContainer, + jsonpCallback = s.jsonpCallback = + jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, + previous = window[ jsonpCallback ], + url = s.url, + data = s.data, + replace = "$1" + jsonpCallback + "$2"; + + if ( s.jsonp !== false ) { + url = url.replace( jsre, replace ); + if ( s.url === url ) { + if ( inspectData ) { + data = data.replace( jsre, replace ); + } + if ( s.data === data ) { + // Add callback manually + url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; + } + } + } + + s.url = url; + s.data = data; + + // Install callback + window[ jsonpCallback ] = function( response ) { + responseContainer = [ response ]; + }; + + // Clean-up function + jqXHR.always(function() { + // Set callback back to previous value + window[ jsonpCallback ] = previous; + // Call if it was a function and we have a response + if ( responseContainer && jQuery.isFunction( previous ) ) { + window[ jsonpCallback ]( responseContainer[ 0 ] ); + } + }); + + // Use data converter to retrieve json after script execution + s.converters["script json"] = function() { + if ( !responseContainer ) { + jQuery.error( jsonpCallback + " was not called" ); + } + return responseContainer[ 0 ]; + }; + + // force json dataType + s.dataTypes[ 0 ] = "json"; + + // Delegate to script + return "script"; + } +}); + + + + +// Install script dataType +jQuery.ajaxSetup({ + accepts: { + script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /javascript|ecmascript/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +}); + +// Handle cache's special case and global +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + s.global = false; + } +}); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function(s) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + + var script, + head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; + + return { + + send: function( _, callback ) { + + script = document.createElement( "script" ); + + script.async = "async"; + + if ( s.scriptCharset ) { + script.charset = s.scriptCharset; + } + + script.src = s.url; + + // Attach handlers for all browsers + script.onload = script.onreadystatechange = function( _, isAbort ) { + + if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { + + // Handle memory leak in IE + script.onload = script.onreadystatechange = null; + + // Remove the script + if ( head && script.parentNode ) { + head.removeChild( script ); + } + + // Dereference the script + script = undefined; + + // Callback if not abort + if ( !isAbort ) { + callback( 200, "success" ); + } + } + }; + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + }, + + abort: function() { + if ( script ) { + script.onload( 0, 1 ); + } + } + }; + } +}); + + + + +var // #5280: Internet Explorer will keep connections alive if we don't abort on unload + xhrOnUnloadAbort = window.ActiveXObject ? function() { + // Abort all pending requests + for ( var key in xhrCallbacks ) { + xhrCallbacks[ key ]( 0, 1 ); + } + } : false, + xhrId = 0, + xhrCallbacks; + +// Functions to create xhrs +function createStandardXHR() { + try { + return new window.XMLHttpRequest(); + } catch( e ) {} +} + +function createActiveXHR() { + try { + return new window.ActiveXObject( "Microsoft.XMLHTTP" ); + } catch( e ) {} +} + +// Create the request object +// (This is still attached to ajaxSettings for backward compatibility) +jQuery.ajaxSettings.xhr = window.ActiveXObject ? + /* Microsoft failed to properly + * implement the XMLHttpRequest in IE7 (can't request local files), + * so we use the ActiveXObject when it is available + * Additionally XMLHttpRequest can be disabled in IE7/IE8 so + * we need a fallback. + */ + function() { + return !this.isLocal && createStandardXHR() || createActiveXHR(); + } : + // For all other browsers, use the standard XMLHttpRequest object + createStandardXHR; + +// Determine support properties +(function( xhr ) { + jQuery.extend( jQuery.support, { + ajax: !!xhr, + cors: !!xhr && ( "withCredentials" in xhr ) + }); +})( jQuery.ajaxSettings.xhr() ); + +// Create transport if the browser can provide an xhr +if ( jQuery.support.ajax ) { + + jQuery.ajaxTransport(function( s ) { + // Cross domain only allowed if supported through XMLHttpRequest + if ( !s.crossDomain || jQuery.support.cors ) { + + var callback; + + return { + send: function( headers, complete ) { + + // Get a new xhr + var xhr = s.xhr(), + handle, + i; + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open( s.type, s.url, s.async, s.username, s.password ); + } else { + xhr.open( s.type, s.url, s.async ); + } + + // Apply custom fields if provided + if ( s.xhrFields ) { + for ( i in s.xhrFields ) { + xhr[ i ] = s.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( s.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( s.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !s.crossDomain && !headers["X-Requested-With"] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + } catch( _ ) {} + + // Do send the request + // This may raise an exception which is actually + // handled in jQuery.ajax (so no try/catch here) + xhr.send( ( s.hasContent && s.data ) || null ); + + // Listener + callback = function( _, isAbort ) { + + var status, + statusText, + responseHeaders, + responses, + xml; + + // Firefox throws exceptions when accessing properties + // of an xhr when a network error occured + // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) + try { + + // Was never called and is aborted or complete + if ( callback && ( isAbort || xhr.readyState === 4 ) ) { + + // Only called once + callback = undefined; + + // Do not keep as active anymore + if ( handle ) { + xhr.onreadystatechange = jQuery.noop; + if ( xhrOnUnloadAbort ) { + delete xhrCallbacks[ handle ]; + } + } + + // If it's an abort + if ( isAbort ) { + // Abort it manually if needed + if ( xhr.readyState !== 4 ) { + xhr.abort(); + } + } else { + status = xhr.status; + responseHeaders = xhr.getAllResponseHeaders(); + responses = {}; + xml = xhr.responseXML; + + // Construct response list + if ( xml && xml.documentElement /* #4958 */ ) { + responses.xml = xml; + } + responses.text = xhr.responseText; + + // Firefox throws an exception when accessing + // statusText for faulty cross-domain requests + try { + statusText = xhr.statusText; + } catch( e ) { + // We normalize with Webkit giving an empty statusText + statusText = ""; + } + + // Filter status for non standard behaviors + + // If the request is local and we have data: assume a success + // (success with no data won't get notified, that's the best we + // can do given current implementations) + if ( !status && s.isLocal && !s.crossDomain ) { + status = responses.text ? 200 : 404; + // IE - #1450: sometimes returns 1223 when it should be 204 + } else if ( status === 1223 ) { + status = 204; + } + } + } + } catch( firefoxAccessException ) { + if ( !isAbort ) { + complete( -1, firefoxAccessException ); + } + } + + // Call complete if needed + if ( responses ) { + complete( status, statusText, responses, responseHeaders ); + } + }; + + // if we're in sync mode or it's in cache + // and has been retrieved directly (IE6 & IE7) + // we need to manually fire the callback + if ( !s.async || xhr.readyState === 4 ) { + callback(); + } else { + handle = ++xhrId; + if ( xhrOnUnloadAbort ) { + // Create the active xhrs callbacks list if needed + // and attach the unload handler + if ( !xhrCallbacks ) { + xhrCallbacks = {}; + jQuery( window ).unload( xhrOnUnloadAbort ); + } + // Add to list of active xhrs callbacks + xhrCallbacks[ handle ] = callback; + } + xhr.onreadystatechange = callback; + } + }, + + abort: function() { + if ( callback ) { + callback(0,1); + } + } + }; + } + }); +} + + + + +var elemdisplay = {}, + iframe, iframeDoc, + rfxtypes = /^(?:toggle|show|hide)$/, + rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, + timerId, + fxAttrs = [ + // height animations + [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], + // width animations + [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], + // opacity animations + [ "opacity" ] + ], + fxNow; + +jQuery.fn.extend({ + show: function( speed, easing, callback ) { + var elem, display; + + if ( speed || speed === 0 ) { + return this.animate( genFx("show", 3), speed, easing, callback ); + + } else { + for ( var i = 0, j = this.length; i < j; i++ ) { + elem = this[ i ]; + + if ( elem.style ) { + display = elem.style.display; + + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { + display = elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( display === "" && jQuery.css(elem, "display") === "none" ) { + jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( i = 0; i < j; i++ ) { + elem = this[ i ]; + + if ( elem.style ) { + display = elem.style.display; + + if ( display === "" || display === "none" ) { + elem.style.display = jQuery._data( elem, "olddisplay" ) || ""; + } + } + } + + return this; + } + }, + + hide: function( speed, easing, callback ) { + if ( speed || speed === 0 ) { + return this.animate( genFx("hide", 3), speed, easing, callback); + + } else { + var elem, display, + i = 0, + j = this.length; + + for ( ; i < j; i++ ) { + elem = this[i]; + if ( elem.style ) { + display = jQuery.css( elem, "display" ); + + if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { + jQuery._data( elem, "olddisplay", display ); + } + } + } + + // Set the display of the elements in a second loop + // to avoid the constant reflow + for ( i = 0; i < j; i++ ) { + if ( this[i].style ) { + this[i].style.display = "none"; + } + } + + return this; + } + }, + + // Save the old toggle function + _toggle: jQuery.fn.toggle, + + toggle: function( fn, fn2, callback ) { + var bool = typeof fn === "boolean"; + + if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { + this._toggle.apply( this, arguments ); + + } else if ( fn == null || bool ) { + this.each(function() { + var state = bool ? fn : jQuery(this).is(":hidden"); + jQuery(this)[ state ? "show" : "hide" ](); + }); + + } else { + this.animate(genFx("toggle", 3), fn, fn2, callback); + } + + return this; + }, + + fadeTo: function( speed, to, easing, callback ) { + return this.filter(":hidden").css("opacity", 0).show().end() + .animate({opacity: to}, speed, easing, callback); + }, + + animate: function( prop, speed, easing, callback ) { + var optall = jQuery.speed( speed, easing, callback ); + + if ( jQuery.isEmptyObject( prop ) ) { + return this.each( optall.complete, [ false ] ); + } + + // Do not change referenced properties as per-property easing will be lost + prop = jQuery.extend( {}, prop ); + + function doAnimation() { + // XXX 'this' does not always have a nodeName when running the + // test suite + + if ( optall.queue === false ) { + jQuery._mark( this ); + } + + var opt = jQuery.extend( {}, optall ), + isElement = this.nodeType === 1, + hidden = isElement && jQuery(this).is(":hidden"), + name, val, p, e, + parts, start, end, unit, + method; + + // will store per property easing and be used to determine when an animation is complete + opt.animatedProperties = {}; + + for ( p in prop ) { + + // property name normalization + name = jQuery.camelCase( p ); + if ( p !== name ) { + prop[ name ] = prop[ p ]; + delete prop[ p ]; + } + + val = prop[ name ]; + + // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) + if ( jQuery.isArray( val ) ) { + opt.animatedProperties[ name ] = val[ 1 ]; + val = prop[ name ] = val[ 0 ]; + } else { + opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; + } + + if ( val === "hide" && hidden || val === "show" && !hidden ) { + return opt.complete.call( this ); + } + + if ( isElement && ( name === "height" || name === "width" ) ) { + // Make sure that nothing sneaks out + // Record all 3 overflow attributes because IE does not + // change the overflow attribute when overflowX and + // overflowY are set to the same value + opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; + + // Set display property to inline-block for height/width + // animations on inline elements that are having width/height animated + if ( jQuery.css( this, "display" ) === "inline" && + jQuery.css( this, "float" ) === "none" ) { + + // inline-level elements accept inline-block; + // block-level elements need to be inline with layout + if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { + this.style.display = "inline-block"; + + } else { + this.style.zoom = 1; + } + } + } + } + + if ( opt.overflow != null ) { + this.style.overflow = "hidden"; + } + + for ( p in prop ) { + e = new jQuery.fx( this, opt, p ); + val = prop[ p ]; + + if ( rfxtypes.test( val ) ) { + + // Tracks whether to show or hide based on private + // data attached to the element + method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); + if ( method ) { + jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); + e[ method ](); + } else { + e[ val ](); + } + + } else { + parts = rfxnum.exec( val ); + start = e.cur(); + + if ( parts ) { + end = parseFloat( parts[2] ); + unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); + + // We need to compute starting value + if ( unit !== "px" ) { + jQuery.style( this, p, (end || 1) + unit); + start = ( (end || 1) / e.cur() ) * start; + jQuery.style( this, p, start + unit); + } + + // If a +=/-= token was provided, we're doing a relative animation + if ( parts[1] ) { + end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; + } + + e.custom( start, end, unit ); + + } else { + e.custom( start, val, "" ); + } + } + } + + // For JS strict compliance + return true; + } + + return optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + + stop: function( type, clearQueue, gotoEnd ) { + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue && type !== false ) { + this.queue( type || "fx", [] ); + } + + return this.each(function() { + var index, + hadTimers = false, + timers = jQuery.timers, + data = jQuery._data( this ); + + // clear marker counters if we know they won't be + if ( !gotoEnd ) { + jQuery._unmark( true, this ); + } + + function stopQueue( elem, data, index ) { + var hooks = data[ index ]; + jQuery.removeData( elem, index, true ); + hooks.stop( gotoEnd ); + } + + if ( type == null ) { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { + stopQueue( this, data, index ); + } + } + } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ + stopQueue( this, data, index ); + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { + if ( gotoEnd ) { + + // force the next step to be the last + timers[ index ]( true ); + } else { + timers[ index ].saveState(); + } + hadTimers = true; + timers.splice( index, 1 ); + } + } + + // start the next in the queue if the last step wasn't forced + // timers currently will call their complete callbacks, which will dequeue + // but only if they were gotoEnd + if ( !( gotoEnd && hadTimers ) ) { + jQuery.dequeue( this, type ); + } + }); + } + +}); + +// Animations created synchronously will run synchronously +function createFxNow() { + setTimeout( clearFxNow, 0 ); + return ( fxNow = jQuery.now() ); +} + +function clearFxNow() { + fxNow = undefined; +} + +// Generate parameters to create a standard animation +function genFx( type, num ) { + var obj = {}; + + jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() { + obj[ this ] = type; + }); + + return obj; +} + +// Generate shortcuts for custom animations +jQuery.each({ + slideDown: genFx( "show", 1 ), + slideUp: genFx( "hide", 1 ), + slideToggle: genFx( "toggle", 1 ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +}); + +jQuery.extend({ + speed: function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing + }; + + opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : + opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; + + // normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function( noUnmark ) { + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } else if ( noUnmark !== false ) { + jQuery._unmark( this ); + } + }; + + return opt; + }, + + easing: { + linear: function( p, n, firstNum, diff ) { + return firstNum + diff * p; + }, + swing: function( p, n, firstNum, diff ) { + return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum; + } + }, + + timers: [], + + fx: function( elem, options, prop ) { + this.options = options; + this.elem = elem; + this.prop = prop; + + options.orig = options.orig || {}; + } + +}); + +jQuery.fx.prototype = { + // Simple function for setting a style value + update: function() { + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + ( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this ); + }, + + // Get the current size + cur: function() { + if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) { + return this.elem[ this.prop ]; + } + + var parsed, + r = jQuery.css( this.elem, this.prop ); + // Empty strings, null, undefined and "auto" are converted to 0, + // complex values such as "rotate(1rad)" are returned as is, + // simple values such as "10px" are parsed to Float. + return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; + }, + + // Start an animation from one number to another + custom: function( from, to, unit ) { + var self = this, + fx = jQuery.fx; + + this.startTime = fxNow || createFxNow(); + this.end = to; + this.now = this.start = from; + this.pos = this.state = 0; + this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); + + function t( gotoEnd ) { + return self.step( gotoEnd ); + } + + t.queue = this.options.queue; + t.elem = this.elem; + t.saveState = function() { + if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { + jQuery._data( self.elem, "fxshow" + self.prop, self.start ); + } + }; + + if ( t() && jQuery.timers.push(t) && !timerId ) { + timerId = setInterval( fx.tick, fx.interval ); + } + }, + + // Simple 'show' function + show: function() { + var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); + + // Remember where we started, so that we can go back to it later + this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop ); + this.options.show = true; + + // Begin the animation + // Make sure that we start at a small width/height to avoid any flash of content + if ( dataShow !== undefined ) { + // This show is picking up where a previous hide or show left off + this.custom( this.cur(), dataShow ); + } else { + this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() ); + } + + // Start by showing the element + jQuery( this.elem ).show(); + }, + + // Simple 'hide' function + hide: function() { + // Remember where we started, so that we can go back to it later + this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop ); + this.options.hide = true; + + // Begin the animation + this.custom( this.cur(), 0 ); + }, + + // Each step of an animation + step: function( gotoEnd ) { + var p, n, complete, + t = fxNow || createFxNow(), + done = true, + elem = this.elem, + options = this.options; + + if ( gotoEnd || t >= options.duration + this.startTime ) { + this.now = this.end; + this.pos = this.state = 1; + this.update(); + + options.animatedProperties[ this.prop ] = true; + + for ( p in options.animatedProperties ) { + if ( options.animatedProperties[ p ] !== true ) { + done = false; + } + } + + if ( done ) { + // Reset the overflow + if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { + + jQuery.each( [ "", "X", "Y" ], function( index, value ) { + elem.style[ "overflow" + value ] = options.overflow[ index ]; + }); + } + + // Hide the element if the "hide" operation was done + if ( options.hide ) { + jQuery( elem ).hide(); + } + + // Reset the properties, if the item has been hidden or shown + if ( options.hide || options.show ) { + for ( p in options.animatedProperties ) { + jQuery.style( elem, p, options.orig[ p ] ); + jQuery.removeData( elem, "fxshow" + p, true ); + // Toggle data is no longer needed + jQuery.removeData( elem, "toggle" + p, true ); + } + } + + // Execute the complete function + // in the event that the complete function throws an exception + // we must ensure it won't be called twice. #5684 + + complete = options.complete; + if ( complete ) { + + options.complete = false; + complete.call( elem ); + } + } + + return false; + + } else { + // classical easing cannot be used with an Infinity duration + if ( options.duration == Infinity ) { + this.now = t; + } else { + n = t - this.startTime; + this.state = n / options.duration; + + // Perform the easing function, defaults to swing + this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration ); + this.now = this.start + ( (this.end - this.start) * this.pos ); + } + // Perform the next step of the animation + this.update(); + } + + return true; + } +}; + +jQuery.extend( jQuery.fx, { + tick: function() { + var timer, + timers = jQuery.timers, + i = 0; + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + // Checks the timer has not already been removed + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + }, + + interval: 13, + + stop: function() { + clearInterval( timerId ); + timerId = null; + }, + + speeds: { + slow: 600, + fast: 200, + // Default speed + _default: 400 + }, + + step: { + opacity: function( fx ) { + jQuery.style( fx.elem, "opacity", fx.now ); + }, + + _default: function( fx ) { + if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { + fx.elem.style[ fx.prop ] = fx.now + fx.unit; + } else { + fx.elem[ fx.prop ] = fx.now; + } + } + } +}); + +// Adds width/height step functions +// Do not set anything below 0 +jQuery.each([ "width", "height" ], function( i, prop ) { + jQuery.fx.step[ prop ] = function( fx ) { + jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); + }; +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} + +// Try to restore the default display value of an element +function defaultDisplay( nodeName ) { + + if ( !elemdisplay[ nodeName ] ) { + + var body = document.body, + elem = jQuery( "<" + nodeName + ">" ).appendTo( body ), + display = elem.css( "display" ); + elem.remove(); + + // If the simple way fails, + // get element's real default display by attaching it to a temp iframe + if ( display === "none" || display === "" ) { + // No iframe to use yet, so create it + if ( !iframe ) { + iframe = document.createElement( "iframe" ); + iframe.frameBorder = iframe.width = iframe.height = 0; + } + + body.appendChild( iframe ); + + // Create a cacheable copy of the iframe document on first call. + // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML + // document to it; WebKit & Firefox won't allow reusing the iframe document. + if ( !iframeDoc || !iframe.createElement ) { + iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; + iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" ); + iframeDoc.close(); + } + + elem = iframeDoc.createElement( nodeName ); + + iframeDoc.body.appendChild( elem ); + + display = jQuery.css( elem, "display" ); + body.removeChild( iframe ); + } + + // Store the correct default display + elemdisplay[ nodeName ] = display; + } + + return elemdisplay[ nodeName ]; +} + + + + +var rtable = /^t(?:able|d|h)$/i, + rroot = /^(?:body|html)$/i; + +if ( "getBoundingClientRect" in document.documentElement ) { + jQuery.fn.offset = function( options ) { + var elem = this[0], box; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + try { + box = elem.getBoundingClientRect(); + } catch(e) {} + + var doc = elem.ownerDocument, + docElem = doc.documentElement; + + // Make sure we're not dealing with a disconnected DOM node + if ( !box || !jQuery.contains( docElem, elem ) ) { + return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; + } + + var body = doc.body, + win = getWindow(doc), + clientTop = docElem.clientTop || body.clientTop || 0, + clientLeft = docElem.clientLeft || body.clientLeft || 0, + scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, + scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, + top = box.top + scrollTop - clientTop, + left = box.left + scrollLeft - clientLeft; + + return { top: top, left: left }; + }; + +} else { + jQuery.fn.offset = function( options ) { + var elem = this[0]; + + if ( options ) { + return this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + if ( !elem || !elem.ownerDocument ) { + return null; + } + + if ( elem === elem.ownerDocument.body ) { + return jQuery.offset.bodyOffset( elem ); + } + + var computedStyle, + offsetParent = elem.offsetParent, + prevOffsetParent = elem, + doc = elem.ownerDocument, + docElem = doc.documentElement, + body = doc.body, + defaultView = doc.defaultView, + prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, + top = elem.offsetTop, + left = elem.offsetLeft; + + while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { + if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { + break; + } + + computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; + top -= elem.scrollTop; + left -= elem.scrollLeft; + + if ( elem === offsetParent ) { + top += elem.offsetTop; + left += elem.offsetLeft; + + if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevOffsetParent = offsetParent; + offsetParent = elem.offsetParent; + } + + if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { + top += parseFloat( computedStyle.borderTopWidth ) || 0; + left += parseFloat( computedStyle.borderLeftWidth ) || 0; + } + + prevComputedStyle = computedStyle; + } + + if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { + top += body.offsetTop; + left += body.offsetLeft; + } + + if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) { + top += Math.max( docElem.scrollTop, body.scrollTop ); + left += Math.max( docElem.scrollLeft, body.scrollLeft ); + } + + return { top: top, left: left }; + }; +} + +jQuery.offset = { + + bodyOffset: function( body ) { + var top = body.offsetTop, + left = body.offsetLeft; + + if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.css(body, "marginTop") ) || 0; + left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + var position = jQuery.css( elem, "position" ); + + // set position first, in-case top/left are set even on static elem + if ( position === "static" ) { + elem.style.position = "relative"; + } + + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curCSSTop = jQuery.css( elem, "top" ), + curCSSLeft = jQuery.css( elem, "left" ), + calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, + props = {}, curPosition = {}, curTop, curLeft; + + // need to be able to calculate position if either top or left is auto and position is either absolute or fixed + if ( calculatePosition ) { + curPosition = curElem.position(); + curTop = curPosition.top; + curLeft = curPosition.left; + } else { + curTop = parseFloat( curCSSTop ) || 0; + curLeft = parseFloat( curCSSLeft ) || 0; + } + + if ( jQuery.isFunction( options ) ) { + options = options.call( elem, i, curOffset ); + } + + if ( options.top != null ) { + props.top = ( options.top - curOffset.top ) + curTop; + } + if ( options.left != null ) { + props.left = ( options.left - curOffset.left ) + curLeft; + } + + if ( "using" in options ) { + options.using.call( elem, props ); + } else { + curElem.css( props ); + } + } +}; + + +jQuery.fn.extend({ + + position: function() { + if ( !this[0] ) { + return null; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract element margins + // note: when an element has margin: auto the offsetLeft and marginLeft + // are the same in Safari causing offset.left to incorrectly be 0 + offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; + offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; + parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent; + }); + } +}); + + +// Create scrollLeft and scrollTop methods +jQuery.each( ["Left", "Top"], function( i, name ) { + var method = "scroll" + name; + + jQuery.fn[ method ] = function( val ) { + var elem, win; + + if ( val === undefined ) { + elem = this[ 0 ]; + + if ( !elem ) { + return null; + } + + win = getWindow( elem ); + + // Return the scroll offset + return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : + jQuery.support.boxModel && win.document.documentElement[ method ] || + win.document.body[ method ] : + elem[ method ]; + } + + // Set the scroll offset + return this.each(function() { + win = getWindow( this ); + + if ( win ) { + win.scrollTo( + !i ? val : jQuery( win ).scrollLeft(), + i ? val : jQuery( win ).scrollTop() + ); + + } else { + this[ method ] = val; + } + }); + }; +}); + +function getWindow( elem ) { + return jQuery.isWindow( elem ) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} + + + + +// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods +jQuery.each([ "Height", "Width" ], function( i, name ) { + + var type = name.toLowerCase(); + + // innerHeight and innerWidth + jQuery.fn[ "inner" + name ] = function() { + var elem = this[0]; + return elem ? + elem.style ? + parseFloat( jQuery.css( elem, type, "padding" ) ) : + this[ type ]() : + null; + }; + + // outerHeight and outerWidth + jQuery.fn[ "outer" + name ] = function( margin ) { + var elem = this[0]; + return elem ? + elem.style ? + parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : + this[ type ]() : + null; + }; + + jQuery.fn[ type ] = function( size ) { + // Get window width or height + var elem = this[0]; + if ( !elem ) { + return size == null ? null : this; + } + + if ( jQuery.isFunction( size ) ) { + return this.each(function( i ) { + var self = jQuery( this ); + self[ type ]( size.call( this, i, self[ type ]() ) ); + }); + } + + if ( jQuery.isWindow( elem ) ) { + // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode + // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat + var docElemProp = elem.document.documentElement[ "client" + name ], + body = elem.document.body; + return elem.document.compatMode === "CSS1Compat" && docElemProp || + body && body[ "client" + name ] || docElemProp; + + // Get document width or height + } else if ( elem.nodeType === 9 ) { + // Either scroll[Width/Height] or offset[Width/Height], whichever is greater + return Math.max( + elem.documentElement["client" + name], + elem.body["scroll" + name], elem.documentElement["scroll" + name], + elem.body["offset" + name], elem.documentElement["offset" + name] + ); + + // Get or set width or height on the element + } else if ( size === undefined ) { + var orig = jQuery.css( elem, type ), + ret = parseFloat( orig ); + + return jQuery.isNumeric( ret ) ? ret : orig; + + // Set the width or height on the element (default to pixels if value is unitless) + } else { + return this.css( type, typeof size === "string" ? size : size + "px" ); + } + }; + +}); + + + + +// Expose jQuery to the global object +window.jQuery = window.$ = jQuery; + +// Expose jQuery as an AMD module, but only for AMD loaders that +// understand the issues with loading multiple versions of jQuery +// in a page that all might call define(). The loader will indicate +// they have special allowances for multiple jQuery versions by +// specifying define.amd.jQuery = true. Register as a named module, +// since jQuery can be concatenated with other files that may use define, +// but not use a proper concatenation script that understands anonymous +// AMD modules. A named AMD is safest and most robust way to register. +// Lowercase jquery is used because AMD module names are derived from +// file names, and jQuery is normally delivered in a lowercase file name. +// Do this after creating the global so that if an AMD module wants to call +// noConflict to hide this version of jQuery, it will work. +if ( typeof define === "function" && define.amd && define.amd.jQuery ) { + define( "jquery", [], function () { return jQuery; } ); +} + + + +})( window ); diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.min.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.min.js new file mode 100644 index 0000000..198b3ff --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery-1.7.1.min.js @@ -0,0 +1,4 @@ +/*! jQuery v1.7.1 jquery.com | jquery.org/license */ +(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; +f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() +{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery-ui-1.8.20.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery-ui-1.8.20.js new file mode 100644 index 0000000..3ce1541 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery-ui-1.8.20.js @@ -0,0 +1,11464 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.effects.core.js, jquery.effects.blind.js, jquery.effects.bounce.js, jquery.effects.clip.js, jquery.effects.drop.js, jquery.effects.explode.js, jquery.effects.fade.js, jquery.effects.fold.js, jquery.effects.highlight.js, jquery.effects.pulsate.js, jquery.effects.scale.js, jquery.effects.shake.js, jquery.effects.slide.js, jquery.effects.transfer.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.tabs.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ + +(function( $, undefined ) { + +// prevent duplicate loading +// this is only a problem because we proxy existing functions +// and we don't want to double proxy them +$.ui = $.ui || {}; +if ( $.ui.version ) { + return; +} + +$.extend( $.ui, { + version: "1.8.20", + + keyCode: { + ALT: 18, + BACKSPACE: 8, + CAPS_LOCK: 20, + COMMA: 188, + COMMAND: 91, + COMMAND_LEFT: 91, // COMMAND + COMMAND_RIGHT: 93, + CONTROL: 17, + DELETE: 46, + DOWN: 40, + END: 35, + ENTER: 13, + ESCAPE: 27, + HOME: 36, + INSERT: 45, + LEFT: 37, + MENU: 93, // COMMAND_RIGHT + NUMPAD_ADD: 107, + NUMPAD_DECIMAL: 110, + NUMPAD_DIVIDE: 111, + NUMPAD_ENTER: 108, + NUMPAD_MULTIPLY: 106, + NUMPAD_SUBTRACT: 109, + PAGE_DOWN: 34, + PAGE_UP: 33, + PERIOD: 190, + RIGHT: 39, + SHIFT: 16, + SPACE: 32, + TAB: 9, + UP: 38, + WINDOWS: 91 // COMMAND + } +}); + +// plugins +$.fn.extend({ + propAttr: $.fn.prop || $.fn.attr, + + _focus: $.fn.focus, + focus: function( delay, fn ) { + return typeof delay === "number" ? + this.each(function() { + var elem = this; + setTimeout(function() { + $( elem ).focus(); + if ( fn ) { + fn.call( elem ); + } + }, delay ); + }) : + this._focus.apply( this, arguments ); + }, + + scrollParent: function() { + var scrollParent; + if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { + scrollParent = this.parents().filter(function() { + return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } else { + scrollParent = this.parents().filter(function() { + return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); + }).eq(0); + } + + return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; + }, + + zIndex: function( zIndex ) { + if ( zIndex !== undefined ) { + return this.css( "zIndex", zIndex ); + } + + if ( this.length ) { + var elem = $( this[ 0 ] ), position, value; + while ( elem.length && elem[ 0 ] !== document ) { + // Ignore z-index if position is set to a value where z-index is ignored by the browser + // This makes behavior of this function consistent across browsers + // WebKit always returns auto if the element is positioned + position = elem.css( "position" ); + if ( position === "absolute" || position === "relative" || position === "fixed" ) { + // IE returns 0 when zIndex is not specified + // other browsers return a string + // we ignore the case of nested elements with an explicit value of 0 + // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> + value = parseInt( elem.css( "zIndex" ), 10 ); + if ( !isNaN( value ) && value !== 0 ) { + return value; + } + } + elem = elem.parent(); + } + } + + return 0; + }, + + disableSelection: function() { + return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + + ".ui-disableSelection", function( event ) { + event.preventDefault(); + }); + }, + + enableSelection: function() { + return this.unbind( ".ui-disableSelection" ); + } +}); + +$.each( [ "Width", "Height" ], function( i, name ) { + var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], + type = name.toLowerCase(), + orig = { + innerWidth: $.fn.innerWidth, + innerHeight: $.fn.innerHeight, + outerWidth: $.fn.outerWidth, + outerHeight: $.fn.outerHeight + }; + + function reduce( elem, size, border, margin ) { + $.each( side, function() { + size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0; + if ( border ) { + size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0; + } + if ( margin ) { + size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0; + } + }); + return size; + } + + $.fn[ "inner" + name ] = function( size ) { + if ( size === undefined ) { + return orig[ "inner" + name ].call( this ); + } + + return this.each(function() { + $( this ).css( type, reduce( this, size ) + "px" ); + }); + }; + + $.fn[ "outer" + name] = function( size, margin ) { + if ( typeof size !== "number" ) { + return orig[ "outer" + name ].call( this, size ); + } + + return this.each(function() { + $( this).css( type, reduce( this, size, true, margin ) + "px" ); + }); + }; +}); + +// selectors +function focusable( element, isTabIndexNotNaN ) { + var nodeName = element.nodeName.toLowerCase(); + if ( "area" === nodeName ) { + var map = element.parentNode, + mapName = map.name, + img; + if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { + return false; + } + img = $( "img[usemap=#" + mapName + "]" )[0]; + return !!img && visible( img ); + } + return ( /input|select|textarea|button|object/.test( nodeName ) + ? !element.disabled + : "a" == nodeName + ? element.href || isTabIndexNotNaN + : isTabIndexNotNaN) + // the element and all of its ancestors must be visible + && visible( element ); +} + +function visible( element ) { + return !$( element ).parents().andSelf().filter(function() { + return $.curCSS( this, "visibility" ) === "hidden" || + $.expr.filters.hidden( this ); + }).length; +} + +$.extend( $.expr[ ":" ], { + data: function( elem, i, match ) { + return !!$.data( elem, match[ 3 ] ); + }, + + focusable: function( element ) { + return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); + }, + + tabbable: function( element ) { + var tabIndex = $.attr( element, "tabindex" ), + isTabIndexNaN = isNaN( tabIndex ); + return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); + } +}); + +// support +$(function() { + var body = document.body, + div = body.appendChild( div = document.createElement( "div" ) ); + + // access offsetHeight before setting the style to prevent a layout bug + // in IE 9 which causes the elemnt to continue to take up space even + // after it is removed from the DOM (#8026) + div.offsetHeight; + + $.extend( div.style, { + minHeight: "100px", + height: "auto", + padding: 0, + borderWidth: 0 + }); + + $.support.minHeight = div.offsetHeight === 100; + $.support.selectstart = "onselectstart" in div; + + // set display to none to avoid a layout bug in IE + // http://dev.jquery.com/ticket/4014 + body.removeChild( div ).style.display = "none"; +}); + + + + + +// deprecated +$.extend( $.ui, { + // $.ui.plugin is deprecated. Use the proxy pattern instead. + plugin: { + add: function( module, option, set ) { + var proto = $.ui[ module ].prototype; + for ( var i in set ) { + proto.plugins[ i ] = proto.plugins[ i ] || []; + proto.plugins[ i ].push( [ option, set[ i ] ] ); + } + }, + call: function( instance, name, args ) { + var set = instance.plugins[ name ]; + if ( !set || !instance.element[ 0 ].parentNode ) { + return; + } + + for ( var i = 0; i < set.length; i++ ) { + if ( instance.options[ set[ i ][ 0 ] ] ) { + set[ i ][ 1 ].apply( instance.element, args ); + } + } + } + }, + + // will be deprecated when we switch to jQuery 1.4 - use jQuery.contains() + contains: function( a, b ) { + return document.compareDocumentPosition ? + a.compareDocumentPosition( b ) & 16 : + a !== b && a.contains( b ); + }, + + // only used by resizable + hasScroll: function( el, a ) { + + //If overflow is hidden, the element might have extra content, but the user wants to hide it + if ( $( el ).css( "overflow" ) === "hidden") { + return false; + } + + var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", + has = false; + + if ( el[ scroll ] > 0 ) { + return true; + } + + // TODO: determine which cases actually cause this to happen + // if the element doesn't have the scroll set, see if it's possible to + // set the scroll + el[ scroll ] = 1; + has = ( el[ scroll ] > 0 ); + el[ scroll ] = 0; + return has; + }, + + // these are odd functions, fix the API or move into individual plugins + isOverAxis: function( x, reference, size ) { + //Determines when x coordinate is over "b" element axis + return ( x > reference ) && ( x < ( reference + size ) ); + }, + isOver: function( y, x, top, left, height, width ) { + //Determines when x, y coordinates is over "b" element + return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width ); + } +}); + +})( jQuery ); + +(function( $, undefined ) { + +// jQuery 1.4+ +if ( $.cleanData ) { + var _cleanData = $.cleanData; + $.cleanData = function( elems ) { + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + try { + $( elem ).triggerHandler( "remove" ); + // http://bugs.jquery.com/ticket/8235 + } catch( e ) {} + } + _cleanData( elems ); + }; +} else { + var _remove = $.fn.remove; + $.fn.remove = function( selector, keepData ) { + return this.each(function() { + if ( !keepData ) { + if ( !selector || $.filter( selector, [ this ] ).length ) { + $( "*", this ).add( [ this ] ).each(function() { + try { + $( this ).triggerHandler( "remove" ); + // http://bugs.jquery.com/ticket/8235 + } catch( e ) {} + }); + } + } + return _remove.call( $(this), selector, keepData ); + }); + }; +} + +$.widget = function( name, base, prototype ) { + var namespace = name.split( "." )[ 0 ], + fullName; + name = name.split( "." )[ 1 ]; + fullName = namespace + "-" + name; + + if ( !prototype ) { + prototype = base; + base = $.Widget; + } + + // create selector for plugin + $.expr[ ":" ][ fullName ] = function( elem ) { + return !!$.data( elem, name ); + }; + + $[ namespace ] = $[ namespace ] || {}; + $[ namespace ][ name ] = function( options, element ) { + // allow instantiation without initializing for simple inheritance + if ( arguments.length ) { + this._createWidget( options, element ); + } + }; + + var basePrototype = new base(); + // we need to make the options hash a property directly on the new instance + // otherwise we'll modify the options hash on the prototype that we're + // inheriting from +// $.each( basePrototype, function( key, val ) { +// if ( $.isPlainObject(val) ) { +// basePrototype[ key ] = $.extend( {}, val ); +// } +// }); + basePrototype.options = $.extend( true, {}, basePrototype.options ); + $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { + namespace: namespace, + widgetName: name, + widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, + widgetBaseClass: fullName + }, prototype ); + + $.widget.bridge( name, $[ namespace ][ name ] ); +}; + +$.widget.bridge = function( name, object ) { + $.fn[ name ] = function( options ) { + var isMethodCall = typeof options === "string", + args = Array.prototype.slice.call( arguments, 1 ), + returnValue = this; + + // allow multiple hashes to be passed on init + options = !isMethodCall && args.length ? + $.extend.apply( null, [ true, options ].concat(args) ) : + options; + + // prevent calls to internal methods + if ( isMethodCall && options.charAt( 0 ) === "_" ) { + return returnValue; + } + + if ( isMethodCall ) { + this.each(function() { + var instance = $.data( this, name ), + methodValue = instance && $.isFunction( instance[options] ) ? + instance[ options ].apply( instance, args ) : + instance; + // TODO: add this back in 1.9 and use $.error() (see #5972) +// if ( !instance ) { +// throw "cannot call methods on " + name + " prior to initialization; " + +// "attempted to call method '" + options + "'"; +// } +// if ( !$.isFunction( instance[options] ) ) { +// throw "no such method '" + options + "' for " + name + " widget instance"; +// } +// var methodValue = instance[ options ].apply( instance, args ); + if ( methodValue !== instance && methodValue !== undefined ) { + returnValue = methodValue; + return false; + } + }); + } else { + this.each(function() { + var instance = $.data( this, name ); + if ( instance ) { + instance.option( options || {} )._init(); + } else { + $.data( this, name, new object( options, this ) ); + } + }); + } + + return returnValue; + }; +}; + +$.Widget = function( options, element ) { + // allow instantiation without initializing for simple inheritance + if ( arguments.length ) { + this._createWidget( options, element ); + } +}; + +$.Widget.prototype = { + widgetName: "widget", + widgetEventPrefix: "", + options: { + disabled: false + }, + _createWidget: function( options, element ) { + // $.widget.bridge stores the plugin instance, but we do it anyway + // so that it's stored even before the _create function runs + $.data( element, this.widgetName, this ); + this.element = $( element ); + this.options = $.extend( true, {}, + this.options, + this._getCreateOptions(), + options ); + + var self = this; + this.element.bind( "remove." + this.widgetName, function() { + self.destroy(); + }); + + this._create(); + this._trigger( "create" ); + this._init(); + }, + _getCreateOptions: function() { + return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; + }, + _create: function() {}, + _init: function() {}, + + destroy: function() { + this.element + .unbind( "." + this.widgetName ) + .removeData( this.widgetName ); + this.widget() + .unbind( "." + this.widgetName ) + .removeAttr( "aria-disabled" ) + .removeClass( + this.widgetBaseClass + "-disabled " + + "ui-state-disabled" ); + }, + + widget: function() { + return this.element; + }, + + option: function( key, value ) { + var options = key; + + if ( arguments.length === 0 ) { + // don't return a reference to the internal hash + return $.extend( {}, this.options ); + } + + if (typeof key === "string" ) { + if ( value === undefined ) { + return this.options[ key ]; + } + options = {}; + options[ key ] = value; + } + + this._setOptions( options ); + + return this; + }, + _setOptions: function( options ) { + var self = this; + $.each( options, function( key, value ) { + self._setOption( key, value ); + }); + + return this; + }, + _setOption: function( key, value ) { + this.options[ key ] = value; + + if ( key === "disabled" ) { + this.widget() + [ value ? "addClass" : "removeClass"]( + this.widgetBaseClass + "-disabled" + " " + + "ui-state-disabled" ) + .attr( "aria-disabled", value ); + } + + return this; + }, + + enable: function() { + return this._setOption( "disabled", false ); + }, + disable: function() { + return this._setOption( "disabled", true ); + }, + + _trigger: function( type, event, data ) { + var prop, orig, + callback = this.options[ type ]; + + data = data || {}; + event = $.Event( event ); + event.type = ( type === this.widgetEventPrefix ? + type : + this.widgetEventPrefix + type ).toLowerCase(); + // the original event may come from any element + // so we need to reset the target on the new event + event.target = this.element[ 0 ]; + + // copy original event properties over to the new event + orig = event.originalEvent; + if ( orig ) { + for ( prop in orig ) { + if ( !( prop in event ) ) { + event[ prop ] = orig[ prop ]; + } + } + } + + this.element.trigger( event, data ); + + return !( $.isFunction(callback) && + callback.call( this.element[0], event, data ) === false || + event.isDefaultPrevented() ); + } +}; + +})( jQuery ); + +(function( $, undefined ) { + +var mouseHandled = false; +$( document ).mouseup( function( e ) { + mouseHandled = false; +}); + +$.widget("ui.mouse", { + options: { + cancel: ':input,option', + distance: 1, + delay: 0 + }, + _mouseInit: function() { + var self = this; + + this.element + .bind('mousedown.'+this.widgetName, function(event) { + return self._mouseDown(event); + }) + .bind('click.'+this.widgetName, function(event) { + if (true === $.data(event.target, self.widgetName + '.preventClickEvent')) { + $.removeData(event.target, self.widgetName + '.preventClickEvent'); + event.stopImmediatePropagation(); + return false; + } + }); + + this.started = false; + }, + + // TODO: make sure destroying one instance of mouse doesn't mess with + // other instances of mouse + _mouseDestroy: function() { + this.element.unbind('.'+this.widgetName); + $(document) + .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); + }, + + _mouseDown: function(event) { + // don't let more than one widget handle mouseStart + if( mouseHandled ) { return }; + + // we may have missed mouseup (out of window) + (this._mouseStarted && this._mouseUp(event)); + + this._mouseDownEvent = event; + + var self = this, + btnIsLeft = (event.which == 1), + // event.target.nodeName works around a bug in IE 8 with + // disabled inputs (#7620) + elIsCancel = (typeof this.options.cancel == "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); + if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { + return true; + } + + this.mouseDelayMet = !this.options.delay; + if (!this.mouseDelayMet) { + this._mouseDelayTimer = setTimeout(function() { + self.mouseDelayMet = true; + }, this.options.delay); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = (this._mouseStart(event) !== false); + if (!this._mouseStarted) { + event.preventDefault(); + return true; + } + } + + // Click event may never have fired (Gecko & Opera) + if (true === $.data(event.target, this.widgetName + '.preventClickEvent')) { + $.removeData(event.target, this.widgetName + '.preventClickEvent'); + } + + // these delegates are required to keep context + this._mouseMoveDelegate = function(event) { + return self._mouseMove(event); + }; + this._mouseUpDelegate = function(event) { + return self._mouseUp(event); + }; + $(document) + .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + event.preventDefault(); + + mouseHandled = true; + return true; + }, + + _mouseMove: function(event) { + // IE mouseup check - mouseup happened when mouse was out of window + if ($.browser.msie && !(document.documentMode >= 9) && !event.button) { + return this._mouseUp(event); + } + + if (this._mouseStarted) { + this._mouseDrag(event); + return event.preventDefault(); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = + (this._mouseStart(this._mouseDownEvent, event) !== false); + (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); + } + + return !this._mouseStarted; + }, + + _mouseUp: function(event) { + $(document) + .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) + .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); + + if (this._mouseStarted) { + this._mouseStarted = false; + + if (event.target == this._mouseDownEvent.target) { + $.data(event.target, this.widgetName + '.preventClickEvent', true); + } + + this._mouseStop(event); + } + + return false; + }, + + _mouseDistanceMet: function(event) { + return (Math.max( + Math.abs(this._mouseDownEvent.pageX - event.pageX), + Math.abs(this._mouseDownEvent.pageY - event.pageY) + ) >= this.options.distance + ); + }, + + _mouseDelayMet: function(event) { + return this.mouseDelayMet; + }, + + // These are placeholder methods, to be overriden by extending plugin + _mouseStart: function(event) {}, + _mouseDrag: function(event) {}, + _mouseStop: function(event) {}, + _mouseCapture: function(event) { return true; } +}); + +})(jQuery); + +(function( $, undefined ) { + +$.widget("ui.draggable", $.ui.mouse, { + widgetEventPrefix: "drag", + options: { + addClasses: true, + appendTo: "parent", + axis: false, + connectToSortable: false, + containment: false, + cursor: "auto", + cursorAt: false, + grid: false, + handle: false, + helper: "original", + iframeFix: false, + opacity: false, + refreshPositions: false, + revert: false, + revertDuration: 500, + scope: "default", + scroll: true, + scrollSensitivity: 20, + scrollSpeed: 20, + snap: false, + snapMode: "both", + snapTolerance: 20, + stack: false, + zIndex: false + }, + _create: function() { + + if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position"))) + this.element[0].style.position = 'relative'; + + (this.options.addClasses && this.element.addClass("ui-draggable")); + (this.options.disabled && this.element.addClass("ui-draggable-disabled")); + + this._mouseInit(); + + }, + + destroy: function() { + if(!this.element.data('draggable')) return; + this.element + .removeData("draggable") + .unbind(".draggable") + .removeClass("ui-draggable" + + " ui-draggable-dragging" + + " ui-draggable-disabled"); + this._mouseDestroy(); + + return this; + }, + + _mouseCapture: function(event) { + + var o = this.options; + + // among others, prevent a drag on a resizable-handle + if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle')) + return false; + + //Quit if we're not on a valid handle + this.handle = this._getHandle(event); + if (!this.handle) + return false; + + if ( o.iframeFix ) { + $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { + $('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>') + .css({ + width: this.offsetWidth+"px", height: this.offsetHeight+"px", + position: "absolute", opacity: "0.001", zIndex: 1000 + }) + .css($(this).offset()) + .appendTo("body"); + }); + } + + return true; + + }, + + _mouseStart: function(event) { + + var o = this.options; + + //Create and append the visible helper + this.helper = this._createHelper(event); + + //Cache the helper size + this._cacheHelperProportions(); + + //If ddmanager is used for droppables, set the global draggable + if($.ui.ddmanager) + $.ui.ddmanager.current = this; + + /* + * - Position generation - + * This block generates everything position related - it's the core of draggables. + */ + + //Cache the margins of the original element + this._cacheMargins(); + + //Store the helper's css position + this.cssPosition = this.helper.css("position"); + this.scrollParent = this.helper.scrollParent(); + + //The element's absolute position on the page minus margins + this.offset = this.positionAbs = this.element.offset(); + this.offset = { + top: this.offset.top - this.margins.top, + left: this.offset.left - this.margins.left + }; + + $.extend(this.offset, { + click: { //Where the click happened, relative to the element + left: event.pageX - this.offset.left, + top: event.pageY - this.offset.top + }, + parent: this._getParentOffset(), + relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper + }); + + //Generate the original position + this.originalPosition = this.position = this._generatePosition(event); + this.originalPageX = event.pageX; + this.originalPageY = event.pageY; + + //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied + (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); + + //Set a containment if given in the options + if(o.containment) + this._setContainment(); + + //Trigger event + callbacks + if(this._trigger("start", event) === false) { + this._clear(); + return false; + } + + //Recache the helper size + this._cacheHelperProportions(); + + //Prepare the droppable offsets + if ($.ui.ddmanager && !o.dropBehaviour) + $.ui.ddmanager.prepareOffsets(this, event); + + this.helper.addClass("ui-draggable-dragging"); + this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position + + //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) + if ( $.ui.ddmanager ) $.ui.ddmanager.dragStart(this, event); + + return true; + }, + + _mouseDrag: function(event, noPropagation) { + + //Compute the helpers position + this.position = this._generatePosition(event); + this.positionAbs = this._convertPositionTo("absolute"); + + //Call plugins and callbacks and use the resulting position if something is returned + if (!noPropagation) { + var ui = this._uiHash(); + if(this._trigger('drag', event, ui) === false) { + this._mouseUp({}); + return false; + } + this.position = ui.position; + } + + if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px'; + if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px'; + if($.ui.ddmanager) $.ui.ddmanager.drag(this, event); + + return false; + }, + + _mouseStop: function(event) { + + //If we are using droppables, inform the manager about the drop + var dropped = false; + if ($.ui.ddmanager && !this.options.dropBehaviour) + dropped = $.ui.ddmanager.drop(this, event); + + //if a drop comes from outside (a sortable) + if(this.dropped) { + dropped = this.dropped; + this.dropped = false; + } + + //if the original element is no longer in the DOM don't bother to continue (see #8269) + var element = this.element[0], elementInDom = false; + while ( element && (element = element.parentNode) ) { + if (element == document ) { + elementInDom = true; + } + } + if ( !elementInDom && this.options.helper === "original" ) + return false; + + if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { + var self = this; + $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { + if(self._trigger("stop", event) !== false) { + self._clear(); + } + }); + } else { + if(this._trigger("stop", event) !== false) { + this._clear(); + } + } + + return false; + }, + + _mouseUp: function(event) { + if (this.options.iframeFix === true) { + $("div.ui-draggable-iframeFix").each(function() { + this.parentNode.removeChild(this); + }); //Remove frame helpers + } + + //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) + if( $.ui.ddmanager ) $.ui.ddmanager.dragStop(this, event); + + return $.ui.mouse.prototype._mouseUp.call(this, event); + }, + + cancel: function() { + + if(this.helper.is(".ui-draggable-dragging")) { + this._mouseUp({}); + } else { + this._clear(); + } + + return this; + + }, + + _getHandle: function(event) { + + var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false; + $(this.options.handle, this.element) + .find("*") + .andSelf() + .each(function() { + if(this == event.target) handle = true; + }); + + return handle; + + }, + + _createHelper: function(event) { + + var o = this.options; + var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone().removeAttr('id') : this.element); + + if(!helper.parents('body').length) + helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo)); + + if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) + helper.css("position", "absolute"); + + return helper; + + }, + + _adjustOffsetFromHelper: function(obj) { + if (typeof obj == 'string') { + obj = obj.split(' '); + } + if ($.isArray(obj)) { + obj = {left: +obj[0], top: +obj[1] || 0}; + } + if ('left' in obj) { + this.offset.click.left = obj.left + this.margins.left; + } + if ('right' in obj) { + this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; + } + if ('top' in obj) { + this.offset.click.top = obj.top + this.margins.top; + } + if ('bottom' in obj) { + this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; + } + }, + + _getParentOffset: function() { + + //Get the offsetParent and cache its position + this.offsetParent = this.helper.offsetParent(); + var po = this.offsetParent.offset(); + + // This is a special case where we need to modify a offset calculated on start, since the following happened: + // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent + // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that + // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag + if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) { + po.left += this.scrollParent.scrollLeft(); + po.top += this.scrollParent.scrollTop(); + } + + if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information + || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix + po = { top: 0, left: 0 }; + + return { + top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), + left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) + }; + + }, + + _getRelativeOffset: function() { + + if(this.cssPosition == "relative") { + var p = this.element.position(); + return { + top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), + left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() + }; + } else { + return { top: 0, left: 0 }; + } + + }, + + _cacheMargins: function() { + this.margins = { + left: (parseInt(this.element.css("marginLeft"),10) || 0), + top: (parseInt(this.element.css("marginTop"),10) || 0), + right: (parseInt(this.element.css("marginRight"),10) || 0), + bottom: (parseInt(this.element.css("marginBottom"),10) || 0) + }; + }, + + _cacheHelperProportions: function() { + this.helperProportions = { + width: this.helper.outerWidth(), + height: this.helper.outerHeight() + }; + }, + + _setContainment: function() { + + var o = this.options; + if(o.containment == 'parent') o.containment = this.helper[0].parentNode; + if(o.containment == 'document' || o.containment == 'window') this.containment = [ + o.containment == 'document' ? 0 : $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left, + o.containment == 'document' ? 0 : $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top, + (o.containment == 'document' ? 0 : $(window).scrollLeft()) + $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left, + (o.containment == 'document' ? 0 : $(window).scrollTop()) + ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top + ]; + + if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) { + var c = $(o.containment); + var ce = c[0]; if(!ce) return; + var co = c.offset(); + var over = ($(ce).css("overflow") != 'hidden'); + + this.containment = [ + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0), + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0), + (over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right, + (over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom + ]; + this.relative_container = c; + + } else if(o.containment.constructor == Array) { + this.containment = o.containment; + } + + }, + + _convertPositionTo: function(d, pos) { + + if(!pos) pos = this.position; + var mod = d == "absolute" ? 1 : -1; + var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); + + return { + top: ( + pos.top // The absolute mouse position + + this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent + + this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border) + - ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) + ), + left: ( + pos.left // The absolute mouse position + + this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent + + this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border) + - ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) + ) + }; + + }, + + _generatePosition: function(event) { + + var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); + var pageX = event.pageX; + var pageY = event.pageY; + + /* + * - Position constraining - + * Constrain the position to a mix of grid, containment. + */ + + if(this.originalPosition) { //If we are not dragging yet, we won't check for options + var containment; + if(this.containment) { + if (this.relative_container){ + var co = this.relative_container.offset(); + containment = [ this.containment[0] + co.left, + this.containment[1] + co.top, + this.containment[2] + co.left, + this.containment[3] + co.top ]; + } + else { + containment = this.containment; + } + + if(event.pageX - this.offset.click.left < containment[0]) pageX = containment[0] + this.offset.click.left; + if(event.pageY - this.offset.click.top < containment[1]) pageY = containment[1] + this.offset.click.top; + if(event.pageX - this.offset.click.left > containment[2]) pageX = containment[2] + this.offset.click.left; + if(event.pageY - this.offset.click.top > containment[3]) pageY = containment[3] + this.offset.click.top; + } + + if(o.grid) { + //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) + var top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; + pageY = containment ? (!(top - this.offset.click.top < containment[1] || top - this.offset.click.top > containment[3]) ? top : (!(top - this.offset.click.top < containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; + + var left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; + pageX = containment ? (!(left - this.offset.click.left < containment[0] || left - this.offset.click.left > containment[2]) ? left : (!(left - this.offset.click.left < containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; + } + + } + + return { + top: ( + pageY // The absolute mouse position + - this.offset.click.top // Click offset (relative to the element) + - this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent + - this.offset.parent.top // The offsetParent's offset without borders (offset + border) + + ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) + ), + left: ( + pageX // The absolute mouse position + - this.offset.click.left // Click offset (relative to the element) + - this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent + - this.offset.parent.left // The offsetParent's offset without borders (offset + border) + + ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) + ) + }; + + }, + + _clear: function() { + this.helper.removeClass("ui-draggable-dragging"); + if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove(); + //if($.ui.ddmanager) $.ui.ddmanager.current = null; + this.helper = null; + this.cancelHelperRemoval = false; + }, + + // From now on bulk stuff - mainly helpers + + _trigger: function(type, event, ui) { + ui = ui || this._uiHash(); + $.ui.plugin.call(this, type, [event, ui]); + if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins + return $.Widget.prototype._trigger.call(this, type, event, ui); + }, + + plugins: {}, + + _uiHash: function(event) { + return { + helper: this.helper, + position: this.position, + originalPosition: this.originalPosition, + offset: this.positionAbs + }; + } + +}); + +$.extend($.ui.draggable, { + version: "1.8.20" +}); + +$.ui.plugin.add("draggable", "connectToSortable", { + start: function(event, ui) { + + var inst = $(this).data("draggable"), o = inst.options, + uiSortable = $.extend({}, ui, { item: inst.element }); + inst.sortables = []; + $(o.connectToSortable).each(function() { + var sortable = $.data(this, 'sortable'); + if (sortable && !sortable.options.disabled) { + inst.sortables.push({ + instance: sortable, + shouldRevert: sortable.options.revert + }); + sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). + sortable._trigger("activate", event, uiSortable); + } + }); + + }, + stop: function(event, ui) { + + //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper + var inst = $(this).data("draggable"), + uiSortable = $.extend({}, ui, { item: inst.element }); + + $.each(inst.sortables, function() { + if(this.instance.isOver) { + + this.instance.isOver = 0; + + inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance + this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) + + //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid' + if(this.shouldRevert) this.instance.options.revert = true; + + //Trigger the stop of the sortable + this.instance._mouseStop(event); + + this.instance.options.helper = this.instance.options._helper; + + //If the helper has been the original item, restore properties in the sortable + if(inst.options.helper == 'original') + this.instance.currentItem.css({ top: 'auto', left: 'auto' }); + + } else { + this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance + this.instance._trigger("deactivate", event, uiSortable); + } + + }); + + }, + drag: function(event, ui) { + + var inst = $(this).data("draggable"), self = this; + + var checkPos = function(o) { + var dyClick = this.offset.click.top, dxClick = this.offset.click.left; + var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left; + var itemHeight = o.height, itemWidth = o.width; + var itemTop = o.top, itemLeft = o.left; + + return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth); + }; + + $.each(inst.sortables, function(i) { + + //Copy over some variables to allow calling the sortable's native _intersectsWith + this.instance.positionAbs = inst.positionAbs; + this.instance.helperProportions = inst.helperProportions; + this.instance.offset.click = inst.offset.click; + + if(this.instance._intersectsWith(this.instance.containerCache)) { + + //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once + if(!this.instance.isOver) { + + this.instance.isOver = 1; + //Now we fake the start of dragging for the sortable instance, + //by cloning the list group item, appending it to the sortable and using it as inst.currentItem + //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) + this.instance.currentItem = $(self).clone().removeAttr('id').appendTo(this.instance.element).data("sortable-item", true); + this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it + this.instance.options.helper = function() { return ui.helper[0]; }; + + event.target = this.instance.currentItem[0]; + this.instance._mouseCapture(event, true); + this.instance._mouseStart(event, true, true); + + //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes + this.instance.offset.click.top = inst.offset.click.top; + this.instance.offset.click.left = inst.offset.click.left; + this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; + this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; + + inst._trigger("toSortable", event); + inst.dropped = this.instance.element; //draggable revert needs that + //hack so receive/update callbacks work (mostly) + inst.currentItem = inst.element; + this.instance.fromOutside = inst; + + } + + //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable + if(this.instance.currentItem) this.instance._mouseDrag(event); + + } else { + + //If it doesn't intersect with the sortable, and it intersected before, + //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval + if(this.instance.isOver) { + + this.instance.isOver = 0; + this.instance.cancelHelperRemoval = true; + + //Prevent reverting on this forced stop + this.instance.options.revert = false; + + // The out event needs to be triggered independently + this.instance._trigger('out', event, this.instance._uiHash(this.instance)); + + this.instance._mouseStop(event, true); + this.instance.options.helper = this.instance.options._helper; + + //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size + this.instance.currentItem.remove(); + if(this.instance.placeholder) this.instance.placeholder.remove(); + + inst._trigger("fromSortable", event); + inst.dropped = false; //draggable revert needs that + } + + }; + + }); + + } +}); + +$.ui.plugin.add("draggable", "cursor", { + start: function(event, ui) { + var t = $('body'), o = $(this).data('draggable').options; + if (t.css("cursor")) o._cursor = t.css("cursor"); + t.css("cursor", o.cursor); + }, + stop: function(event, ui) { + var o = $(this).data('draggable').options; + if (o._cursor) $('body').css("cursor", o._cursor); + } +}); + +$.ui.plugin.add("draggable", "opacity", { + start: function(event, ui) { + var t = $(ui.helper), o = $(this).data('draggable').options; + if(t.css("opacity")) o._opacity = t.css("opacity"); + t.css('opacity', o.opacity); + }, + stop: function(event, ui) { + var o = $(this).data('draggable').options; + if(o._opacity) $(ui.helper).css('opacity', o._opacity); + } +}); + +$.ui.plugin.add("draggable", "scroll", { + start: function(event, ui) { + var i = $(this).data("draggable"); + if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset(); + }, + drag: function(event, ui) { + + var i = $(this).data("draggable"), o = i.options, scrolled = false; + + if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') { + + if(!o.axis || o.axis != 'x') { + if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) + i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; + else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) + i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; + } + + if(!o.axis || o.axis != 'y') { + if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) + i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; + else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) + i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; + } + + } else { + + if(!o.axis || o.axis != 'x') { + if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) + scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); + else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) + scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); + } + + if(!o.axis || o.axis != 'y') { + if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) + scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); + else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) + scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); + } + + } + + if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) + $.ui.ddmanager.prepareOffsets(i, event); + + } +}); + +$.ui.plugin.add("draggable", "snap", { + start: function(event, ui) { + + var i = $(this).data("draggable"), o = i.options; + i.snapElements = []; + + $(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() { + var $t = $(this); var $o = $t.offset(); + if(this != i.element[0]) i.snapElements.push({ + item: this, + width: $t.outerWidth(), height: $t.outerHeight(), + top: $o.top, left: $o.left + }); + }); + + }, + drag: function(event, ui) { + + var inst = $(this).data("draggable"), o = inst.options; + var d = o.snapTolerance; + + var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, + y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; + + for (var i = inst.snapElements.length - 1; i >= 0; i--){ + + var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width, + t = inst.snapElements[i].top, b = t + inst.snapElements[i].height; + + //Yes, I know, this is insane ;) + if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) { + if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); + inst.snapElements[i].snapping = false; + continue; + } + + if(o.snapMode != 'inner') { + var ts = Math.abs(t - y2) <= d; + var bs = Math.abs(b - y1) <= d; + var ls = Math.abs(l - x2) <= d; + var rs = Math.abs(r - x1) <= d; + if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; + if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; + if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; + if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; + } + + var first = (ts || bs || ls || rs); + + if(o.snapMode != 'outer') { + var ts = Math.abs(t - y1) <= d; + var bs = Math.abs(b - y2) <= d; + var ls = Math.abs(l - x1) <= d; + var rs = Math.abs(r - x2) <= d; + if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; + if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; + if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; + if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; + } + + if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) + (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); + inst.snapElements[i].snapping = (ts || bs || ls || rs || first); + + }; + + } +}); + +$.ui.plugin.add("draggable", "stack", { + start: function(event, ui) { + + var o = $(this).data("draggable").options; + + var group = $.makeArray($(o.stack)).sort(function(a,b) { + return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); + }); + if (!group.length) { return; } + + var min = parseInt(group[0].style.zIndex) || 0; + $(group).each(function(i) { + this.style.zIndex = min + i; + }); + + this[0].style.zIndex = min + group.length; + + } +}); + +$.ui.plugin.add("draggable", "zIndex", { + start: function(event, ui) { + var t = $(ui.helper), o = $(this).data("draggable").options; + if(t.css("zIndex")) o._zIndex = t.css("zIndex"); + t.css('zIndex', o.zIndex); + }, + stop: function(event, ui) { + var o = $(this).data("draggable").options; + if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex); + } +}); + +})(jQuery); + +(function( $, undefined ) { + +$.widget("ui.droppable", { + widgetEventPrefix: "drop", + options: { + accept: '*', + activeClass: false, + addClasses: true, + greedy: false, + hoverClass: false, + scope: 'default', + tolerance: 'intersect' + }, + _create: function() { + + var o = this.options, accept = o.accept; + this.isover = 0; this.isout = 1; + + this.accept = $.isFunction(accept) ? accept : function(d) { + return d.is(accept); + }; + + //Store the droppable's proportions + this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; + + // Add the reference and positions to the manager + $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; + $.ui.ddmanager.droppables[o.scope].push(this); + + (o.addClasses && this.element.addClass("ui-droppable")); + + }, + + destroy: function() { + var drop = $.ui.ddmanager.droppables[this.options.scope]; + for ( var i = 0; i < drop.length; i++ ) + if ( drop[i] == this ) + drop.splice(i, 1); + + this.element + .removeClass("ui-droppable ui-droppable-disabled") + .removeData("droppable") + .unbind(".droppable"); + + return this; + }, + + _setOption: function(key, value) { + + if(key == 'accept') { + this.accept = $.isFunction(value) ? value : function(d) { + return d.is(value); + }; + } + $.Widget.prototype._setOption.apply(this, arguments); + }, + + _activate: function(event) { + var draggable = $.ui.ddmanager.current; + if(this.options.activeClass) this.element.addClass(this.options.activeClass); + (draggable && this._trigger('activate', event, this.ui(draggable))); + }, + + _deactivate: function(event) { + var draggable = $.ui.ddmanager.current; + if(this.options.activeClass) this.element.removeClass(this.options.activeClass); + (draggable && this._trigger('deactivate', event, this.ui(draggable))); + }, + + _over: function(event) { + + var draggable = $.ui.ddmanager.current; + if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element + + if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { + if(this.options.hoverClass) this.element.addClass(this.options.hoverClass); + this._trigger('over', event, this.ui(draggable)); + } + + }, + + _out: function(event) { + + var draggable = $.ui.ddmanager.current; + if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element + + if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { + if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); + this._trigger('out', event, this.ui(draggable)); + } + + }, + + _drop: function(event,custom) { + + var draggable = custom || $.ui.ddmanager.current; + if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element + + var childrenIntersection = false; + this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() { + var inst = $.data(this, 'droppable'); + if( + inst.options.greedy + && !inst.options.disabled + && inst.options.scope == draggable.options.scope + && inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) + && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance) + ) { childrenIntersection = true; return false; } + }); + if(childrenIntersection) return false; + + if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { + if(this.options.activeClass) this.element.removeClass(this.options.activeClass); + if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); + this._trigger('drop', event, this.ui(draggable)); + return this.element; + } + + return false; + + }, + + ui: function(c) { + return { + draggable: (c.currentItem || c.element), + helper: c.helper, + position: c.position, + offset: c.positionAbs + }; + } + +}); + +$.extend($.ui.droppable, { + version: "1.8.20" +}); + +$.ui.intersect = function(draggable, droppable, toleranceMode) { + + if (!droppable.offset) return false; + + var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, + y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height; + var l = droppable.offset.left, r = l + droppable.proportions.width, + t = droppable.offset.top, b = t + droppable.proportions.height; + + switch (toleranceMode) { + case 'fit': + return (l <= x1 && x2 <= r + && t <= y1 && y2 <= b); + break; + case 'intersect': + return (l < x1 + (draggable.helperProportions.width / 2) // Right Half + && x2 - (draggable.helperProportions.width / 2) < r // Left Half + && t < y1 + (draggable.helperProportions.height / 2) // Bottom Half + && y2 - (draggable.helperProportions.height / 2) < b ); // Top Half + break; + case 'pointer': + var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left), + draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top), + isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width); + return isOver; + break; + case 'touch': + return ( + (y1 >= t && y1 <= b) || // Top edge touching + (y2 >= t && y2 <= b) || // Bottom edge touching + (y1 < t && y2 > b) // Surrounded vertically + ) && ( + (x1 >= l && x1 <= r) || // Left edge touching + (x2 >= l && x2 <= r) || // Right edge touching + (x1 < l && x2 > r) // Surrounded horizontally + ); + break; + default: + return false; + break; + } + +}; + +/* + This manager tracks offsets of draggables and droppables +*/ +$.ui.ddmanager = { + current: null, + droppables: { 'default': [] }, + prepareOffsets: function(t, event) { + + var m = $.ui.ddmanager.droppables[t.options.scope] || []; + var type = event ? event.type : null; // workaround for #2317 + var list = (t.currentItem || t.element).find(":data(droppable)").andSelf(); + + droppablesLoop: for (var i = 0; i < m.length; i++) { + + if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) continue; //No disabled and non-accepted + for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item + m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; //If the element is not visible, continue + + if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables + + m[i].offset = m[i].element.offset(); + m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; + + } + + }, + drop: function(draggable, event) { + + var dropped = false; + $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { + + if(!this.options) return; + if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) + dropped = this._drop.call(this, event) || dropped; + + if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { + this.isout = 1; this.isover = 0; + this._deactivate.call(this, event); + } + + }); + return dropped; + + }, + dragStart: function( draggable, event ) { + //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) + draggable.element.parents( ":not(body,html)" ).bind( "scroll.droppable", function() { + if( !draggable.options.refreshPositions ) $.ui.ddmanager.prepareOffsets( draggable, event ); + }); + }, + drag: function(draggable, event) { + + //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. + if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event); + + //Run through all droppables and check their positions based on specific tolerance options + $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { + + if(this.options.disabled || this.greedyChild || !this.visible) return; + var intersects = $.ui.intersect(draggable, this, this.options.tolerance); + + var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null); + if(!c) return; + + var parentInstance; + if (this.options.greedy) { + var parent = this.element.parents(':data(droppable):eq(0)'); + if (parent.length) { + parentInstance = $.data(parent[0], 'droppable'); + parentInstance.greedyChild = (c == 'isover' ? 1 : 0); + } + } + + // we just moved into a greedy child + if (parentInstance && c == 'isover') { + parentInstance['isover'] = 0; + parentInstance['isout'] = 1; + parentInstance._out.call(parentInstance, event); + } + + this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0; + this[c == "isover" ? "_over" : "_out"].call(this, event); + + // we just moved out of a greedy child + if (parentInstance && c == 'isout') { + parentInstance['isout'] = 0; + parentInstance['isover'] = 1; + parentInstance._over.call(parentInstance, event); + } + }); + + }, + dragStop: function( draggable, event ) { + draggable.element.parents( ":not(body,html)" ).unbind( "scroll.droppable" ); + //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) + if( !draggable.options.refreshPositions ) $.ui.ddmanager.prepareOffsets( draggable, event ); + } +}; + +})(jQuery); + +(function( $, undefined ) { + +$.widget("ui.resizable", $.ui.mouse, { + widgetEventPrefix: "resize", + options: { + alsoResize: false, + animate: false, + animateDuration: "slow", + animateEasing: "swing", + aspectRatio: false, + autoHide: false, + containment: false, + ghost: false, + grid: false, + handles: "e,s,se", + helper: false, + maxHeight: null, + maxWidth: null, + minHeight: 10, + minWidth: 10, + zIndex: 1000 + }, + _create: function() { + + var self = this, o = this.options; + this.element.addClass("ui-resizable"); + + $.extend(this, { + _aspectRatio: !!(o.aspectRatio), + aspectRatio: o.aspectRatio, + originalElement: this.element, + _proportionallyResizeElements: [], + _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null + }); + + //Wrap the element if it cannot hold child nodes + if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { + + //Create a wrapper element and set the wrapper to the new current internal element + this.element.wrap( + $('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({ + position: this.element.css('position'), + width: this.element.outerWidth(), + height: this.element.outerHeight(), + top: this.element.css('top'), + left: this.element.css('left') + }) + ); + + //Overwrite the original this.element + this.element = this.element.parent().data( + "resizable", this.element.data('resizable') + ); + + this.elementIsWrapper = true; + + //Move margins to the wrapper + this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); + this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); + + //Prevent Safari textarea resize + this.originalResizeStyle = this.originalElement.css('resize'); + this.originalElement.css('resize', 'none'); + + //Push the actual element to our proportionallyResize internal array + this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); + + // avoid IE jump (hard set the margin) + this.originalElement.css({ margin: this.originalElement.css('margin') }); + + // fix handlers offset + this._proportionallyResize(); + + } + + this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' }); + if(this.handles.constructor == String) { + + if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw'; + var n = this.handles.split(","); this.handles = {}; + + for(var i = 0; i < n.length; i++) { + + var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; + var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>'); + + // Apply zIndex to all handles - see #7960 + axis.css({ zIndex: o.zIndex }); + + //TODO : What's going on here? + if ('se' == handle) { + axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se'); + }; + + //Insert into internal handles object and append to element + this.handles[handle] = '.ui-resizable-'+handle; + this.element.append(axis); + } + + } + + this._renderAxis = function(target) { + + target = target || this.element; + + for(var i in this.handles) { + + if(this.handles[i].constructor == String) + this.handles[i] = $(this.handles[i], this.element).show(); + + //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) + if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { + + var axis = $(this.handles[i], this.element), padWrapper = 0; + + //Checking the correct pad and border + padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); + + //The padding type i have to apply... + var padPos = [ 'padding', + /ne|nw|n/.test(i) ? 'Top' : + /se|sw|s/.test(i) ? 'Bottom' : + /^e$/.test(i) ? 'Right' : 'Left' ].join(""); + + target.css(padPos, padWrapper); + + this._proportionallyResize(); + + } + + //TODO: What's that good for? There's not anything to be executed left + if(!$(this.handles[i]).length) + continue; + + } + }; + + //TODO: make renderAxis a prototype function + this._renderAxis(this.element); + + this._handles = $('.ui-resizable-handle', this.element) + .disableSelection(); + + //Matching axis name + this._handles.mouseover(function() { + if (!self.resizing) { + if (this.className) + var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); + //Axis, default = se + self.axis = axis && axis[1] ? axis[1] : 'se'; + } + }); + + //If we want to auto hide the elements + if (o.autoHide) { + this._handles.hide(); + $(this.element) + .addClass("ui-resizable-autohide") + .hover(function() { + if (o.disabled) return; + $(this).removeClass("ui-resizable-autohide"); + self._handles.show(); + }, + function(){ + if (o.disabled) return; + if (!self.resizing) { + $(this).addClass("ui-resizable-autohide"); + self._handles.hide(); + } + }); + } + + //Initialize the mouse interaction + this._mouseInit(); + + }, + + destroy: function() { + + this._mouseDestroy(); + + var _destroy = function(exp) { + $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") + .removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); + }; + + //TODO: Unwrap at same DOM position + if (this.elementIsWrapper) { + _destroy(this.element); + var wrapper = this.element; + wrapper.after( + this.originalElement.css({ + position: wrapper.css('position'), + width: wrapper.outerWidth(), + height: wrapper.outerHeight(), + top: wrapper.css('top'), + left: wrapper.css('left') + }) + ).remove(); + } + + this.originalElement.css('resize', this.originalResizeStyle); + _destroy(this.originalElement); + + return this; + }, + + _mouseCapture: function(event) { + var handle = false; + for (var i in this.handles) { + if ($(this.handles[i])[0] == event.target) { + handle = true; + } + } + + return !this.options.disabled && handle; + }, + + _mouseStart: function(event) { + + var o = this.options, iniPos = this.element.position(), el = this.element; + + this.resizing = true; + this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; + + // bugfix for http://dev.jquery.com/ticket/1749 + if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { + el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); + } + + this._renderProxy(); + + var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top')); + + if (o.containment) { + curleft += $(o.containment).scrollLeft() || 0; + curtop += $(o.containment).scrollTop() || 0; + } + + //Store needed variables + this.offset = this.helper.offset(); + this.position = { left: curleft, top: curtop }; + this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; + this.originalPosition = { left: curleft, top: curtop }; + this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; + this.originalMousePosition = { left: event.pageX, top: event.pageY }; + + //Aspect Ratio + this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); + + var cursor = $('.ui-resizable-' + this.axis).css('cursor'); + $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor); + + el.addClass("ui-resizable-resizing"); + this._propagate("start", event); + return true; + }, + + _mouseDrag: function(event) { + + //Increase performance, avoid regex + var el = this.helper, o = this.options, props = {}, + self = this, smp = this.originalMousePosition, a = this.axis; + + var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0; + var trigger = this._change[a]; + if (!trigger) return false; + + // Calculate the attrs that will be change + var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff; + + // Put this in the mouseDrag handler since the user can start pressing shift while resizing + this._updateVirtualBoundaries(event.shiftKey); + if (this._aspectRatio || event.shiftKey) + data = this._updateRatio(data, event); + + data = this._respectSize(data, event); + + // plugins callbacks need to be called first + this._propagate("resize", event); + + el.css({ + top: this.position.top + "px", left: this.position.left + "px", + width: this.size.width + "px", height: this.size.height + "px" + }); + + if (!this._helper && this._proportionallyResizeElements.length) + this._proportionallyResize(); + + this._updateCache(data); + + // calling the user callback at the end + this._trigger('resize', event, this.ui()); + + return false; + }, + + _mouseStop: function(event) { + + this.resizing = false; + var o = this.options, self = this; + + if(this._helper) { + var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var s = { width: (self.helper.width() - soffsetw), height: (self.helper.height() - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + if (!o.animate) + this.element.css($.extend(s, { top: top, left: left })); + + self.helper.height(self.size.height); + self.helper.width(self.size.width); + + if (this._helper && !o.animate) this._proportionallyResize(); + } + + $('body').css('cursor', 'auto'); + + this.element.removeClass("ui-resizable-resizing"); + + this._propagate("stop", event); + + if (this._helper) this.helper.remove(); + return false; + + }, + + _updateVirtualBoundaries: function(forceAspectRatio) { + var o = this.options, pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b; + + b = { + minWidth: isNumber(o.minWidth) ? o.minWidth : 0, + maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity, + minHeight: isNumber(o.minHeight) ? o.minHeight : 0, + maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity + }; + + if(this._aspectRatio || forceAspectRatio) { + // We want to create an enclosing box whose aspect ration is the requested one + // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension + pMinWidth = b.minHeight * this.aspectRatio; + pMinHeight = b.minWidth / this.aspectRatio; + pMaxWidth = b.maxHeight * this.aspectRatio; + pMaxHeight = b.maxWidth / this.aspectRatio; + + if(pMinWidth > b.minWidth) b.minWidth = pMinWidth; + if(pMinHeight > b.minHeight) b.minHeight = pMinHeight; + if(pMaxWidth < b.maxWidth) b.maxWidth = pMaxWidth; + if(pMaxHeight < b.maxHeight) b.maxHeight = pMaxHeight; + } + this._vBoundaries = b; + }, + + _updateCache: function(data) { + var o = this.options; + this.offset = this.helper.offset(); + if (isNumber(data.left)) this.position.left = data.left; + if (isNumber(data.top)) this.position.top = data.top; + if (isNumber(data.height)) this.size.height = data.height; + if (isNumber(data.width)) this.size.width = data.width; + }, + + _updateRatio: function(data, event) { + + var o = this.options, cpos = this.position, csize = this.size, a = this.axis; + + if (isNumber(data.height)) data.width = (data.height * this.aspectRatio); + else if (isNumber(data.width)) data.height = (data.width / this.aspectRatio); + + if (a == 'sw') { + data.left = cpos.left + (csize.width - data.width); + data.top = null; + } + if (a == 'nw') { + data.top = cpos.top + (csize.height - data.height); + data.left = cpos.left + (csize.width - data.width); + } + + return data; + }, + + _respectSize: function(data, event) { + + var el = this.helper, o = this._vBoundaries, pRatio = this._aspectRatio || event.shiftKey, a = this.axis, + ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), + isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height); + + if (isminw) data.width = o.minWidth; + if (isminh) data.height = o.minHeight; + if (ismaxw) data.width = o.maxWidth; + if (ismaxh) data.height = o.maxHeight; + + var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; + var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); + + if (isminw && cw) data.left = dw - o.minWidth; + if (ismaxw && cw) data.left = dw - o.maxWidth; + if (isminh && ch) data.top = dh - o.minHeight; + if (ismaxh && ch) data.top = dh - o.maxHeight; + + // fixing jump error on top/left - bug #2330 + var isNotwh = !data.width && !data.height; + if (isNotwh && !data.left && data.top) data.top = null; + else if (isNotwh && !data.top && data.left) data.left = null; + + return data; + }, + + _proportionallyResize: function() { + + var o = this.options; + if (!this._proportionallyResizeElements.length) return; + var element = this.helper || this.element; + + for (var i=0; i < this._proportionallyResizeElements.length; i++) { + + var prel = this._proportionallyResizeElements[i]; + + if (!this.borderDif) { + var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], + p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; + + this.borderDif = $.map(b, function(v, i) { + var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; + return border + padding; + }); + } + + if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length))) + continue; + + prel.css({ + height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, + width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 + }); + + }; + + }, + + _renderProxy: function() { + + var el = this.element, o = this.options; + this.elementOffset = el.offset(); + + if(this._helper) { + + this.helper = this.helper || $('<div style="overflow:hidden;"></div>'); + + // fix ie6 offset TODO: This seems broken + var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0), + pxyoffset = ( ie6 ? 2 : -1 ); + + this.helper.addClass(this._helper).css({ + width: this.element.outerWidth() + pxyoffset, + height: this.element.outerHeight() + pxyoffset, + position: 'absolute', + left: this.elementOffset.left - ie6offset +'px', + top: this.elementOffset.top - ie6offset +'px', + zIndex: ++o.zIndex //TODO: Don't modify option + }); + + this.helper + .appendTo("body") + .disableSelection(); + + } else { + this.helper = this.element; + } + + }, + + _change: { + e: function(event, dx, dy) { + return { width: this.originalSize.width + dx }; + }, + w: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { left: sp.left + dx, width: cs.width - dx }; + }, + n: function(event, dx, dy) { + var o = this.options, cs = this.originalSize, sp = this.originalPosition; + return { top: sp.top + dy, height: cs.height - dy }; + }, + s: function(event, dx, dy) { + return { height: this.originalSize.height + dy }; + }, + se: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + sw: function(event, dx, dy) { + return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + }, + ne: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); + }, + nw: function(event, dx, dy) { + return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); + } + }, + + _propagate: function(n, event) { + $.ui.plugin.call(this, n, [event, this.ui()]); + (n != "resize" && this._trigger(n, event, this.ui())); + }, + + plugins: {}, + + ui: function() { + return { + originalElement: this.originalElement, + element: this.element, + helper: this.helper, + position: this.position, + size: this.size, + originalSize: this.originalSize, + originalPosition: this.originalPosition + }; + } + +}); + +$.extend($.ui.resizable, { + version: "1.8.20" +}); + +/* + * Resizable Extensions + */ + +$.ui.plugin.add("resizable", "alsoResize", { + + start: function (event, ui) { + var self = $(this).data("resizable"), o = self.options; + + var _store = function (exp) { + $(exp).each(function() { + var el = $(this); + el.data("resizable-alsoresize", { + width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), + left: parseInt(el.css('left'), 10), top: parseInt(el.css('top'), 10) + }); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) { + if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } + else { $.each(o.alsoResize, function (exp) { _store(exp); }); } + }else{ + _store(o.alsoResize); + } + }, + + resize: function (event, ui) { + var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition; + + var delta = { + height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0, + top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0 + }, + + _alsoResize = function (exp, c) { + $(exp).each(function() { + var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, + css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ['width', 'height'] : ['width', 'height', 'top', 'left']; + + $.each(css, function (i, prop) { + var sum = (start[prop]||0) + (delta[prop]||0); + if (sum && sum >= 0) + style[prop] = sum || null; + }); + + el.css(style); + }); + }; + + if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { + $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); + }else{ + _alsoResize(o.alsoResize); + } + }, + + stop: function (event, ui) { + $(this).removeData("resizable-alsoresize"); + } +}); + +$.ui.plugin.add("resizable", "animate", { + + stop: function(event, ui) { + var self = $(this).data("resizable"), o = self.options; + + var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), + soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height, + soffsetw = ista ? 0 : self.sizeDiff.width; + + var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) }, + left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null, + top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null; + + self.element.animate( + $.extend(style, top && left ? { top: top, left: left } : {}), { + duration: o.animateDuration, + easing: o.animateEasing, + step: function() { + + var data = { + width: parseInt(self.element.css('width'), 10), + height: parseInt(self.element.css('height'), 10), + top: parseInt(self.element.css('top'), 10), + left: parseInt(self.element.css('left'), 10) + }; + + if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height }); + + // propagating resize, and updating values for each animation step + self._updateCache(data); + self._propagate("resize", event); + + } + } + ); + } + +}); + +$.ui.plugin.add("resizable", "containment", { + + start: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, el = self.element; + var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; + if (!ce) return; + + self.containerElement = $(ce); + + if (/document/.test(oc) || oc == document) { + self.containerOffset = { left: 0, top: 0 }; + self.containerPosition = { left: 0, top: 0 }; + + self.parentData = { + element: $(document), left: 0, top: 0, + width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight + }; + } + + // i'm a node, so compute top, left, right, bottom + else { + var element = $(ce), p = []; + $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); + + self.containerOffset = element.offset(); + self.containerPosition = element.position(); + self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; + + var co = self.containerOffset, ch = self.containerSize.height, cw = self.containerSize.width, + width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); + + self.parentData = { + element: ce, left: co.left, top: co.top, width: width, height: height + }; + } + }, + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, + ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position, + pRatio = self._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement; + + if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co; + + if (cp.left < (self._helper ? co.left : 0)) { + self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left)); + if (pRatio) self.size.height = self.size.width / self.aspectRatio; + self.position.left = o.helper ? co.left : 0; + } + + if (cp.top < (self._helper ? co.top : 0)) { + self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top); + if (pRatio) self.size.width = self.size.height * self.aspectRatio; + self.position.top = self._helper ? co.top : 0; + } + + self.offset.left = self.parentData.left+self.position.left; + self.offset.top = self.parentData.top+self.position.top; + + var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ), + hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height ); + + var isParent = self.containerElement.get(0) == self.element.parent().get(0), + isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position')); + + if(isParent && isOffsetRelative) woset -= self.parentData.left; + + if (woset + self.size.width >= self.parentData.width) { + self.size.width = self.parentData.width - woset; + if (pRatio) self.size.height = self.size.width / self.aspectRatio; + } + + if (hoset + self.size.height >= self.parentData.height) { + self.size.height = self.parentData.height - hoset; + if (pRatio) self.size.width = self.size.height * self.aspectRatio; + } + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options, cp = self.position, + co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement; + + var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height; + + if (self._helper && !o.animate && (/relative/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + if (self._helper && !o.animate && (/static/).test(ce.css('position'))) + $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); + + } +}); + +$.ui.plugin.add("resizable", "ghost", { + + start: function(event, ui) { + + var self = $(this).data("resizable"), o = self.options, cs = self.size; + + self.ghost = self.originalElement.clone(); + self.ghost + .css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) + .addClass('ui-resizable-ghost') + .addClass(typeof o.ghost == 'string' ? o.ghost : ''); + + self.ghost.appendTo(self.helper); + + }, + + resize: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width }); + }, + + stop: function(event, ui){ + var self = $(this).data("resizable"), o = self.options; + if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0)); + } + +}); + +$.ui.plugin.add("resizable", "grid", { + + resize: function(event, ui) { + var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey; + o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; + var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); + + if (/^(se|s|e)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + } + else if (/^(ne)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + } + else if (/^(sw)$/.test(a)) { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.left = op.left - ox; + } + else { + self.size.width = os.width + ox; + self.size.height = os.height + oy; + self.position.top = op.top - oy; + self.position.left = op.left - ox; + } + } + +}); + +var num = function(v) { + return parseInt(v, 10) || 0; +}; + +var isNumber = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.widget("ui.selectable", $.ui.mouse, { + options: { + appendTo: 'body', + autoRefresh: true, + distance: 0, + filter: '*', + tolerance: 'touch' + }, + _create: function() { + var self = this; + + this.element.addClass("ui-selectable"); + + this.dragged = false; + + // cache selectee children based on filter + var selectees; + this.refresh = function() { + selectees = $(self.options.filter, self.element[0]); + selectees.addClass("ui-selectee"); + selectees.each(function() { + var $this = $(this); + var pos = $this.offset(); + $.data(this, "selectable-item", { + element: this, + $element: $this, + left: pos.left, + top: pos.top, + right: pos.left + $this.outerWidth(), + bottom: pos.top + $this.outerHeight(), + startselected: false, + selected: $this.hasClass('ui-selected'), + selecting: $this.hasClass('ui-selecting'), + unselecting: $this.hasClass('ui-unselecting') + }); + }); + }; + this.refresh(); + + this.selectees = selectees.addClass("ui-selectee"); + + this._mouseInit(); + + this.helper = $("<div class='ui-selectable-helper'></div>"); + }, + + destroy: function() { + this.selectees + .removeClass("ui-selectee") + .removeData("selectable-item"); + this.element + .removeClass("ui-selectable ui-selectable-disabled") + .removeData("selectable") + .unbind(".selectable"); + this._mouseDestroy(); + + return this; + }, + + _mouseStart: function(event) { + var self = this; + + this.opos = [event.pageX, event.pageY]; + + if (this.options.disabled) + return; + + var options = this.options; + + this.selectees = $(options.filter, this.element[0]); + + this._trigger("start", event); + + $(options.appendTo).append(this.helper); + // position helper (lasso) + this.helper.css({ + "left": event.clientX, + "top": event.clientY, + "width": 0, + "height": 0 + }); + + if (options.autoRefresh) { + this.refresh(); + } + + this.selectees.filter('.ui-selected').each(function() { + var selectee = $.data(this, "selectable-item"); + selectee.startselected = true; + if (!event.metaKey && !event.ctrlKey) { + selectee.$element.removeClass('ui-selected'); + selectee.selected = false; + selectee.$element.addClass('ui-unselecting'); + selectee.unselecting = true; + // selectable UNSELECTING callback + self._trigger("unselecting", event, { + unselecting: selectee.element + }); + } + }); + + $(event.target).parents().andSelf().each(function() { + var selectee = $.data(this, "selectable-item"); + if (selectee) { + var doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass('ui-selected'); + selectee.$element + .removeClass(doSelect ? "ui-unselecting" : "ui-selected") + .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); + selectee.unselecting = !doSelect; + selectee.selecting = doSelect; + selectee.selected = doSelect; + // selectable (UN)SELECTING callback + if (doSelect) { + self._trigger("selecting", event, { + selecting: selectee.element + }); + } else { + self._trigger("unselecting", event, { + unselecting: selectee.element + }); + } + return false; + } + }); + + }, + + _mouseDrag: function(event) { + var self = this; + this.dragged = true; + + if (this.options.disabled) + return; + + var options = this.options; + + var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; + if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; } + if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; } + this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1}); + + this.selectees.each(function() { + var selectee = $.data(this, "selectable-item"); + //prevent helper from being selected if appendTo: selectable + if (!selectee || selectee.element == self.element[0]) + return; + var hit = false; + if (options.tolerance == 'touch') { + hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); + } else if (options.tolerance == 'fit') { + hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); + } + + if (hit) { + // SELECT + if (selectee.selected) { + selectee.$element.removeClass('ui-selected'); + selectee.selected = false; + } + if (selectee.unselecting) { + selectee.$element.removeClass('ui-unselecting'); + selectee.unselecting = false; + } + if (!selectee.selecting) { + selectee.$element.addClass('ui-selecting'); + selectee.selecting = true; + // selectable SELECTING callback + self._trigger("selecting", event, { + selecting: selectee.element + }); + } + } else { + // UNSELECT + if (selectee.selecting) { + if ((event.metaKey || event.ctrlKey) && selectee.startselected) { + selectee.$element.removeClass('ui-selecting'); + selectee.selecting = false; + selectee.$element.addClass('ui-selected'); + selectee.selected = true; + } else { + selectee.$element.removeClass('ui-selecting'); + selectee.selecting = false; + if (selectee.startselected) { + selectee.$element.addClass('ui-unselecting'); + selectee.unselecting = true; + } + // selectable UNSELECTING callback + self._trigger("unselecting", event, { + unselecting: selectee.element + }); + } + } + if (selectee.selected) { + if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { + selectee.$element.removeClass('ui-selected'); + selectee.selected = false; + + selectee.$element.addClass('ui-unselecting'); + selectee.unselecting = true; + // selectable UNSELECTING callback + self._trigger("unselecting", event, { + unselecting: selectee.element + }); + } + } + } + }); + + return false; + }, + + _mouseStop: function(event) { + var self = this; + + this.dragged = false; + + var options = this.options; + + $('.ui-unselecting', this.element[0]).each(function() { + var selectee = $.data(this, "selectable-item"); + selectee.$element.removeClass('ui-unselecting'); + selectee.unselecting = false; + selectee.startselected = false; + self._trigger("unselected", event, { + unselected: selectee.element + }); + }); + $('.ui-selecting', this.element[0]).each(function() { + var selectee = $.data(this, "selectable-item"); + selectee.$element.removeClass('ui-selecting').addClass('ui-selected'); + selectee.selecting = false; + selectee.selected = true; + selectee.startselected = true; + self._trigger("selected", event, { + selected: selectee.element + }); + }); + this._trigger("stop", event); + + this.helper.remove(); + + return false; + } + +}); + +$.extend($.ui.selectable, { + version: "1.8.20" +}); + +})(jQuery); + +(function( $, undefined ) { + +$.widget("ui.sortable", $.ui.mouse, { + widgetEventPrefix: "sort", + ready: false, + options: { + appendTo: "parent", + axis: false, + connectWith: false, + containment: false, + cursor: 'auto', + cursorAt: false, + dropOnEmpty: true, + forcePlaceholderSize: false, + forceHelperSize: false, + grid: false, + handle: false, + helper: "original", + items: '> *', + opacity: false, + placeholder: false, + revert: false, + scroll: true, + scrollSensitivity: 20, + scrollSpeed: 20, + scope: "default", + tolerance: "intersect", + zIndex: 1000 + }, + _create: function() { + + var o = this.options; + this.containerCache = {}; + this.element.addClass("ui-sortable"); + + //Get the items + this.refresh(); + + //Let's determine if the items are being displayed horizontally + this.floating = this.items.length ? o.axis === 'x' || (/left|right/).test(this.items[0].item.css('float')) || (/inline|table-cell/).test(this.items[0].item.css('display')) : false; + + //Let's determine the parent's offset + this.offset = this.element.offset(); + + //Initialize mouse events for interaction + this._mouseInit(); + + //We're ready to go + this.ready = true + + }, + + destroy: function() { + $.Widget.prototype.destroy.call( this ); + this.element + .removeClass("ui-sortable ui-sortable-disabled"); + this._mouseDestroy(); + + for ( var i = this.items.length - 1; i >= 0; i-- ) + this.items[i].item.removeData(this.widgetName + "-item"); + + return this; + }, + + _setOption: function(key, value){ + if ( key === "disabled" ) { + this.options[ key ] = value; + + this.widget() + [ value ? "addClass" : "removeClass"]( "ui-sortable-disabled" ); + } else { + // Don't call widget base _setOption for disable as it adds ui-state-disabled class + $.Widget.prototype._setOption.apply(this, arguments); + } + }, + + _mouseCapture: function(event, overrideHandle) { + var that = this; + + if (this.reverting) { + return false; + } + + if(this.options.disabled || this.options.type == 'static') return false; + + //We have to refresh the items data once first + this._refreshItems(event); + + //Find out if the clicked node (or one of its parents) is a actual item in this.items + var currentItem = null, self = this, nodes = $(event.target).parents().each(function() { + if($.data(this, that.widgetName + '-item') == self) { + currentItem = $(this); + return false; + } + }); + if($.data(event.target, that.widgetName + '-item') == self) currentItem = $(event.target); + + if(!currentItem) return false; + if(this.options.handle && !overrideHandle) { + var validHandle = false; + + $(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; }); + if(!validHandle) return false; + } + + this.currentItem = currentItem; + this._removeCurrentsFromItems(); + return true; + + }, + + _mouseStart: function(event, overrideHandle, noActivation) { + + var o = this.options, self = this; + this.currentContainer = this; + + //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture + this.refreshPositions(); + + //Create and append the visible helper + this.helper = this._createHelper(event); + + //Cache the helper size + this._cacheHelperProportions(); + + /* + * - Position generation - + * This block generates everything position related - it's the core of draggables. + */ + + //Cache the margins of the original element + this._cacheMargins(); + + //Get the next scrolling parent + this.scrollParent = this.helper.scrollParent(); + + //The element's absolute position on the page minus margins + this.offset = this.currentItem.offset(); + this.offset = { + top: this.offset.top - this.margins.top, + left: this.offset.left - this.margins.left + }; + + // Only after we got the offset, we can change the helper's position to absolute + // TODO: Still need to figure out a way to make relative sorting possible + this.helper.css("position", "absolute"); + this.cssPosition = this.helper.css("position"); + + $.extend(this.offset, { + click: { //Where the click happened, relative to the element + left: event.pageX - this.offset.left, + top: event.pageY - this.offset.top + }, + parent: this._getParentOffset(), + relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper + }); + + //Generate the original position + this.originalPosition = this._generatePosition(event); + this.originalPageX = event.pageX; + this.originalPageY = event.pageY; + + //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied + (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); + + //Cache the former DOM position + this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; + + //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way + if(this.helper[0] != this.currentItem[0]) { + this.currentItem.hide(); + } + + //Create the placeholder + this._createPlaceholder(); + + //Set a containment if given in the options + if(o.containment) + this._setContainment(); + + if(o.cursor) { // cursor option + if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor"); + $('body').css("cursor", o.cursor); + } + + if(o.opacity) { // opacity option + if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity"); + this.helper.css("opacity", o.opacity); + } + + if(o.zIndex) { // zIndex option + if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex"); + this.helper.css("zIndex", o.zIndex); + } + + //Prepare scrolling + if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') + this.overflowOffset = this.scrollParent.offset(); + + //Call callbacks + this._trigger("start", event, this._uiHash()); + + //Recache the helper size + if(!this._preserveHelperProportions) + this._cacheHelperProportions(); + + + //Post 'activate' events to possible containers + if(!noActivation) { + for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); } + } + + //Prepare possible droppables + if($.ui.ddmanager) + $.ui.ddmanager.current = this; + + if ($.ui.ddmanager && !o.dropBehaviour) + $.ui.ddmanager.prepareOffsets(this, event); + + this.dragging = true; + + this.helper.addClass("ui-sortable-helper"); + this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position + return true; + + }, + + _mouseDrag: function(event) { + + //Compute the helpers position + this.position = this._generatePosition(event); + this.positionAbs = this._convertPositionTo("absolute"); + + if (!this.lastPositionAbs) { + this.lastPositionAbs = this.positionAbs; + } + + //Do scrolling + if(this.options.scroll) { + var o = this.options, scrolled = false; + if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') { + + if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) + this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; + else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) + this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; + + if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) + this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; + else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) + this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; + + } else { + + if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) + scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); + else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) + scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); + + if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) + scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); + else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) + scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); + + } + + if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) + $.ui.ddmanager.prepareOffsets(this, event); + } + + //Regenerate the absolute position used for position checks + this.positionAbs = this._convertPositionTo("absolute"); + + //Set the helper position + if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px'; + if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px'; + + //Rearrange + for (var i = this.items.length - 1; i >= 0; i--) { + + //Cache variables and intersection, continue if no intersection + var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item); + if (!intersection) continue; + + if(itemElement != this.currentItem[0] //cannot intersect with itself + && this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before + && !$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked + && (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true) + //&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container + ) { + + this.direction = intersection == 1 ? "down" : "up"; + + if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) { + this._rearrange(event, item); + } else { + break; + } + + this._trigger("change", event, this._uiHash()); + break; + } + } + + //Post events to containers + this._contactContainers(event); + + //Interconnect with droppables + if($.ui.ddmanager) $.ui.ddmanager.drag(this, event); + + //Call callbacks + this._trigger('sort', event, this._uiHash()); + + this.lastPositionAbs = this.positionAbs; + return false; + + }, + + _mouseStop: function(event, noPropagation) { + + if(!event) return; + + //If we are using droppables, inform the manager about the drop + if ($.ui.ddmanager && !this.options.dropBehaviour) + $.ui.ddmanager.drop(this, event); + + if(this.options.revert) { + var self = this; + var cur = self.placeholder.offset(); + + self.reverting = true; + + $(this.helper).animate({ + left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft), + top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop) + }, parseInt(this.options.revert, 10) || 500, function() { + self._clear(event); + }); + } else { + this._clear(event, noPropagation); + } + + return false; + + }, + + cancel: function() { + + var self = this; + + if(this.dragging) { + + this._mouseUp({ target: null }); + + if(this.options.helper == "original") + this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); + else + this.currentItem.show(); + + //Post deactivating events to containers + for (var i = this.containers.length - 1; i >= 0; i--){ + this.containers[i]._trigger("deactivate", null, self._uiHash(this)); + if(this.containers[i].containerCache.over) { + this.containers[i]._trigger("out", null, self._uiHash(this)); + this.containers[i].containerCache.over = 0; + } + } + + } + + if (this.placeholder) { + //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! + if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]); + if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove(); + + $.extend(this, { + helper: null, + dragging: false, + reverting: false, + _noFinalSort: null + }); + + if(this.domPosition.prev) { + $(this.domPosition.prev).after(this.currentItem); + } else { + $(this.domPosition.parent).prepend(this.currentItem); + } + } + + return this; + + }, + + serialize: function(o) { + + var items = this._getItemsAsjQuery(o && o.connected); + var str = []; o = o || {}; + + $(items).each(function() { + var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/)); + if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2])); + }); + + if(!str.length && o.key) { + str.push(o.key + '='); + } + + return str.join('&'); + + }, + + toArray: function(o) { + + var items = this._getItemsAsjQuery(o && o.connected); + var ret = []; o = o || {}; + + items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); }); + return ret; + + }, + + /* Be careful with the following core functions */ + _intersectsWith: function(item) { + + var x1 = this.positionAbs.left, + x2 = x1 + this.helperProportions.width, + y1 = this.positionAbs.top, + y2 = y1 + this.helperProportions.height; + + var l = item.left, + r = l + item.width, + t = item.top, + b = t + item.height; + + var dyClick = this.offset.click.top, + dxClick = this.offset.click.left; + + var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r; + + if( this.options.tolerance == "pointer" + || this.options.forcePointerForContainers + || (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height']) + ) { + return isOverElement; + } else { + + return (l < x1 + (this.helperProportions.width / 2) // Right Half + && x2 - (this.helperProportions.width / 2) < r // Left Half + && t < y1 + (this.helperProportions.height / 2) // Bottom Half + && y2 - (this.helperProportions.height / 2) < b ); // Top Half + + } + }, + + _intersectsWithPointer: function(item) { + + var isOverElementHeight = (this.options.axis === 'x') || $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), + isOverElementWidth = (this.options.axis === 'y') || $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), + isOverElement = isOverElementHeight && isOverElementWidth, + verticalDirection = this._getDragVerticalDirection(), + horizontalDirection = this._getDragHorizontalDirection(); + + if (!isOverElement) + return false; + + return this.floating ? + ( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 ) + : ( verticalDirection && (verticalDirection == "down" ? 2 : 1) ); + + }, + + _intersectsWithSides: function(item) { + + var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), + isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), + verticalDirection = this._getDragVerticalDirection(), + horizontalDirection = this._getDragHorizontalDirection(); + + if (this.floating && horizontalDirection) { + return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf)); + } else { + return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf)); + } + + }, + + _getDragVerticalDirection: function() { + var delta = this.positionAbs.top - this.lastPositionAbs.top; + return delta != 0 && (delta > 0 ? "down" : "up"); + }, + + _getDragHorizontalDirection: function() { + var delta = this.positionAbs.left - this.lastPositionAbs.left; + return delta != 0 && (delta > 0 ? "right" : "left"); + }, + + refresh: function(event) { + this._refreshItems(event); + this.refreshPositions(); + return this; + }, + + _connectWith: function() { + var options = this.options; + return options.connectWith.constructor == String + ? [options.connectWith] + : options.connectWith; + }, + + _getItemsAsjQuery: function(connected) { + + var self = this; + var items = []; + var queries = []; + var connectWith = this._connectWith(); + + if(connectWith && connected) { + for (var i = connectWith.length - 1; i >= 0; i--){ + var cur = $(connectWith[i]); + for (var j = cur.length - 1; j >= 0; j--){ + var inst = $.data(cur[j], this.widgetName); + if(inst && inst != this && !inst.options.disabled) { + queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), inst]); + } + }; + }; + } + + queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), this]); + + for (var i = queries.length - 1; i >= 0; i--){ + queries[i][0].each(function() { + items.push(this); + }); + }; + + return $(items); + + }, + + _removeCurrentsFromItems: function() { + + var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); + + for (var i=0; i < this.items.length; i++) { + + for (var j=0; j < list.length; j++) { + if(list[j] == this.items[i].item[0]) + this.items.splice(i,1); + }; + + }; + + }, + + _refreshItems: function(event) { + + this.items = []; + this.containers = [this]; + var items = this.items; + var self = this; + var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]]; + var connectWith = this._connectWith(); + + if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down + for (var i = connectWith.length - 1; i >= 0; i--){ + var cur = $(connectWith[i]); + for (var j = cur.length - 1; j >= 0; j--){ + var inst = $.data(cur[j], this.widgetName); + if(inst && inst != this && !inst.options.disabled) { + queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); + this.containers.push(inst); + } + }; + }; + } + + for (var i = queries.length - 1; i >= 0; i--) { + var targetData = queries[i][1]; + var _queries = queries[i][0]; + + for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) { + var item = $(_queries[j]); + + item.data(this.widgetName + '-item', targetData); // Data for target checking (mouse manager) + + items.push({ + item: item, + instance: targetData, + width: 0, height: 0, + left: 0, top: 0 + }); + }; + }; + + }, + + refreshPositions: function(fast) { + + //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change + if(this.offsetParent && this.helper) { + this.offset.parent = this._getParentOffset(); + } + + for (var i = this.items.length - 1; i >= 0; i--){ + var item = this.items[i]; + + //We ignore calculating positions of all connected containers when we're not over them + if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0]) + continue; + + var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; + + if (!fast) { + item.width = t.outerWidth(); + item.height = t.outerHeight(); + } + + var p = t.offset(); + item.left = p.left; + item.top = p.top; + }; + + if(this.options.custom && this.options.custom.refreshContainers) { + this.options.custom.refreshContainers.call(this); + } else { + for (var i = this.containers.length - 1; i >= 0; i--){ + var p = this.containers[i].element.offset(); + this.containers[i].containerCache.left = p.left; + this.containers[i].containerCache.top = p.top; + this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); + this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); + }; + } + + return this; + }, + + _createPlaceholder: function(that) { + + var self = that || this, o = self.options; + + if(!o.placeholder || o.placeholder.constructor == String) { + var className = o.placeholder; + o.placeholder = { + element: function() { + + var el = $(document.createElement(self.currentItem[0].nodeName)) + .addClass(className || self.currentItem[0].className+" ui-sortable-placeholder") + .removeClass("ui-sortable-helper")[0]; + + if(!className) + el.style.visibility = "hidden"; + + return el; + }, + update: function(container, p) { + + // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that + // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified + if(className && !o.forcePlaceholderSize) return; + + //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item + if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); }; + if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); }; + } + }; + } + + //Create the placeholder + self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem)); + + //Append it after the actual current item + self.currentItem.after(self.placeholder); + + //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) + o.placeholder.update(self, self.placeholder); + + }, + + _contactContainers: function(event) { + + // get innermost container that intersects with item + var innermostContainer = null, innermostIndex = null; + + + for (var i = this.containers.length - 1; i >= 0; i--){ + + // never consider a container that's located within the item itself + if($.ui.contains(this.currentItem[0], this.containers[i].element[0])) + continue; + + if(this._intersectsWith(this.containers[i].containerCache)) { + + // if we've already found a container and it's more "inner" than this, then continue + if(innermostContainer && $.ui.contains(this.containers[i].element[0], innermostContainer.element[0])) + continue; + + innermostContainer = this.containers[i]; + innermostIndex = i; + + } else { + // container doesn't intersect. trigger "out" event if necessary + if(this.containers[i].containerCache.over) { + this.containers[i]._trigger("out", event, this._uiHash(this)); + this.containers[i].containerCache.over = 0; + } + } + + } + + // if no intersecting containers found, return + if(!innermostContainer) return; + + // move the item into the container if it's not there already + if(this.containers.length === 1) { + this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); + this.containers[innermostIndex].containerCache.over = 1; + } else if(this.currentContainer != this.containers[innermostIndex]) { + + //When entering a new container, we will find the item with the least distance and append our item near it + var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[innermostIndex].floating ? 'left' : 'top']; + for (var j = this.items.length - 1; j >= 0; j--) { + if(!$.ui.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) continue; + var cur = this.items[j][this.containers[innermostIndex].floating ? 'left' : 'top']; + if(Math.abs(cur - base) < dist) { + dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; + } + } + + if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled + return; + + this.currentContainer = this.containers[innermostIndex]; + itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); + this._trigger("change", event, this._uiHash()); + this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); + + //Update the placeholder + this.options.placeholder.update(this.currentContainer, this.placeholder); + + this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); + this.containers[innermostIndex].containerCache.over = 1; + } + + + }, + + _createHelper: function(event) { + + var o = this.options; + var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem); + + if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already + $(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); + + if(helper[0] == this.currentItem[0]) + this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; + + if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width()); + if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height()); + + return helper; + + }, + + _adjustOffsetFromHelper: function(obj) { + if (typeof obj == 'string') { + obj = obj.split(' '); + } + if ($.isArray(obj)) { + obj = {left: +obj[0], top: +obj[1] || 0}; + } + if ('left' in obj) { + this.offset.click.left = obj.left + this.margins.left; + } + if ('right' in obj) { + this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; + } + if ('top' in obj) { + this.offset.click.top = obj.top + this.margins.top; + } + if ('bottom' in obj) { + this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; + } + }, + + _getParentOffset: function() { + + + //Get the offsetParent and cache its position + this.offsetParent = this.helper.offsetParent(); + var po = this.offsetParent.offset(); + + // This is a special case where we need to modify a offset calculated on start, since the following happened: + // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent + // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that + // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag + if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) { + po.left += this.scrollParent.scrollLeft(); + po.top += this.scrollParent.scrollTop(); + } + + if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information + || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix + po = { top: 0, left: 0 }; + + return { + top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), + left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) + }; + + }, + + _getRelativeOffset: function() { + + if(this.cssPosition == "relative") { + var p = this.currentItem.position(); + return { + top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), + left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() + }; + } else { + return { top: 0, left: 0 }; + } + + }, + + _cacheMargins: function() { + this.margins = { + left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), + top: (parseInt(this.currentItem.css("marginTop"),10) || 0) + }; + }, + + _cacheHelperProportions: function() { + this.helperProportions = { + width: this.helper.outerWidth(), + height: this.helper.outerHeight() + }; + }, + + _setContainment: function() { + + var o = this.options; + if(o.containment == 'parent') o.containment = this.helper[0].parentNode; + if(o.containment == 'document' || o.containment == 'window') this.containment = [ + 0 - this.offset.relative.left - this.offset.parent.left, + 0 - this.offset.relative.top - this.offset.parent.top, + $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left, + ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top + ]; + + if(!(/^(document|window|parent)$/).test(o.containment)) { + var ce = $(o.containment)[0]; + var co = $(o.containment).offset(); + var over = ($(ce).css("overflow") != 'hidden'); + + this.containment = [ + co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, + co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, + co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, + co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top + ]; + } + + }, + + _convertPositionTo: function(d, pos) { + + if(!pos) pos = this.position; + var mod = d == "absolute" ? 1 : -1; + var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); + + return { + top: ( + pos.top // The absolute mouse position + + this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent + + this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border) + - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) + ), + left: ( + pos.left // The absolute mouse position + + this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent + + this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border) + - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) + ) + }; + + }, + + _generatePosition: function(event) { + + var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); + + // This is another very weird special case that only happens for relative elements: + // 1. If the css position is relative + // 2. and the scroll parent is the document or similar to the offset parent + // we have to refresh the relative offset during the scroll so there are no jumps + if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) { + this.offset.relative = this._getRelativeOffset(); + } + + var pageX = event.pageX; + var pageY = event.pageY; + + /* + * - Position constraining - + * Constrain the position to a mix of grid, containment. + */ + + if(this.originalPosition) { //If we are not dragging yet, we won't check for options + + if(this.containment) { + if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left; + if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top; + if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left; + if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top; + } + + if(o.grid) { + var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; + pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; + + var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; + pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; + } + + } + + return { + top: ( + pageY // The absolute mouse position + - this.offset.click.top // Click offset (relative to the element) + - this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent + - this.offset.parent.top // The offsetParent's offset without borders (offset + border) + + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) + ), + left: ( + pageX // The absolute mouse position + - this.offset.click.left // Click offset (relative to the element) + - this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent + - this.offset.parent.left // The offsetParent's offset without borders (offset + border) + + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) + ) + }; + + }, + + _rearrange: function(event, i, a, hardRefresh) { + + a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling)); + + //Various things done here to improve the performance: + // 1. we create a setTimeout, that calls refreshPositions + // 2. on the instance, we have a counter variable, that get's higher after every append + // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same + // 4. this lets only the last addition to the timeout stack through + this.counter = this.counter ? ++this.counter : 1; + var self = this, counter = this.counter; + + window.setTimeout(function() { + if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove + },0); + + }, + + _clear: function(event, noPropagation) { + + this.reverting = false; + // We delay all events that have to be triggered to after the point where the placeholder has been removed and + // everything else normalized again + var delayedTriggers = [], self = this; + + // We first have to update the dom position of the actual currentItem + // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) + if(!this._noFinalSort && this.currentItem.parent().length) this.placeholder.before(this.currentItem); + this._noFinalSort = null; + + if(this.helper[0] == this.currentItem[0]) { + for(var i in this._storedCSS) { + if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = ''; + } + this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); + } else { + this.currentItem.show(); + } + + if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); + if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed + if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element + if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); + for (var i = this.containers.length - 1; i >= 0; i--){ + if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) { + delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.containers[i])); + delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.containers[i])); + } + }; + }; + + //Post events to containers + for (var i = this.containers.length - 1; i >= 0; i--){ + if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); + if(this.containers[i].containerCache.over) { + delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i])); + this.containers[i].containerCache.over = 0; + } + } + + //Do what was originally in plugins + if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor + if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity + if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index + + this.dragging = false; + if(this.cancelHelperRemoval) { + if(!noPropagation) { + this._trigger("beforeStop", event, this._uiHash()); + for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events + this._trigger("stop", event, this._uiHash()); + } + return false; + } + + if(!noPropagation) this._trigger("beforeStop", event, this._uiHash()); + + //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! + this.placeholder[0].parentNode.removeChild(this.placeholder[0]); + + if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null; + + if(!noPropagation) { + for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events + this._trigger("stop", event, this._uiHash()); + } + + this.fromOutside = false; + return true; + + }, + + _trigger: function() { + if ($.Widget.prototype._trigger.apply(this, arguments) === false) { + this.cancel(); + } + }, + + _uiHash: function(inst) { + var self = inst || this; + return { + helper: self.helper, + placeholder: self.placeholder || $([]), + position: self.position, + originalPosition: self.originalPosition, + offset: self.positionAbs, + item: self.currentItem, + sender: inst ? inst.element : null + }; + } + +}); + +$.extend($.ui.sortable, { + version: "1.8.20" +}); + +})(jQuery); + +;jQuery.effects || (function($, undefined) { + +$.effects = {}; + + + +/******************************************************************************/ +/****************************** COLOR ANIMATIONS ******************************/ +/******************************************************************************/ + +// override the animation for color styles +$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', + 'borderRightColor', 'borderTopColor', 'borderColor', 'color', 'outlineColor'], +function(i, attr) { + $.fx.step[attr] = function(fx) { + if (!fx.colorInit) { + fx.start = getColor(fx.elem, attr); + fx.end = getRGB(fx.end); + fx.colorInit = true; + } + + fx.elem.style[attr] = 'rgb(' + + Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0) + ',' + + Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0) + ',' + + Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0) + ')'; + }; +}); + +// Color Conversion functions from highlightFade +// By Blair Mitchelmore +// http://jquery.offput.ca/highlightFade/ + +// Parse strings looking for color tuples [255,255,255] +function getRGB(color) { + var result; + + // Check if we're already dealing with an array of colors + if ( color && color.constructor == Array && color.length == 3 ) + return color; + + // Look for rgb(num,num,num) + if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) + return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)]; + + // Look for rgb(num%,num%,num%) + if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) + return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; + + // Look for #a0b1c2 + if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) + return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; + + // Look for #fff + if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) + return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; + + // Look for rgba(0, 0, 0, 0) == transparent in Safari 3 + if (result = /rgba\(0, 0, 0, 0\)/.exec(color)) + return colors['transparent']; + + // Otherwise, we're most likely dealing with a named color + return colors[$.trim(color).toLowerCase()]; +} + +function getColor(elem, attr) { + var color; + + do { + color = $.curCSS(elem, attr); + + // Keep going until we find an element that has color, or we hit the body + if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") ) + break; + + attr = "backgroundColor"; + } while ( elem = elem.parentNode ); + + return getRGB(color); +}; + +// Some named colors to work with +// From Interface by Stefan Petre +// http://interface.eyecon.ro/ + +var colors = { + aqua:[0,255,255], + azure:[240,255,255], + beige:[245,245,220], + black:[0,0,0], + blue:[0,0,255], + brown:[165,42,42], + cyan:[0,255,255], + darkblue:[0,0,139], + darkcyan:[0,139,139], + darkgrey:[169,169,169], + darkgreen:[0,100,0], + darkkhaki:[189,183,107], + darkmagenta:[139,0,139], + darkolivegreen:[85,107,47], + darkorange:[255,140,0], + darkorchid:[153,50,204], + darkred:[139,0,0], + darksalmon:[233,150,122], + darkviolet:[148,0,211], + fuchsia:[255,0,255], + gold:[255,215,0], + green:[0,128,0], + indigo:[75,0,130], + khaki:[240,230,140], + lightblue:[173,216,230], + lightcyan:[224,255,255], + lightgreen:[144,238,144], + lightgrey:[211,211,211], + lightpink:[255,182,193], + lightyellow:[255,255,224], + lime:[0,255,0], + magenta:[255,0,255], + maroon:[128,0,0], + navy:[0,0,128], + olive:[128,128,0], + orange:[255,165,0], + pink:[255,192,203], + purple:[128,0,128], + violet:[128,0,128], + red:[255,0,0], + silver:[192,192,192], + white:[255,255,255], + yellow:[255,255,0], + transparent: [255,255,255] +}; + + + +/******************************************************************************/ +/****************************** CLASS ANIMATIONS ******************************/ +/******************************************************************************/ + +var classAnimationActions = ['add', 'remove', 'toggle'], + shorthandStyles = { + border: 1, + borderBottom: 1, + borderColor: 1, + borderLeft: 1, + borderRight: 1, + borderTop: 1, + borderWidth: 1, + margin: 1, + padding: 1 + }; + +function getElementStyles() { + var style = document.defaultView + ? document.defaultView.getComputedStyle(this, null) + : this.currentStyle, + newStyle = {}, + key, + camelCase; + + // webkit enumerates style porperties + if (style && style.length && style[0] && style[style[0]]) { + var len = style.length; + while (len--) { + key = style[len]; + if (typeof style[key] == 'string') { + camelCase = key.replace(/\-(\w)/g, function(all, letter){ + return letter.toUpperCase(); + }); + newStyle[camelCase] = style[key]; + } + } + } else { + for (key in style) { + if (typeof style[key] === 'string') { + newStyle[key] = style[key]; + } + } + } + + return newStyle; +} + +function filterStyles(styles) { + var name, value; + for (name in styles) { + value = styles[name]; + if ( + // ignore null and undefined values + value == null || + // ignore functions (when does this occur?) + $.isFunction(value) || + // shorthand styles that need to be expanded + name in shorthandStyles || + // ignore scrollbars (break in IE) + (/scrollbar/).test(name) || + + // only colors or values that can be converted to numbers + (!(/color/i).test(name) && isNaN(parseFloat(value))) + ) { + delete styles[name]; + } + } + + return styles; +} + +function styleDifference(oldStyle, newStyle) { + var diff = { _: 0 }, // http://dev.jquery.com/ticket/5459 + name; + + for (name in newStyle) { + if (oldStyle[name] != newStyle[name]) { + diff[name] = newStyle[name]; + } + } + + return diff; +} + +$.effects.animateClass = function(value, duration, easing, callback) { + if ($.isFunction(easing)) { + callback = easing; + easing = null; + } + + return this.queue(function() { + var that = $(this), + originalStyleAttr = that.attr('style') || ' ', + originalStyle = filterStyles(getElementStyles.call(this)), + newStyle, + className = that.attr('class') || ""; + + $.each(classAnimationActions, function(i, action) { + if (value[action]) { + that[action + 'Class'](value[action]); + } + }); + newStyle = filterStyles(getElementStyles.call(this)); + that.attr('class', className); + + that.animate(styleDifference(originalStyle, newStyle), { + queue: false, + duration: duration, + easing: easing, + complete: function() { + $.each(classAnimationActions, function(i, action) { + if (value[action]) { that[action + 'Class'](value[action]); } + }); + // work around bug in IE by clearing the cssText before setting it + if (typeof that.attr('style') == 'object') { + that.attr('style').cssText = ''; + that.attr('style').cssText = originalStyleAttr; + } else { + that.attr('style', originalStyleAttr); + } + if (callback) { callback.apply(this, arguments); } + $.dequeue( this ); + } + }); + }); +}; + +$.fn.extend({ + _addClass: $.fn.addClass, + addClass: function(classNames, speed, easing, callback) { + return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames); + }, + + _removeClass: $.fn.removeClass, + removeClass: function(classNames,speed,easing,callback) { + return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames); + }, + + _toggleClass: $.fn.toggleClass, + toggleClass: function(classNames, force, speed, easing, callback) { + if ( typeof force == "boolean" || force === undefined ) { + if ( !speed ) { + // without speed parameter; + return this._toggleClass(classNames, force); + } else { + return $.effects.animateClass.apply(this, [(force?{add:classNames}:{remove:classNames}),speed,easing,callback]); + } + } else { + // without switch parameter; + return $.effects.animateClass.apply(this, [{ toggle: classNames },force,speed,easing]); + } + }, + + switchClass: function(remove,add,speed,easing,callback) { + return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]); + } +}); + + + +/******************************************************************************/ +/*********************************** EFFECTS **********************************/ +/******************************************************************************/ + +$.extend($.effects, { + version: "1.8.20", + + // Saves a set of properties in a data storage + save: function(element, set) { + for(var i=0; i < set.length; i++) { + if(set[i] !== null) element.data("ec.storage."+set[i], element[0].style[set[i]]); + } + }, + + // Restores a set of previously saved properties from a data storage + restore: function(element, set) { + for(var i=0; i < set.length; i++) { + if(set[i] !== null) element.css(set[i], element.data("ec.storage."+set[i])); + } + }, + + setMode: function(el, mode) { + if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle + return mode; + }, + + getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value + // this should be a little more flexible in the future to handle a string & hash + var y, x; + switch (origin[0]) { + case 'top': y = 0; break; + case 'middle': y = 0.5; break; + case 'bottom': y = 1; break; + default: y = origin[0] / original.height; + }; + switch (origin[1]) { + case 'left': x = 0; break; + case 'center': x = 0.5; break; + case 'right': x = 1; break; + default: x = origin[1] / original.width; + }; + return {x: x, y: y}; + }, + + // Wraps the element around a wrapper that copies position properties + createWrapper: function(element) { + + // if the element is already wrapped, return it + if (element.parent().is('.ui-effects-wrapper')) { + return element.parent(); + } + + // wrap the element + var props = { + width: element.outerWidth(true), + height: element.outerHeight(true), + 'float': element.css('float') + }, + wrapper = $('<div></div>') + .addClass('ui-effects-wrapper') + .css({ + fontSize: '100%', + background: 'transparent', + border: 'none', + margin: 0, + padding: 0 + }), + active = document.activeElement; + + element.wrap(wrapper); + + // Fixes #7595 - Elements lose focus when wrapped. + if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { + $( active ).focus(); + } + + wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually loose the reference to the wrapped element + + // transfer positioning properties to the wrapper + if (element.css('position') == 'static') { + wrapper.css({ position: 'relative' }); + element.css({ position: 'relative' }); + } else { + $.extend(props, { + position: element.css('position'), + zIndex: element.css('z-index') + }); + $.each(['top', 'left', 'bottom', 'right'], function(i, pos) { + props[pos] = element.css(pos); + if (isNaN(parseInt(props[pos], 10))) { + props[pos] = 'auto'; + } + }); + element.css({position: 'relative', top: 0, left: 0, right: 'auto', bottom: 'auto' }); + } + + return wrapper.css(props).show(); + }, + + removeWrapper: function(element) { + var parent, + active = document.activeElement; + + if (element.parent().is('.ui-effects-wrapper')) { + parent = element.parent().replaceWith(element); + // Fixes #7595 - Elements lose focus when wrapped. + if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { + $( active ).focus(); + } + return parent; + } + + return element; + }, + + setTransition: function(element, list, factor, value) { + value = value || {}; + $.each(list, function(i, x){ + var unit = element.cssUnit(x); + if (unit[0] > 0) value[x] = unit[0] * factor + unit[1]; + }); + return value; + } +}); + + +function _normalizeArguments(effect, options, speed, callback) { + // shift params for method overloading + if (typeof effect == 'object') { + callback = options; + speed = null; + options = effect; + effect = options.effect; + } + if ($.isFunction(options)) { + callback = options; + speed = null; + options = {}; + } + if (typeof options == 'number' || $.fx.speeds[options]) { + callback = speed; + speed = options; + options = {}; + } + if ($.isFunction(speed)) { + callback = speed; + speed = null; + } + + options = options || {}; + + speed = speed || options.duration; + speed = $.fx.off ? 0 : typeof speed == 'number' + ? speed : speed in $.fx.speeds ? $.fx.speeds[speed] : $.fx.speeds._default; + + callback = callback || options.complete; + + return [effect, options, speed, callback]; +} + +function standardSpeed( speed ) { + // valid standard speeds + if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) { + return true; + } + + // invalid strings - treat as "normal" speed + if ( typeof speed === "string" && !$.effects[ speed ] ) { + return true; + } + + return false; +} + +$.fn.extend({ + effect: function(effect, options, speed, callback) { + var args = _normalizeArguments.apply(this, arguments), + // TODO: make effects take actual parameters instead of a hash + args2 = { + options: args[1], + duration: args[2], + callback: args[3] + }, + mode = args2.options.mode, + effectMethod = $.effects[effect]; + + if ( $.fx.off || !effectMethod ) { + // delegate to the original method (e.g., .show()) if possible + if ( mode ) { + return this[ mode ]( args2.duration, args2.callback ); + } else { + return this.each(function() { + if ( args2.callback ) { + args2.callback.call( this ); + } + }); + } + } + + return effectMethod.call(this, args2); + }, + + _show: $.fn.show, + show: function(speed) { + if ( standardSpeed( speed ) ) { + return this._show.apply(this, arguments); + } else { + var args = _normalizeArguments.apply(this, arguments); + args[1].mode = 'show'; + return this.effect.apply(this, args); + } + }, + + _hide: $.fn.hide, + hide: function(speed) { + if ( standardSpeed( speed ) ) { + return this._hide.apply(this, arguments); + } else { + var args = _normalizeArguments.apply(this, arguments); + args[1].mode = 'hide'; + return this.effect.apply(this, args); + } + }, + + // jQuery core overloads toggle and creates _toggle + __toggle: $.fn.toggle, + toggle: function(speed) { + if ( standardSpeed( speed ) || typeof speed === "boolean" || $.isFunction( speed ) ) { + return this.__toggle.apply(this, arguments); + } else { + var args = _normalizeArguments.apply(this, arguments); + args[1].mode = 'toggle'; + return this.effect.apply(this, args); + } + }, + + // helper functions + cssUnit: function(key) { + var style = this.css(key), val = []; + $.each( ['em','px','%','pt'], function(i, unit){ + if(style.indexOf(unit) > 0) + val = [parseFloat(style), unit]; + }); + return val; + } +}); + + + +/******************************************************************************/ +/*********************************** EASING ***********************************/ +/******************************************************************************/ + +/* + * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ + * + * Uses the built in easing capabilities added In jQuery 1.1 + * to offer multiple easing options + * + * TERMS OF USE - jQuery Easing + * + * Open source under the BSD License. + * + * Copyright 2008 George McGinley Smith + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * Neither the name of the author nor the names of contributors may be used to endorse + * or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * +*/ + +// t: current time, b: begInnIng value, c: change In value, d: duration +$.easing.jswing = $.easing.swing; + +$.extend($.easing, +{ + def: 'easeOutQuad', + swing: function (x, t, b, c, d) { + //alert($.easing.default); + return $.easing[$.easing.def](x, t, b, c, d); + }, + easeInQuad: function (x, t, b, c, d) { + return c*(t/=d)*t + b; + }, + easeOutQuad: function (x, t, b, c, d) { + return -c *(t/=d)*(t-2) + b; + }, + easeInOutQuad: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t + b; + return -c/2 * ((--t)*(t-2) - 1) + b; + }, + easeInCubic: function (x, t, b, c, d) { + return c*(t/=d)*t*t + b; + }, + easeOutCubic: function (x, t, b, c, d) { + return c*((t=t/d-1)*t*t + 1) + b; + }, + easeInOutCubic: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t + b; + return c/2*((t-=2)*t*t + 2) + b; + }, + easeInQuart: function (x, t, b, c, d) { + return c*(t/=d)*t*t*t + b; + }, + easeOutQuart: function (x, t, b, c, d) { + return -c * ((t=t/d-1)*t*t*t - 1) + b; + }, + easeInOutQuart: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t*t + b; + return -c/2 * ((t-=2)*t*t*t - 2) + b; + }, + easeInQuint: function (x, t, b, c, d) { + return c*(t/=d)*t*t*t*t + b; + }, + easeOutQuint: function (x, t, b, c, d) { + return c*((t=t/d-1)*t*t*t*t + 1) + b; + }, + easeInOutQuint: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; + return c/2*((t-=2)*t*t*t*t + 2) + b; + }, + easeInSine: function (x, t, b, c, d) { + return -c * Math.cos(t/d * (Math.PI/2)) + c + b; + }, + easeOutSine: function (x, t, b, c, d) { + return c * Math.sin(t/d * (Math.PI/2)) + b; + }, + easeInOutSine: function (x, t, b, c, d) { + return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; + }, + easeInExpo: function (x, t, b, c, d) { + return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; + }, + easeOutExpo: function (x, t, b, c, d) { + return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; + }, + easeInOutExpo: function (x, t, b, c, d) { + if (t==0) return b; + if (t==d) return b+c; + if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; + return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; + }, + easeInCirc: function (x, t, b, c, d) { + return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; + }, + easeOutCirc: function (x, t, b, c, d) { + return c * Math.sqrt(1 - (t=t/d-1)*t) + b; + }, + easeInOutCirc: function (x, t, b, c, d) { + if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; + return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; + }, + easeInElastic: function (x, t, b, c, d) { + var s=1.70158;var p=0;var a=c; + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + }, + easeOutElastic: function (x, t, b, c, d) { + var s=1.70158;var p=0;var a=c; + if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; + if (a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; + }, + easeInOutElastic: function (x, t, b, c, d) { + var s=1.70158;var p=0;var a=c; + if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); + if (a < Math.abs(c)) { a=c; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (c/a); + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; + }, + easeInBack: function (x, t, b, c, d, s) { + if (s == undefined) s = 1.70158; + return c*(t/=d)*t*((s+1)*t - s) + b; + }, + easeOutBack: function (x, t, b, c, d, s) { + if (s == undefined) s = 1.70158; + return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; + }, + easeInOutBack: function (x, t, b, c, d, s) { + if (s == undefined) s = 1.70158; + if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; + return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; + }, + easeInBounce: function (x, t, b, c, d) { + return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b; + }, + easeOutBounce: function (x, t, b, c, d) { + if ((t/=d) < (1/2.75)) { + return c*(7.5625*t*t) + b; + } else if (t < (2/2.75)) { + return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; + } else if (t < (2.5/2.75)) { + return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; + } else { + return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; + } + }, + easeInOutBounce: function (x, t, b, c, d) { + if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; + return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; + } +}); + +/* + * + * TERMS OF USE - EASING EQUATIONS + * + * Open source under the BSD License. + * + * Copyright 2001 Robert Penner + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * Neither the name of the author nor the names of contributors may be used to endorse + * or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +})(jQuery); + +(function( $, undefined ) { + +$.effects.blind = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode + var direction = o.options.direction || 'vertical'; // Default direction + + // Adjust + $.effects.save(el, props); el.show(); // Save & Show + var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper + var ref = (direction == 'vertical') ? 'height' : 'width'; + var distance = (direction == 'vertical') ? wrapper.height() : wrapper.width(); + if(mode == 'show') wrapper.css(ref, 0); // Shift + + // Animation + var animation = {}; + animation[ref] = mode == 'show' ? distance : 0; + + // Animate + wrapper.animate(animation, o.duration, o.options.easing, function() { + if(mode == 'hide') el.hide(); // Hide + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(el[0], arguments); // Callback + el.dequeue(); + }); + + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.bounce = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode + var direction = o.options.direction || 'up'; // Default direction + var distance = o.options.distance || 20; // Default distance + var times = o.options.times || 5; // Default # of times + var speed = o.duration || 250; // Default speed per bounce + if (/show|hide/.test(mode)) props.push('opacity'); // Avoid touching opacity to prevent clearType and PNG issues in IE + + // Adjust + $.effects.save(el, props); el.show(); // Save & Show + $.effects.createWrapper(el); // Create Wrapper + var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; + var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; + var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 3 : el.outerWidth({margin:true}) / 3); + if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift + if (mode == 'hide') distance = distance / (times * 2); + if (mode != 'hide') times--; + + // Animate + if (mode == 'show') { // Show Bounce + var animation = {opacity: 1}; + animation[ref] = (motion == 'pos' ? '+=' : '-=') + distance; + el.animate(animation, speed / 2, o.options.easing); + distance = distance / 2; + times--; + }; + for (var i = 0; i < times; i++) { // Bounces + var animation1 = {}, animation2 = {}; + animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance; + animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance; + el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing); + distance = (mode == 'hide') ? distance * 2 : distance / 2; + }; + if (mode == 'hide') { // Last Bounce + var animation = {opacity: 0}; + animation[ref] = (motion == 'pos' ? '-=' : '+=') + distance; + el.animate(animation, speed / 2, o.options.easing, function(){ + el.hide(); // Hide + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(this, arguments); // Callback + }); + } else { + var animation1 = {}, animation2 = {}; + animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance; + animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance; + el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing, function(){ + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(this, arguments); // Callback + }); + }; + el.queue('fx', function() { el.dequeue(); }); + el.dequeue(); + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.clip = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right','height','width']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode + var direction = o.options.direction || 'vertical'; // Default direction + + // Adjust + $.effects.save(el, props); el.show(); // Save & Show + var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper + var animate = el[0].tagName == 'IMG' ? wrapper : el; + var ref = { + size: (direction == 'vertical') ? 'height' : 'width', + position: (direction == 'vertical') ? 'top' : 'left' + }; + var distance = (direction == 'vertical') ? animate.height() : animate.width(); + if(mode == 'show') { animate.css(ref.size, 0); animate.css(ref.position, distance / 2); } // Shift + + // Animation + var animation = {}; + animation[ref.size] = mode == 'show' ? distance : 0; + animation[ref.position] = mode == 'show' ? 0 : distance / 2; + + // Animate + animate.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { + if(mode == 'hide') el.hide(); // Hide + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(el[0], arguments); // Callback + el.dequeue(); + }}); + + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.drop = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right','opacity']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode + var direction = o.options.direction || 'left'; // Default Direction + + // Adjust + $.effects.save(el, props); el.show(); // Save & Show + $.effects.createWrapper(el); // Create Wrapper + var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; + var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; + var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 2 : el.outerWidth({margin:true}) / 2); + if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift + + // Animation + var animation = {opacity: mode == 'show' ? 1 : 0}; + animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance; + + // Animate + el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { + if(mode == 'hide') el.hide(); // Hide + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(this, arguments); // Callback + el.dequeue(); + }}); + + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.explode = function(o) { + + return this.queue(function() { + + var rows = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3; + var cells = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3; + + o.options.mode = o.options.mode == 'toggle' ? ($(this).is(':visible') ? 'hide' : 'show') : o.options.mode; + var el = $(this).show().css('visibility', 'hidden'); + var offset = el.offset(); + + //Substract the margins - not fixing the problem yet. + offset.top -= parseInt(el.css("marginTop"),10) || 0; + offset.left -= parseInt(el.css("marginLeft"),10) || 0; + + var width = el.outerWidth(true); + var height = el.outerHeight(true); + + for(var i=0;i<rows;i++) { // = + for(var j=0;j<cells;j++) { // || + el + .clone() + .appendTo('body') + .wrap('<div></div>') + .css({ + position: 'absolute', + visibility: 'visible', + left: -j*(width/cells), + top: -i*(height/rows) + }) + .parent() + .addClass('ui-effects-explode') + .css({ + position: 'absolute', + overflow: 'hidden', + width: width/cells, + height: height/rows, + left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? (j-Math.floor(cells/2))*(width/cells) : 0), + top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? (i-Math.floor(rows/2))*(height/rows) : 0), + opacity: o.options.mode == 'show' ? 0 : 1 + }).animate({ + left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? 0 : (j-Math.floor(cells/2))*(width/cells)), + top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? 0 : (i-Math.floor(rows/2))*(height/rows)), + opacity: o.options.mode == 'show' ? 1 : 0 + }, o.duration || 500); + } + } + + // Set a timeout, to call the callback approx. when the other animations have finished + setTimeout(function() { + + o.options.mode == 'show' ? el.css({ visibility: 'visible' }) : el.css({ visibility: 'visible' }).hide(); + if(o.callback) o.callback.apply(el[0]); // Callback + el.dequeue(); + + $('div.ui-effects-explode').remove(); + + }, o.duration || 500); + + + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.fade = function(o) { + return this.queue(function() { + var elem = $(this), + mode = $.effects.setMode(elem, o.options.mode || 'hide'); + + elem.animate({ opacity: mode }, { + queue: false, + duration: o.duration, + easing: o.options.easing, + complete: function() { + (o.callback && o.callback.apply(this, arguments)); + elem.dequeue(); + } + }); + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.fold = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode + var size = o.options.size || 15; // Default fold size + var horizFirst = !(!o.options.horizFirst); // Ensure a boolean value + var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2; + + // Adjust + $.effects.save(el, props); el.show(); // Save & Show + var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper + var widthFirst = ((mode == 'show') != horizFirst); + var ref = widthFirst ? ['width', 'height'] : ['height', 'width']; + var distance = widthFirst ? [wrapper.width(), wrapper.height()] : [wrapper.height(), wrapper.width()]; + var percent = /([0-9]+)%/.exec(size); + if(percent) size = parseInt(percent[1],10) / 100 * distance[mode == 'hide' ? 0 : 1]; + if(mode == 'show') wrapper.css(horizFirst ? {height: 0, width: size} : {height: size, width: 0}); // Shift + + // Animation + var animation1 = {}, animation2 = {}; + animation1[ref[0]] = mode == 'show' ? distance[0] : size; + animation2[ref[1]] = mode == 'show' ? distance[1] : 0; + + // Animate + wrapper.animate(animation1, duration, o.options.easing) + .animate(animation2, duration, o.options.easing, function() { + if(mode == 'hide') el.hide(); // Hide + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(el[0], arguments); // Callback + el.dequeue(); + }); + + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.highlight = function(o) { + return this.queue(function() { + var elem = $(this), + props = ['backgroundImage', 'backgroundColor', 'opacity'], + mode = $.effects.setMode(elem, o.options.mode || 'show'), + animation = { + backgroundColor: elem.css('backgroundColor') + }; + + if (mode == 'hide') { + animation.opacity = 0; + } + + $.effects.save(elem, props); + elem + .show() + .css({ + backgroundImage: 'none', + backgroundColor: o.options.color || '#ffff99' + }) + .animate(animation, { + queue: false, + duration: o.duration, + easing: o.options.easing, + complete: function() { + (mode == 'hide' && elem.hide()); + $.effects.restore(elem, props); + (mode == 'show' && !$.support.opacity && this.style.removeAttribute('filter')); + (o.callback && o.callback.apply(this, arguments)); + elem.dequeue(); + } + }); + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.pulsate = function(o) { + return this.queue(function() { + var elem = $(this), + mode = $.effects.setMode(elem, o.options.mode || 'show'), + times = ((o.options.times || 5) * 2) - 1, + duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2, + isVisible = elem.is(':visible'), + animateTo = 0; + + if (!isVisible) { + elem.css('opacity', 0).show(); + animateTo = 1; + } + + if ((mode == 'hide' && isVisible) || (mode == 'show' && !isVisible)) { + times--; + } + + for (var i = 0; i < times; i++) { + elem.animate({ opacity: animateTo }, duration, o.options.easing); + animateTo = (animateTo + 1) % 2; + } + + elem.animate({ opacity: animateTo }, duration, o.options.easing, function() { + if (animateTo == 0) { + elem.hide(); + } + (o.callback && o.callback.apply(this, arguments)); + }); + + elem + .queue('fx', function() { elem.dequeue(); }) + .dequeue(); + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.puff = function(o) { + return this.queue(function() { + var elem = $(this), + mode = $.effects.setMode(elem, o.options.mode || 'hide'), + percent = parseInt(o.options.percent, 10) || 150, + factor = percent / 100, + original = { height: elem.height(), width: elem.width() }; + + $.extend(o.options, { + fade: true, + mode: mode, + percent: mode == 'hide' ? percent : 100, + from: mode == 'hide' + ? original + : { + height: original.height * factor, + width: original.width * factor + } + }); + + elem.effect('scale', o.options, o.duration, o.callback); + elem.dequeue(); + }); +}; + +$.effects.scale = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this); + + // Set options + var options = $.extend(true, {}, o.options); + var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode + var percent = parseInt(o.options.percent,10) || (parseInt(o.options.percent,10) == 0 ? 0 : (mode == 'hide' ? 0 : 100)); // Set default scaling percent + var direction = o.options.direction || 'both'; // Set default axis + var origin = o.options.origin; // The origin of the scaling + if (mode != 'effect') { // Set default origin and restore for show/hide + options.origin = origin || ['middle','center']; + options.restore = true; + } + var original = {height: el.height(), width: el.width()}; // Save original + el.from = o.options.from || (mode == 'show' ? {height: 0, width: 0} : original); // Default from state + + // Adjust + var factor = { // Set scaling factor + y: direction != 'horizontal' ? (percent / 100) : 1, + x: direction != 'vertical' ? (percent / 100) : 1 + }; + el.to = {height: original.height * factor.y, width: original.width * factor.x}; // Set to state + + if (o.options.fade) { // Fade option to support puff + if (mode == 'show') {el.from.opacity = 0; el.to.opacity = 1;}; + if (mode == 'hide') {el.from.opacity = 1; el.to.opacity = 0;}; + }; + + // Animation + options.from = el.from; options.to = el.to; options.mode = mode; + + // Animate + el.effect('size', options, o.duration, o.callback); + el.dequeue(); + }); + +}; + +$.effects.size = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right','width','height','overflow','opacity']; + var props1 = ['position','top','bottom','left','right','overflow','opacity']; // Always restore + var props2 = ['width','height','overflow']; // Copy for children + var cProps = ['fontSize']; + var vProps = ['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom']; + var hProps = ['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode + var restore = o.options.restore || false; // Default restore + var scale = o.options.scale || 'both'; // Default scale mode + var origin = o.options.origin; // The origin of the sizing + var original = {height: el.height(), width: el.width()}; // Save original + el.from = o.options.from || original; // Default from state + el.to = o.options.to || original; // Default to state + // Adjust + if (origin) { // Calculate baseline shifts + var baseline = $.effects.getBaseline(origin, original); + el.from.top = (original.height - el.from.height) * baseline.y; + el.from.left = (original.width - el.from.width) * baseline.x; + el.to.top = (original.height - el.to.height) * baseline.y; + el.to.left = (original.width - el.to.width) * baseline.x; + }; + var factor = { // Set scaling factor + from: {y: el.from.height / original.height, x: el.from.width / original.width}, + to: {y: el.to.height / original.height, x: el.to.width / original.width} + }; + if (scale == 'box' || scale == 'both') { // Scale the css box + if (factor.from.y != factor.to.y) { // Vertical props scaling + props = props.concat(vProps); + el.from = $.effects.setTransition(el, vProps, factor.from.y, el.from); + el.to = $.effects.setTransition(el, vProps, factor.to.y, el.to); + }; + if (factor.from.x != factor.to.x) { // Horizontal props scaling + props = props.concat(hProps); + el.from = $.effects.setTransition(el, hProps, factor.from.x, el.from); + el.to = $.effects.setTransition(el, hProps, factor.to.x, el.to); + }; + }; + if (scale == 'content' || scale == 'both') { // Scale the content + if (factor.from.y != factor.to.y) { // Vertical props scaling + props = props.concat(cProps); + el.from = $.effects.setTransition(el, cProps, factor.from.y, el.from); + el.to = $.effects.setTransition(el, cProps, factor.to.y, el.to); + }; + }; + $.effects.save(el, restore ? props : props1); el.show(); // Save & Show + $.effects.createWrapper(el); // Create Wrapper + el.css('overflow','hidden').css(el.from); // Shift + + // Animate + if (scale == 'content' || scale == 'both') { // Scale the children + vProps = vProps.concat(['marginTop','marginBottom']).concat(cProps); // Add margins/font-size + hProps = hProps.concat(['marginLeft','marginRight']); // Add margins + props2 = props.concat(vProps).concat(hProps); // Concat + el.find("*[width]").each(function(){ + var child = $(this); + if (restore) $.effects.save(child, props2); + var c_original = {height: child.height(), width: child.width()}; // Save original + child.from = {height: c_original.height * factor.from.y, width: c_original.width * factor.from.x}; + child.to = {height: c_original.height * factor.to.y, width: c_original.width * factor.to.x}; + if (factor.from.y != factor.to.y) { // Vertical props scaling + child.from = $.effects.setTransition(child, vProps, factor.from.y, child.from); + child.to = $.effects.setTransition(child, vProps, factor.to.y, child.to); + }; + if (factor.from.x != factor.to.x) { // Horizontal props scaling + child.from = $.effects.setTransition(child, hProps, factor.from.x, child.from); + child.to = $.effects.setTransition(child, hProps, factor.to.x, child.to); + }; + child.css(child.from); // Shift children + child.animate(child.to, o.duration, o.options.easing, function(){ + if (restore) $.effects.restore(child, props2); // Restore children + }); // Animate children + }); + }; + + // Animate + el.animate(el.to, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { + if (el.to.opacity === 0) { + el.css('opacity', el.from.opacity); + } + if(mode == 'hide') el.hide(); // Hide + $.effects.restore(el, restore ? props : props1); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(this, arguments); // Callback + el.dequeue(); + }}); + + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.shake = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode + var direction = o.options.direction || 'left'; // Default direction + var distance = o.options.distance || 20; // Default distance + var times = o.options.times || 3; // Default # of times + var speed = o.duration || o.options.duration || 140; // Default speed per shake + + // Adjust + $.effects.save(el, props); el.show(); // Save & Show + $.effects.createWrapper(el); // Create Wrapper + var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; + var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; + + // Animation + var animation = {}, animation1 = {}, animation2 = {}; + animation[ref] = (motion == 'pos' ? '-=' : '+=') + distance; + animation1[ref] = (motion == 'pos' ? '+=' : '-=') + distance * 2; + animation2[ref] = (motion == 'pos' ? '-=' : '+=') + distance * 2; + + // Animate + el.animate(animation, speed, o.options.easing); + for (var i = 1; i < times; i++) { // Shakes + el.animate(animation1, speed, o.options.easing).animate(animation2, speed, o.options.easing); + }; + el.animate(animation1, speed, o.options.easing). + animate(animation, speed / 2, o.options.easing, function(){ // Last shake + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(this, arguments); // Callback + }); + el.queue('fx', function() { el.dequeue(); }); + el.dequeue(); + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.slide = function(o) { + + return this.queue(function() { + + // Create element + var el = $(this), props = ['position','top','bottom','left','right']; + + // Set options + var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode + var direction = o.options.direction || 'left'; // Default Direction + + // Adjust + $.effects.save(el, props); el.show(); // Save & Show + $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper + var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; + var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; + var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) : el.outerWidth({margin:true})); + if (mode == 'show') el.css(ref, motion == 'pos' ? (isNaN(distance) ? "-" + distance : -distance) : distance); // Shift + + // Animation + var animation = {}; + animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance; + + // Animate + el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { + if(mode == 'hide') el.hide(); // Hide + $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore + if(o.callback) o.callback.apply(this, arguments); // Callback + el.dequeue(); + }}); + + }); + +}; + +})(jQuery); + +(function( $, undefined ) { + +$.effects.transfer = function(o) { + return this.queue(function() { + var elem = $(this), + target = $(o.options.to), + endPosition = target.offset(), + animation = { + top: endPosition.top, + left: endPosition.left, + height: target.innerHeight(), + width: target.innerWidth() + }, + startPosition = elem.offset(), + transfer = $('<div class="ui-effects-transfer"></div>') + .appendTo(document.body) + .addClass(o.options.className) + .css({ + top: startPosition.top, + left: startPosition.left, + height: elem.innerHeight(), + width: elem.innerWidth(), + position: 'absolute' + }) + .animate(animation, o.duration, o.options.easing, function() { + transfer.remove(); + (o.callback && o.callback.apply(elem[0], arguments)); + elem.dequeue(); + }); + }); +}; + +})(jQuery); + +(function( $, undefined ) { + +$.widget( "ui.accordion", { + options: { + active: 0, + animated: "slide", + autoHeight: true, + clearStyle: false, + collapsible: false, + event: "click", + fillSpace: false, + header: "> li > :first-child,> :not(li):even", + icons: { + header: "ui-icon-triangle-1-e", + headerSelected: "ui-icon-triangle-1-s" + }, + navigation: false, + navigationFilter: function() { + return this.href.toLowerCase() === location.href.toLowerCase(); + } + }, + + _create: function() { + var self = this, + options = self.options; + + self.running = 0; + + self.element + .addClass( "ui-accordion ui-widget ui-helper-reset" ) + // in lack of child-selectors in CSS + // we need to mark top-LIs in a UL-accordion for some IE-fix + .children( "li" ) + .addClass( "ui-accordion-li-fix" ); + + self.headers = self.element.find( options.header ) + .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" ) + .bind( "mouseenter.accordion", function() { + if ( options.disabled ) { + return; + } + $( this ).addClass( "ui-state-hover" ); + }) + .bind( "mouseleave.accordion", function() { + if ( options.disabled ) { + return; + } + $( this ).removeClass( "ui-state-hover" ); + }) + .bind( "focus.accordion", function() { + if ( options.disabled ) { + return; + } + $( this ).addClass( "ui-state-focus" ); + }) + .bind( "blur.accordion", function() { + if ( options.disabled ) { + return; + } + $( this ).removeClass( "ui-state-focus" ); + }); + + self.headers.next() + .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ); + + if ( options.navigation ) { + var current = self.element.find( "a" ).filter( options.navigationFilter ).eq( 0 ); + if ( current.length ) { + var header = current.closest( ".ui-accordion-header" ); + if ( header.length ) { + // anchor within header + self.active = header; + } else { + // anchor within content + self.active = current.closest( ".ui-accordion-content" ).prev(); + } + } + } + + self.active = self._findActive( self.active || options.active ) + .addClass( "ui-state-default ui-state-active" ) + .toggleClass( "ui-corner-all" ) + .toggleClass( "ui-corner-top" ); + self.active.next().addClass( "ui-accordion-content-active" ); + + self._createIcons(); + self.resize(); + + // ARIA + self.element.attr( "role", "tablist" ); + + self.headers + .attr( "role", "tab" ) + .bind( "keydown.accordion", function( event ) { + return self._keydown( event ); + }) + .next() + .attr( "role", "tabpanel" ); + + self.headers + .not( self.active || "" ) + .attr({ + "aria-expanded": "false", + "aria-selected": "false", + tabIndex: -1 + }) + .next() + .hide(); + + // make sure at least one header is in the tab order + if ( !self.active.length ) { + self.headers.eq( 0 ).attr( "tabIndex", 0 ); + } else { + self.active + .attr({ + "aria-expanded": "true", + "aria-selected": "true", + tabIndex: 0 + }); + } + + // only need links in tab order for Safari + if ( !$.browser.safari ) { + self.headers.find( "a" ).attr( "tabIndex", -1 ); + } + + if ( options.event ) { + self.headers.bind( options.event.split(" ").join(".accordion ") + ".accordion", function(event) { + self._clickHandler.call( self, event, this ); + event.preventDefault(); + }); + } + }, + + _createIcons: function() { + var options = this.options; + if ( options.icons ) { + $( "<span></span>" ) + .addClass( "ui-icon " + options.icons.header ) + .prependTo( this.headers ); + this.active.children( ".ui-icon" ) + .toggleClass(options.icons.header) + .toggleClass(options.icons.headerSelected); + this.element.addClass( "ui-accordion-icons" ); + } + }, + + _destroyIcons: function() { + this.headers.children( ".ui-icon" ).remove(); + this.element.removeClass( "ui-accordion-icons" ); + }, + + destroy: function() { + var options = this.options; + + this.element + .removeClass( "ui-accordion ui-widget ui-helper-reset" ) + .removeAttr( "role" ); + + this.headers + .unbind( ".accordion" ) + .removeClass( "ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) + .removeAttr( "role" ) + .removeAttr( "aria-expanded" ) + .removeAttr( "aria-selected" ) + .removeAttr( "tabIndex" ); + + this.headers.find( "a" ).removeAttr( "tabIndex" ); + this._destroyIcons(); + var contents = this.headers.next() + .css( "display", "" ) + .removeAttr( "role" ) + .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled" ); + if ( options.autoHeight || options.fillHeight ) { + contents.css( "height", "" ); + } + + return $.Widget.prototype.destroy.call( this ); + }, + + _setOption: function( key, value ) { + $.Widget.prototype._setOption.apply( this, arguments ); + + if ( key == "active" ) { + this.activate( value ); + } + if ( key == "icons" ) { + this._destroyIcons(); + if ( value ) { + this._createIcons(); + } + } + // #5332 - opacity doesn't cascade to positioned elements in IE + // so we need to add the disabled class to the headers and panels + if ( key == "disabled" ) { + this.headers.add(this.headers.next()) + [ value ? "addClass" : "removeClass" ]( + "ui-accordion-disabled ui-state-disabled" ); + } + }, + + _keydown: function( event ) { + if ( this.options.disabled || event.altKey || event.ctrlKey ) { + return; + } + + var keyCode = $.ui.keyCode, + length = this.headers.length, + currentIndex = this.headers.index( event.target ), + toFocus = false; + + switch ( event.keyCode ) { + case keyCode.RIGHT: + case keyCode.DOWN: + toFocus = this.headers[ ( currentIndex + 1 ) % length ]; + break; + case keyCode.LEFT: + case keyCode.UP: + toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; + break; + case keyCode.SPACE: + case keyCode.ENTER: + this._clickHandler( { target: event.target }, event.target ); + event.preventDefault(); + } + + if ( toFocus ) { + $( event.target ).attr( "tabIndex", -1 ); + $( toFocus ).attr( "tabIndex", 0 ); + toFocus.focus(); + return false; + } + + return true; + }, + + resize: function() { + var options = this.options, + maxHeight; + + if ( options.fillSpace ) { + if ( $.browser.msie ) { + var defOverflow = this.element.parent().css( "overflow" ); + this.element.parent().css( "overflow", "hidden"); + } + maxHeight = this.element.parent().height(); + if ($.browser.msie) { + this.element.parent().css( "overflow", defOverflow ); + } + + this.headers.each(function() { + maxHeight -= $( this ).outerHeight( true ); + }); + + this.headers.next() + .each(function() { + $( this ).height( Math.max( 0, maxHeight - + $( this ).innerHeight() + $( this ).height() ) ); + }) + .css( "overflow", "auto" ); + } else if ( options.autoHeight ) { + maxHeight = 0; + this.headers.next() + .each(function() { + maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); + }) + .height( maxHeight ); + } + + return this; + }, + + activate: function( index ) { + // TODO this gets called on init, changing the option without an explicit call for that + this.options.active = index; + // call clickHandler with custom event + var active = this._findActive( index )[ 0 ]; + this._clickHandler( { target: active }, active ); + + return this; + }, + + _findActive: function( selector ) { + return selector + ? typeof selector === "number" + ? this.headers.filter( ":eq(" + selector + ")" ) + : this.headers.not( this.headers.not( selector ) ) + : selector === false + ? $( [] ) + : this.headers.filter( ":eq(0)" ); + }, + + // TODO isn't event.target enough? why the separate target argument? + _clickHandler: function( event, target ) { + var options = this.options; + if ( options.disabled ) { + return; + } + + // called only when using activate(false) to close all parts programmatically + if ( !event.target ) { + if ( !options.collapsible ) { + return; + } + this.active + .removeClass( "ui-state-active ui-corner-top" ) + .addClass( "ui-state-default ui-corner-all" ) + .children( ".ui-icon" ) + .removeClass( options.icons.headerSelected ) + .addClass( options.icons.header ); + this.active.next().addClass( "ui-accordion-content-active" ); + var toHide = this.active.next(), + data = { + options: options, + newHeader: $( [] ), + oldHeader: options.active, + newContent: $( [] ), + oldContent: toHide + }, + toShow = ( this.active = $( [] ) ); + this._toggle( toShow, toHide, data ); + return; + } + + // get the click target + var clicked = $( event.currentTarget || target ), + clickedIsActive = clicked[0] === this.active[0]; + + // TODO the option is changed, is that correct? + // TODO if it is correct, shouldn't that happen after determining that the click is valid? + options.active = options.collapsible && clickedIsActive ? + false : + this.headers.index( clicked ); + + // if animations are still active, or the active header is the target, ignore click + if ( this.running || ( !options.collapsible && clickedIsActive ) ) { + return; + } + + // find elements to show and hide + var active = this.active, + toShow = clicked.next(), + toHide = this.active.next(), + data = { + options: options, + newHeader: clickedIsActive && options.collapsible ? $([]) : clicked, + oldHeader: this.active, + newContent: clickedIsActive && options.collapsible ? $([]) : toShow, + oldContent: toHide + }, + down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] ); + + // when the call to ._toggle() comes after the class changes + // it causes a very odd bug in IE 8 (see #6720) + this.active = clickedIsActive ? $([]) : clicked; + this._toggle( toShow, toHide, data, clickedIsActive, down ); + + // switch classes + active + .removeClass( "ui-state-active ui-corner-top" ) + .addClass( "ui-state-default ui-corner-all" ) + .children( ".ui-icon" ) + .removeClass( options.icons.headerSelected ) + .addClass( options.icons.header ); + if ( !clickedIsActive ) { + clicked + .removeClass( "ui-state-default ui-corner-all" ) + .addClass( "ui-state-active ui-corner-top" ) + .children( ".ui-icon" ) + .removeClass( options.icons.header ) + .addClass( options.icons.headerSelected ); + clicked + .next() + .addClass( "ui-accordion-content-active" ); + } + + return; + }, + + _toggle: function( toShow, toHide, data, clickedIsActive, down ) { + var self = this, + options = self.options; + + self.toShow = toShow; + self.toHide = toHide; + self.data = data; + + var complete = function() { + if ( !self ) { + return; + } + return self._completed.apply( self, arguments ); + }; + + // trigger changestart event + self._trigger( "changestart", null, self.data ); + + // count elements to animate + self.running = toHide.size() === 0 ? toShow.size() : toHide.size(); + + if ( options.animated ) { + var animOptions = {}; + + if ( options.collapsible && clickedIsActive ) { + animOptions = { + toShow: $( [] ), + toHide: toHide, + complete: complete, + down: down, + autoHeight: options.autoHeight || options.fillSpace + }; + } else { + animOptions = { + toShow: toShow, + toHide: toHide, + complete: complete, + down: down, + autoHeight: options.autoHeight || options.fillSpace + }; + } + + if ( !options.proxied ) { + options.proxied = options.animated; + } + + if ( !options.proxiedDuration ) { + options.proxiedDuration = options.duration; + } + + options.animated = $.isFunction( options.proxied ) ? + options.proxied( animOptions ) : + options.proxied; + + options.duration = $.isFunction( options.proxiedDuration ) ? + options.proxiedDuration( animOptions ) : + options.proxiedDuration; + + var animations = $.ui.accordion.animations, + duration = options.duration, + easing = options.animated; + + if ( easing && !animations[ easing ] && !$.easing[ easing ] ) { + easing = "slide"; + } + if ( !animations[ easing ] ) { + animations[ easing ] = function( options ) { + this.slide( options, { + easing: easing, + duration: duration || 700 + }); + }; + } + + animations[ easing ]( animOptions ); + } else { + if ( options.collapsible && clickedIsActive ) { + toShow.toggle(); + } else { + toHide.hide(); + toShow.show(); + } + + complete( true ); + } + + // TODO assert that the blur and focus triggers are really necessary, remove otherwise + toHide.prev() + .attr({ + "aria-expanded": "false", + "aria-selected": "false", + tabIndex: -1 + }) + .blur(); + toShow.prev() + .attr({ + "aria-expanded": "true", + "aria-selected": "true", + tabIndex: 0 + }) + .focus(); + }, + + _completed: function( cancel ) { + this.running = cancel ? 0 : --this.running; + if ( this.running ) { + return; + } + + if ( this.options.clearStyle ) { + this.toShow.add( this.toHide ).css({ + height: "", + overflow: "" + }); + } + + // other classes are removed before the animation; this one needs to stay until completed + this.toHide.removeClass( "ui-accordion-content-active" ); + // Work around for rendering bug in IE (#5421) + if ( this.toHide.length ) { + this.toHide.parent()[0].className = this.toHide.parent()[0].className; + } + + this._trigger( "change", null, this.data ); + } +}); + +$.extend( $.ui.accordion, { + version: "1.8.20", + animations: { + slide: function( options, additions ) { + options = $.extend({ + easing: "swing", + duration: 300 + }, options, additions ); + if ( !options.toHide.size() ) { + options.toShow.animate({ + height: "show", + paddingTop: "show", + paddingBottom: "show" + }, options ); + return; + } + if ( !options.toShow.size() ) { + options.toHide.animate({ + height: "hide", + paddingTop: "hide", + paddingBottom: "hide" + }, options ); + return; + } + var overflow = options.toShow.css( "overflow" ), + percentDone = 0, + showProps = {}, + hideProps = {}, + fxAttrs = [ "height", "paddingTop", "paddingBottom" ], + originalWidth; + // fix width before calculating height of hidden element + var s = options.toShow; + originalWidth = s[0].style.width; + s.width( s.parent().width() + - parseFloat( s.css( "paddingLeft" ) ) + - parseFloat( s.css( "paddingRight" ) ) + - ( parseFloat( s.css( "borderLeftWidth" ) ) || 0 ) + - ( parseFloat( s.css( "borderRightWidth" ) ) || 0 ) ); + + $.each( fxAttrs, function( i, prop ) { + hideProps[ prop ] = "hide"; + + var parts = ( "" + $.css( options.toShow[0], prop ) ).match( /^([\d+-.]+)(.*)$/ ); + showProps[ prop ] = { + value: parts[ 1 ], + unit: parts[ 2 ] || "px" + }; + }); + options.toShow.css({ height: 0, overflow: "hidden" }).show(); + options.toHide + .filter( ":hidden" ) + .each( options.complete ) + .end() + .filter( ":visible" ) + .animate( hideProps, { + step: function( now, settings ) { + // only calculate the percent when animating height + // IE gets very inconsistent results when animating elements + // with small values, which is common for padding + if ( settings.prop == "height" ) { + percentDone = ( settings.end - settings.start === 0 ) ? 0 : + ( settings.now - settings.start ) / ( settings.end - settings.start ); + } + + options.toShow[ 0 ].style[ settings.prop ] = + ( percentDone * showProps[ settings.prop ].value ) + + showProps[ settings.prop ].unit; + }, + duration: options.duration, + easing: options.easing, + complete: function() { + if ( !options.autoHeight ) { + options.toShow.css( "height", "" ); + } + options.toShow.css({ + width: originalWidth, + overflow: overflow + }); + options.complete(); + } + }); + }, + bounceslide: function( options ) { + this.slide( options, { + easing: options.down ? "easeOutBounce" : "swing", + duration: options.down ? 1000 : 200 + }); + } + } +}); + +})( jQuery ); + +(function( $, undefined ) { + +// used to prevent race conditions with remote data sources +var requestIndex = 0; + +$.widget( "ui.autocomplete", { + options: { + appendTo: "body", + autoFocus: false, + delay: 300, + minLength: 1, + position: { + my: "left top", + at: "left bottom", + collision: "none" + }, + source: null + }, + + pending: 0, + + _create: function() { + var self = this, + doc = this.element[ 0 ].ownerDocument, + suppressKeyPress; + this.isMultiLine = this.element.is( "textarea" ); + + this.element + .addClass( "ui-autocomplete-input" ) + .attr( "autocomplete", "off" ) + // TODO verify these actually work as intended + .attr({ + role: "textbox", + "aria-autocomplete": "list", + "aria-haspopup": "true" + }) + .bind( "keydown.autocomplete", function( event ) { + if ( self.options.disabled || self.element.propAttr( "readOnly" ) ) { + return; + } + + suppressKeyPress = false; + var keyCode = $.ui.keyCode; + switch( event.keyCode ) { + case keyCode.PAGE_UP: + self._move( "previousPage", event ); + break; + case keyCode.PAGE_DOWN: + self._move( "nextPage", event ); + break; + case keyCode.UP: + self._keyEvent( "previous", event ); + break; + case keyCode.DOWN: + self._keyEvent( "next", event ); + break; + case keyCode.ENTER: + case keyCode.NUMPAD_ENTER: + // when menu is open and has focus + if ( self.menu.active ) { + // #6055 - Opera still allows the keypress to occur + // which causes forms to submit + suppressKeyPress = true; + event.preventDefault(); + } + //passthrough - ENTER and TAB both select the current element + case keyCode.TAB: + if ( !self.menu.active ) { + return; + } + self.menu.select( event ); + break; + case keyCode.ESCAPE: + self.element.val( self.term ); + self.close( event ); + break; + default: + // keypress is triggered before the input value is changed + clearTimeout( self.searching ); + self.searching = setTimeout(function() { + // only search if the value has changed + if ( self.term != self.element.val() ) { + self.selectedItem = null; + self.search( null, event ); + } + }, self.options.delay ); + break; + } + }) + .bind( "keypress.autocomplete", function( event ) { + if ( suppressKeyPress ) { + suppressKeyPress = false; + event.preventDefault(); + } + }) + .bind( "focus.autocomplete", function() { + if ( self.options.disabled ) { + return; + } + + self.selectedItem = null; + self.previous = self.element.val(); + }) + .bind( "blur.autocomplete", function( event ) { + if ( self.options.disabled ) { + return; + } + + clearTimeout( self.searching ); + // clicks on the menu (or a button to trigger a search) will cause a blur event + self.closing = setTimeout(function() { + self.close( event ); + self._change( event ); + }, 150 ); + }); + this._initSource(); + this.menu = $( "<ul></ul>" ) + .addClass( "ui-autocomplete" ) + .appendTo( $( this.options.appendTo || "body", doc )[0] ) + // prevent the close-on-blur in case of a "slow" click on the menu (long mousedown) + .mousedown(function( event ) { + // clicking on the scrollbar causes focus to shift to the body + // but we can't detect a mouseup or a click immediately afterward + // so we have to track the next mousedown and close the menu if + // the user clicks somewhere outside of the autocomplete + var menuElement = self.menu.element[ 0 ]; + if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { + setTimeout(function() { + $( document ).one( 'mousedown', function( event ) { + if ( event.target !== self.element[ 0 ] && + event.target !== menuElement && + !$.ui.contains( menuElement, event.target ) ) { + self.close(); + } + }); + }, 1 ); + } + + // use another timeout to make sure the blur-event-handler on the input was already triggered + setTimeout(function() { + clearTimeout( self.closing ); + }, 13); + }) + .menu({ + focus: function( event, ui ) { + var item = ui.item.data( "item.autocomplete" ); + if ( false !== self._trigger( "focus", event, { item: item } ) ) { + // use value to match what will end up in the input, if it was a key event + if ( /^key/.test(event.originalEvent.type) ) { + self.element.val( item.value ); + } + } + }, + selected: function( event, ui ) { + var item = ui.item.data( "item.autocomplete" ), + previous = self.previous; + + // only trigger when focus was lost (click on menu) + if ( self.element[0] !== doc.activeElement ) { + self.element.focus(); + self.previous = previous; + // #6109 - IE triggers two focus events and the second + // is asynchronous, so we need to reset the previous + // term synchronously and asynchronously :-( + setTimeout(function() { + self.previous = previous; + self.selectedItem = item; + }, 1); + } + + if ( false !== self._trigger( "select", event, { item: item } ) ) { + self.element.val( item.value ); + } + // reset the term after the select event + // this allows custom select handling to work properly + self.term = self.element.val(); + + self.close( event ); + self.selectedItem = item; + }, + blur: function( event, ui ) { + // don't set the value of the text field if it's already correct + // this prevents moving the cursor unnecessarily + if ( self.menu.element.is(":visible") && + ( self.element.val() !== self.term ) ) { + self.element.val( self.term ); + } + } + }) + .zIndex( this.element.zIndex() + 1 ) + // workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781 + .css({ top: 0, left: 0 }) + .hide() + .data( "menu" ); + if ( $.fn.bgiframe ) { + this.menu.element.bgiframe(); + } + // turning off autocomplete prevents the browser from remembering the + // value when navigating through history, so we re-enable autocomplete + // if the page is unloaded before the widget is destroyed. #7790 + self.beforeunloadHandler = function() { + self.element.removeAttr( "autocomplete" ); + }; + $( window ).bind( "beforeunload", self.beforeunloadHandler ); + }, + + destroy: function() { + this.element + .removeClass( "ui-autocomplete-input" ) + .removeAttr( "autocomplete" ) + .removeAttr( "role" ) + .removeAttr( "aria-autocomplete" ) + .removeAttr( "aria-haspopup" ); + this.menu.element.remove(); + $( window ).unbind( "beforeunload", this.beforeunloadHandler ); + $.Widget.prototype.destroy.call( this ); + }, + + _setOption: function( key, value ) { + $.Widget.prototype._setOption.apply( this, arguments ); + if ( key === "source" ) { + this._initSource(); + } + if ( key === "appendTo" ) { + this.menu.element.appendTo( $( value || "body", this.element[0].ownerDocument )[0] ) + } + if ( key === "disabled" && value && this.xhr ) { + this.xhr.abort(); + } + }, + + _initSource: function() { + var self = this, + array, + url; + if ( $.isArray(this.options.source) ) { + array = this.options.source; + this.source = function( request, response ) { + response( $.ui.autocomplete.filter(array, request.term) ); + }; + } else if ( typeof this.options.source === "string" ) { + url = this.options.source; + this.source = function( request, response ) { + if ( self.xhr ) { + self.xhr.abort(); + } + self.xhr = $.ajax({ + url: url, + data: request, + dataType: "json", + success: function( data, status ) { + response( data ); + }, + error: function() { + response( [] ); + } + }); + }; + } else { + this.source = this.options.source; + } + }, + + search: function( value, event ) { + value = value != null ? value : this.element.val(); + + // always save the actual value, not the one passed as an argument + this.term = this.element.val(); + + if ( value.length < this.options.minLength ) { + return this.close( event ); + } + + clearTimeout( this.closing ); + if ( this._trigger( "search", event ) === false ) { + return; + } + + return this._search( value ); + }, + + _search: function( value ) { + this.pending++; + this.element.addClass( "ui-autocomplete-loading" ); + + this.source( { term: value }, this._response() ); + }, + + _response: function() { + var that = this, + index = ++requestIndex; + + return function( content ) { + if ( index === requestIndex ) { + that.__response( content ); + } + + that.pending--; + if ( !that.pending ) { + that.element.removeClass( "ui-autocomplete-loading" ); + } + }; + }, + + __response: function( content ) { + if ( !this.options.disabled && content && content.length ) { + content = this._normalize( content ); + this._suggest( content ); + this._trigger( "open" ); + } else { + this.close(); + } + }, + + close: function( event ) { + clearTimeout( this.closing ); + if ( this.menu.element.is(":visible") ) { + this.menu.element.hide(); + this.menu.deactivate(); + this._trigger( "close", event ); + } + }, + + _change: function( event ) { + if ( this.previous !== this.element.val() ) { + this._trigger( "change", event, { item: this.selectedItem } ); + } + }, + + _normalize: function( items ) { + // assume all items have the right format when the first item is complete + if ( items.length && items[0].label && items[0].value ) { + return items; + } + return $.map( items, function(item) { + if ( typeof item === "string" ) { + return { + label: item, + value: item + }; + } + return $.extend({ + label: item.label || item.value, + value: item.value || item.label + }, item ); + }); + }, + + _suggest: function( items ) { + var ul = this.menu.element + .empty() + .zIndex( this.element.zIndex() + 1 ); + this._renderMenu( ul, items ); + // TODO refresh should check if the active item is still in the dom, removing the need for a manual deactivate + this.menu.deactivate(); + this.menu.refresh(); + + // size and position menu + ul.show(); + this._resizeMenu(); + ul.position( $.extend({ + of: this.element + }, this.options.position )); + + if ( this.options.autoFocus ) { + this.menu.next( new $.Event("mouseover") ); + } + }, + + _resizeMenu: function() { + var ul = this.menu.element; + ul.outerWidth( Math.max( + // Firefox wraps long text (possibly a rounding bug) + // so we add 1px to avoid the wrapping (#7513) + ul.width( "" ).outerWidth() + 1, + this.element.outerWidth() + ) ); + }, + + _renderMenu: function( ul, items ) { + var self = this; + $.each( items, function( index, item ) { + self._renderItem( ul, item ); + }); + }, + + _renderItem: function( ul, item) { + return $( "<li></li>" ) + .data( "item.autocomplete", item ) + .append( $( "<a></a>" ).text( item.label ) ) + .appendTo( ul ); + }, + + _move: function( direction, event ) { + if ( !this.menu.element.is(":visible") ) { + this.search( null, event ); + return; + } + if ( this.menu.first() && /^previous/.test(direction) || + this.menu.last() && /^next/.test(direction) ) { + this.element.val( this.term ); + this.menu.deactivate(); + return; + } + this.menu[ direction ]( event ); + }, + + widget: function() { + return this.menu.element; + }, + _keyEvent: function( keyEvent, event ) { + if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { + this._move( keyEvent, event ); + + // prevents moving cursor to beginning/end of the text field in some browsers + event.preventDefault(); + } + } +}); + +$.extend( $.ui.autocomplete, { + escapeRegex: function( value ) { + return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + }, + filter: function(array, term) { + var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" ); + return $.grep( array, function(value) { + return matcher.test( value.label || value.value || value ); + }); + } +}); + +}( jQuery )); + +/* + * jQuery UI Menu (not officially released) + * + * This widget isn't yet finished and the API is subject to change. We plan to finish + * it for the next release. You're welcome to give it a try anyway and give us feedback, + * as long as you're okay with migrating your code later on. We can help with that, too. + * + * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * http://docs.jquery.com/UI/Menu + * + * Depends: + * jquery.ui.core.js + * jquery.ui.widget.js + */ +(function($) { + +$.widget("ui.menu", { + _create: function() { + var self = this; + this.element + .addClass("ui-menu ui-widget ui-widget-content ui-corner-all") + .attr({ + role: "listbox", + "aria-activedescendant": "ui-active-menuitem" + }) + .click(function( event ) { + if ( !$( event.target ).closest( ".ui-menu-item a" ).length ) { + return; + } + // temporary + event.preventDefault(); + self.select( event ); + }); + this.refresh(); + }, + + refresh: function() { + var self = this; + + // don't refresh list items that are already adapted + var items = this.element.children("li:not(.ui-menu-item):has(a)") + .addClass("ui-menu-item") + .attr("role", "menuitem"); + + items.children("a") + .addClass("ui-corner-all") + .attr("tabindex", -1) + // mouseenter doesn't work with event delegation + .mouseenter(function( event ) { + self.activate( event, $(this).parent() ); + }) + .mouseleave(function() { + self.deactivate(); + }); + }, + + activate: function( event, item ) { + this.deactivate(); + if (this.hasScroll()) { + var offset = item.offset().top - this.element.offset().top, + scroll = this.element.scrollTop(), + elementHeight = this.element.height(); + if (offset < 0) { + this.element.scrollTop( scroll + offset); + } else if (offset >= elementHeight) { + this.element.scrollTop( scroll + offset - elementHeight + item.height()); + } + } + this.active = item.eq(0) + .children("a") + .addClass("ui-state-hover") + .attr("id", "ui-active-menuitem") + .end(); + this._trigger("focus", event, { item: item }); + }, + + deactivate: function() { + if (!this.active) { return; } + + this.active.children("a") + .removeClass("ui-state-hover") + .removeAttr("id"); + this._trigger("blur"); + this.active = null; + }, + + next: function(event) { + this.move("next", ".ui-menu-item:first", event); + }, + + previous: function(event) { + this.move("prev", ".ui-menu-item:last", event); + }, + + first: function() { + return this.active && !this.active.prevAll(".ui-menu-item").length; + }, + + last: function() { + return this.active && !this.active.nextAll(".ui-menu-item").length; + }, + + move: function(direction, edge, event) { + if (!this.active) { + this.activate(event, this.element.children(edge)); + return; + } + var next = this.active[direction + "All"](".ui-menu-item").eq(0); + if (next.length) { + this.activate(event, next); + } else { + this.activate(event, this.element.children(edge)); + } + }, + + // TODO merge with previousPage + nextPage: function(event) { + if (this.hasScroll()) { + // TODO merge with no-scroll-else + if (!this.active || this.last()) { + this.activate(event, this.element.children(".ui-menu-item:first")); + return; + } + var base = this.active.offset().top, + height = this.element.height(), + result = this.element.children(".ui-menu-item").filter(function() { + var close = $(this).offset().top - base - height + $(this).height(); + // TODO improve approximation + return close < 10 && close > -10; + }); + + // TODO try to catch this earlier when scrollTop indicates the last page anyway + if (!result.length) { + result = this.element.children(".ui-menu-item:last"); + } + this.activate(event, result); + } else { + this.activate(event, this.element.children(".ui-menu-item") + .filter(!this.active || this.last() ? ":first" : ":last")); + } + }, + + // TODO merge with nextPage + previousPage: function(event) { + if (this.hasScroll()) { + // TODO merge with no-scroll-else + if (!this.active || this.first()) { + this.activate(event, this.element.children(".ui-menu-item:last")); + return; + } + + var base = this.active.offset().top, + height = this.element.height(), + result = this.element.children(".ui-menu-item").filter(function() { + var close = $(this).offset().top - base + height - $(this).height(); + // TODO improve approximation + return close < 10 && close > -10; + }); + + // TODO try to catch this earlier when scrollTop indicates the last page anyway + if (!result.length) { + result = this.element.children(".ui-menu-item:first"); + } + this.activate(event, result); + } else { + this.activate(event, this.element.children(".ui-menu-item") + .filter(!this.active || this.first() ? ":last" : ":first")); + } + }, + + hasScroll: function() { + return this.element.height() < this.element[ $.fn.prop ? "prop" : "attr" ]("scrollHeight"); + }, + + select: function( event ) { + this._trigger("selected", event, { item: this.active }); + } +}); + +}(jQuery)); + +(function( $, undefined ) { + +var lastActive, startXPos, startYPos, clickDragged, + baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", + stateClasses = "ui-state-hover ui-state-active ", + typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", + formResetHandler = function() { + var buttons = $( this ).find( ":ui-button" ); + setTimeout(function() { + buttons.button( "refresh" ); + }, 1 ); + }, + radioGroup = function( radio ) { + var name = radio.name, + form = radio.form, + radios = $( [] ); + if ( name ) { + if ( form ) { + radios = $( form ).find( "[name='" + name + "']" ); + } else { + radios = $( "[name='" + name + "']", radio.ownerDocument ) + .filter(function() { + return !this.form; + }); + } + } + return radios; + }; + +$.widget( "ui.button", { + options: { + disabled: null, + text: true, + label: null, + icons: { + primary: null, + secondary: null + } + }, + _create: function() { + this.element.closest( "form" ) + .unbind( "reset.button" ) + .bind( "reset.button", formResetHandler ); + + if ( typeof this.options.disabled !== "boolean" ) { + this.options.disabled = !!this.element.propAttr( "disabled" ); + } else { + this.element.propAttr( "disabled", this.options.disabled ); + } + + this._determineButtonType(); + this.hasTitle = !!this.buttonElement.attr( "title" ); + + var self = this, + options = this.options, + toggleButton = this.type === "checkbox" || this.type === "radio", + hoverClass = "ui-state-hover" + ( !toggleButton ? " ui-state-active" : "" ), + focusClass = "ui-state-focus"; + + if ( options.label === null ) { + options.label = this.buttonElement.html(); + } + + this.buttonElement + .addClass( baseClasses ) + .attr( "role", "button" ) + .bind( "mouseenter.button", function() { + if ( options.disabled ) { + return; + } + $( this ).addClass( "ui-state-hover" ); + if ( this === lastActive ) { + $( this ).addClass( "ui-state-active" ); + } + }) + .bind( "mouseleave.button", function() { + if ( options.disabled ) { + return; + } + $( this ).removeClass( hoverClass ); + }) + .bind( "click.button", function( event ) { + if ( options.disabled ) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + }); + + this.element + .bind( "focus.button", function() { + // no need to check disabled, focus won't be triggered anyway + self.buttonElement.addClass( focusClass ); + }) + .bind( "blur.button", function() { + self.buttonElement.removeClass( focusClass ); + }); + + if ( toggleButton ) { + this.element.bind( "change.button", function() { + if ( clickDragged ) { + return; + } + self.refresh(); + }); + // if mouse moves between mousedown and mouseup (drag) set clickDragged flag + // prevents issue where button state changes but checkbox/radio checked state + // does not in Firefox (see ticket #6970) + this.buttonElement + .bind( "mousedown.button", function( event ) { + if ( options.disabled ) { + return; + } + clickDragged = false; + startXPos = event.pageX; + startYPos = event.pageY; + }) + .bind( "mouseup.button", function( event ) { + if ( options.disabled ) { + return; + } + if ( startXPos !== event.pageX || startYPos !== event.pageY ) { + clickDragged = true; + } + }); + } + + if ( this.type === "checkbox" ) { + this.buttonElement.bind( "click.button", function() { + if ( options.disabled || clickDragged ) { + return false; + } + $( this ).toggleClass( "ui-state-active" ); + self.buttonElement.attr( "aria-pressed", self.element[0].checked ); + }); + } else if ( this.type === "radio" ) { + this.buttonElement.bind( "click.button", function() { + if ( options.disabled || clickDragged ) { + return false; + } + $( this ).addClass( "ui-state-active" ); + self.buttonElement.attr( "aria-pressed", "true" ); + + var radio = self.element[ 0 ]; + radioGroup( radio ) + .not( radio ) + .map(function() { + return $( this ).button( "widget" )[ 0 ]; + }) + .removeClass( "ui-state-active" ) + .attr( "aria-pressed", "false" ); + }); + } else { + this.buttonElement + .bind( "mousedown.button", function() { + if ( options.disabled ) { + return false; + } + $( this ).addClass( "ui-state-active" ); + lastActive = this; + $( document ).one( "mouseup", function() { + lastActive = null; + }); + }) + .bind( "mouseup.button", function() { + if ( options.disabled ) { + return false; + } + $( this ).removeClass( "ui-state-active" ); + }) + .bind( "keydown.button", function(event) { + if ( options.disabled ) { + return false; + } + if ( event.keyCode == $.ui.keyCode.SPACE || event.keyCode == $.ui.keyCode.ENTER ) { + $( this ).addClass( "ui-state-active" ); + } + }) + .bind( "keyup.button", function() { + $( this ).removeClass( "ui-state-active" ); + }); + + if ( this.buttonElement.is("a") ) { + this.buttonElement.keyup(function(event) { + if ( event.keyCode === $.ui.keyCode.SPACE ) { + // TODO pass through original event correctly (just as 2nd argument doesn't work) + $( this ).click(); + } + }); + } + } + + // TODO: pull out $.Widget's handling for the disabled option into + // $.Widget.prototype._setOptionDisabled so it's easy to proxy and can + // be overridden by individual plugins + this._setOption( "disabled", options.disabled ); + this._resetButton(); + }, + + _determineButtonType: function() { + + if ( this.element.is(":checkbox") ) { + this.type = "checkbox"; + } else if ( this.element.is(":radio") ) { + this.type = "radio"; + } else if ( this.element.is("input") ) { + this.type = "input"; + } else { + this.type = "button"; + } + + if ( this.type === "checkbox" || this.type === "radio" ) { + // we don't search against the document in case the element + // is disconnected from the DOM + var ancestor = this.element.parents().filter(":last"), + labelSelector = "label[for='" + this.element.attr("id") + "']"; + this.buttonElement = ancestor.find( labelSelector ); + if ( !this.buttonElement.length ) { + ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); + this.buttonElement = ancestor.filter( labelSelector ); + if ( !this.buttonElement.length ) { + this.buttonElement = ancestor.find( labelSelector ); + } + } + this.element.addClass( "ui-helper-hidden-accessible" ); + + var checked = this.element.is( ":checked" ); + if ( checked ) { + this.buttonElement.addClass( "ui-state-active" ); + } + this.buttonElement.attr( "aria-pressed", checked ); + } else { + this.buttonElement = this.element; + } + }, + + widget: function() { + return this.buttonElement; + }, + + destroy: function() { + this.element + .removeClass( "ui-helper-hidden-accessible" ); + this.buttonElement + .removeClass( baseClasses + " " + stateClasses + " " + typeClasses ) + .removeAttr( "role" ) + .removeAttr( "aria-pressed" ) + .html( this.buttonElement.find(".ui-button-text").html() ); + + if ( !this.hasTitle ) { + this.buttonElement.removeAttr( "title" ); + } + + $.Widget.prototype.destroy.call( this ); + }, + + _setOption: function( key, value ) { + $.Widget.prototype._setOption.apply( this, arguments ); + if ( key === "disabled" ) { + if ( value ) { + this.element.propAttr( "disabled", true ); + } else { + this.element.propAttr( "disabled", false ); + } + return; + } + this._resetButton(); + }, + + refresh: function() { + var isDisabled = this.element.is( ":disabled" ); + if ( isDisabled !== this.options.disabled ) { + this._setOption( "disabled", isDisabled ); + } + if ( this.type === "radio" ) { + radioGroup( this.element[0] ).each(function() { + if ( $( this ).is( ":checked" ) ) { + $( this ).button( "widget" ) + .addClass( "ui-state-active" ) + .attr( "aria-pressed", "true" ); + } else { + $( this ).button( "widget" ) + .removeClass( "ui-state-active" ) + .attr( "aria-pressed", "false" ); + } + }); + } else if ( this.type === "checkbox" ) { + if ( this.element.is( ":checked" ) ) { + this.buttonElement + .addClass( "ui-state-active" ) + .attr( "aria-pressed", "true" ); + } else { + this.buttonElement + .removeClass( "ui-state-active" ) + .attr( "aria-pressed", "false" ); + } + } + }, + + _resetButton: function() { + if ( this.type === "input" ) { + if ( this.options.label ) { + this.element.val( this.options.label ); + } + return; + } + var buttonElement = this.buttonElement.removeClass( typeClasses ), + buttonText = $( "<span></span>", this.element[0].ownerDocument ) + .addClass( "ui-button-text" ) + .html( this.options.label ) + .appendTo( buttonElement.empty() ) + .text(), + icons = this.options.icons, + multipleIcons = icons.primary && icons.secondary, + buttonClasses = []; + + if ( icons.primary || icons.secondary ) { + if ( this.options.text ) { + buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); + } + + if ( icons.primary ) { + buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); + } + + if ( icons.secondary ) { + buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); + } + + if ( !this.options.text ) { + buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); + + if ( !this.hasTitle ) { + buttonElement.attr( "title", buttonText ); + } + } + } else { + buttonClasses.push( "ui-button-text-only" ); + } + buttonElement.addClass( buttonClasses.join( " " ) ); + } +}); + +$.widget( "ui.buttonset", { + options: { + items: ":button, :submit, :reset, :checkbox, :radio, a, :data(button)" + }, + + _create: function() { + this.element.addClass( "ui-buttonset" ); + }, + + _init: function() { + this.refresh(); + }, + + _setOption: function( key, value ) { + if ( key === "disabled" ) { + this.buttons.button( "option", key, value ); + } + + $.Widget.prototype._setOption.apply( this, arguments ); + }, + + refresh: function() { + var rtl = this.element.css( "direction" ) === "rtl"; + + this.buttons = this.element.find( this.options.items ) + .filter( ":ui-button" ) + .button( "refresh" ) + .end() + .not( ":ui-button" ) + .button() + .end() + .map(function() { + return $( this ).button( "widget" )[ 0 ]; + }) + .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) + .filter( ":first" ) + .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) + .end() + .filter( ":last" ) + .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) + .end() + .end(); + }, + + destroy: function() { + this.element.removeClass( "ui-buttonset" ); + this.buttons + .map(function() { + return $( this ).button( "widget" )[ 0 ]; + }) + .removeClass( "ui-corner-left ui-corner-right" ) + .end() + .button( "destroy" ); + + $.Widget.prototype.destroy.call( this ); + } +}); + +}( jQuery ) ); + +(function( $, undefined ) { + +$.extend($.ui, { datepicker: { version: "1.8.20" } }); + +var PROP_NAME = 'datepicker'; +var dpuuid = new Date().getTime(); +var instActive; + +/* Date picker manager. + Use the singleton instance of this class, $.datepicker, to interact with the date picker. + Settings for (groups of) date pickers are maintained in an instance object, + allowing multiple different settings on the same page. */ + +function Datepicker() { + this.debug = false; // Change this to true to start debugging + this._curInst = null; // The current instance in use + this._keyEvent = false; // If the last event was a key event + this._disabledInputs = []; // List of date picker inputs that have been disabled + this._datepickerShowing = false; // True if the popup picker is showing , false if not + this._inDialog = false; // True if showing within a "dialog", false if not + this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division + this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class + this._appendClass = 'ui-datepicker-append'; // The name of the append marker class + this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class + this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class + this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class + this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class + this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class + this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class + this.regional = []; // Available regional settings, indexed by language code + this.regional[''] = { // Default regional settings + closeText: 'Done', // Display text for close link + prevText: 'Prev', // Display text for previous month link + nextText: 'Next', // Display text for next month link + currentText: 'Today', // Display text for current month link + monthNames: ['January','February','March','April','May','June', + 'July','August','September','October','November','December'], // Names of months for drop-down and formatting + monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting + dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting + dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting + dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday + weekHeader: 'Wk', // Column header for week of the year + dateFormat: 'mm/dd/yy', // See format options on parseDate + firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... + isRTL: false, // True if right-to-left language, false if left-to-right + showMonthAfterYear: false, // True if the year select precedes month, false for month then year + yearSuffix: '' // Additional text to append to the year in the month headers + }; + this._defaults = { // Global defaults for all the date picker instances + showOn: 'focus', // 'focus' for popup on focus, + // 'button' for trigger button, or 'both' for either + showAnim: 'fadeIn', // Name of jQuery animation for popup + showOptions: {}, // Options for enhanced animations + defaultDate: null, // Used when field is blank: actual date, + // +/-number for offset from today, null for today + appendText: '', // Display text following the input box, e.g. showing the format + buttonText: '...', // Text for trigger button + buttonImage: '', // URL for trigger button image + buttonImageOnly: false, // True if the image appears alone, false if it appears on a button + hideIfNoPrevNext: false, // True to hide next/previous month links + // if not applicable, false to just disable them + navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links + gotoCurrent: false, // True if today link goes back to current selection instead + changeMonth: false, // True if month can be selected directly, false if only prev/next + changeYear: false, // True if year can be selected directly, false if only prev/next + yearRange: 'c-10:c+10', // Range of years to display in drop-down, + // either relative to today's year (-nn:+nn), relative to currently displayed year + // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) + showOtherMonths: false, // True to show dates in other months, false to leave blank + selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable + showWeek: false, // True to show week of the year, false to not show it + calculateWeek: this.iso8601Week, // How to calculate the week of the year, + // takes a Date and returns the number of the week for it + shortYearCutoff: '+10', // Short year values < this are in the current century, + // > this are in the previous century, + // string value starting with '+' for current year + value + minDate: null, // The earliest selectable date, or null for no limit + maxDate: null, // The latest selectable date, or null for no limit + duration: 'fast', // Duration of display/closure + beforeShowDay: null, // Function that takes a date and returns an array with + // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', + // [2] = cell title (optional), e.g. $.datepicker.noWeekends + beforeShow: null, // Function that takes an input field and + // returns a set of custom settings for the date picker + onSelect: null, // Define a callback function when a date is selected + onChangeMonthYear: null, // Define a callback function when the month or year is changed + onClose: null, // Define a callback function when the datepicker is closed + numberOfMonths: 1, // Number of months to show at a time + showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) + stepMonths: 1, // Number of months to step back/forward + stepBigMonths: 12, // Number of months to step back/forward for the big links + altField: '', // Selector for an alternate field to store selected dates into + altFormat: '', // The date format to use for the alternate field + constrainInput: true, // The input is constrained by the current date format + showButtonPanel: false, // True to show button panel, false to not show it + autoSize: false, // True to size the input for the date format, false to leave as is + disabled: false // The initial disabled state + }; + $.extend(this._defaults, this.regional['']); + this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')); +} + +$.extend(Datepicker.prototype, { + /* Class name added to elements to indicate already configured with a date picker. */ + markerClassName: 'hasDatepicker', + + //Keep track of the maximum number of rows displayed (see #7043) + maxRows: 4, + + /* Debug logging (if enabled). */ + log: function () { + if (this.debug) + console.log.apply('', arguments); + }, + + // TODO rename to "widget" when switching to widget factory + _widgetDatepicker: function() { + return this.dpDiv; + }, + + /* Override the default settings for all instances of the date picker. + @param settings object - the new settings to use as defaults (anonymous object) + @return the manager object */ + setDefaults: function(settings) { + extendRemove(this._defaults, settings || {}); + return this; + }, + + /* Attach the date picker to a jQuery selection. + @param target element - the target input field or division or span + @param settings object - the new settings to use for this date picker instance (anonymous) */ + _attachDatepicker: function(target, settings) { + // check for settings on the control itself - in namespace 'date:' + var inlineSettings = null; + for (var attrName in this._defaults) { + var attrValue = target.getAttribute('date:' + attrName); + if (attrValue) { + inlineSettings = inlineSettings || {}; + try { + inlineSettings[attrName] = eval(attrValue); + } catch (err) { + inlineSettings[attrName] = attrValue; + } + } + } + var nodeName = target.nodeName.toLowerCase(); + var inline = (nodeName == 'div' || nodeName == 'span'); + if (!target.id) { + this.uuid += 1; + target.id = 'dp' + this.uuid; + } + var inst = this._newInst($(target), inline); + inst.settings = $.extend({}, settings || {}, inlineSettings || {}); + if (nodeName == 'input') { + this._connectDatepicker(target, inst); + } else if (inline) { + this._inlineDatepicker(target, inst); + } + }, + + /* Create a new instance object. */ + _newInst: function(target, inline) { + var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars + return {id: id, input: target, // associated target + selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection + drawMonth: 0, drawYear: 0, // month being drawn + inline: inline, // is datepicker inline or not + dpDiv: (!inline ? this.dpDiv : // presentation div + bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}; + }, + + /* Attach the date picker to an input field. */ + _connectDatepicker: function(target, inst) { + var input = $(target); + inst.append = $([]); + inst.trigger = $([]); + if (input.hasClass(this.markerClassName)) + return; + this._attachments(input, inst); + input.addClass(this.markerClassName).keydown(this._doKeyDown). + keypress(this._doKeyPress).keyup(this._doKeyUp). + bind("setData.datepicker", function(event, key, value) { + inst.settings[key] = value; + }).bind("getData.datepicker", function(event, key) { + return this._get(inst, key); + }); + this._autoSize(inst); + $.data(target, PROP_NAME, inst); + //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) + if( inst.settings.disabled ) { + this._disableDatepicker( target ); + } + }, + + /* Make attachments based on settings. */ + _attachments: function(input, inst) { + var appendText = this._get(inst, 'appendText'); + var isRTL = this._get(inst, 'isRTL'); + if (inst.append) + inst.append.remove(); + if (appendText) { + inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>'); + input[isRTL ? 'before' : 'after'](inst.append); + } + input.unbind('focus', this._showDatepicker); + if (inst.trigger) + inst.trigger.remove(); + var showOn = this._get(inst, 'showOn'); + if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field + input.focus(this._showDatepicker); + if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked + var buttonText = this._get(inst, 'buttonText'); + var buttonImage = this._get(inst, 'buttonImage'); + inst.trigger = $(this._get(inst, 'buttonImageOnly') ? + $('<img/>').addClass(this._triggerClass). + attr({ src: buttonImage, alt: buttonText, title: buttonText }) : + $('<button type="button"></button>').addClass(this._triggerClass). + html(buttonImage == '' ? buttonText : $('<img/>').attr( + { src:buttonImage, alt:buttonText, title:buttonText }))); + input[isRTL ? 'before' : 'after'](inst.trigger); + inst.trigger.click(function() { + if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0]) + $.datepicker._hideDatepicker(); + else if ($.datepicker._datepickerShowing && $.datepicker._lastInput != input[0]) { + $.datepicker._hideDatepicker(); + $.datepicker._showDatepicker(input[0]); + } else + $.datepicker._showDatepicker(input[0]); + return false; + }); + } + }, + + /* Apply the maximum length for the date format. */ + _autoSize: function(inst) { + if (this._get(inst, 'autoSize') && !inst.inline) { + var date = new Date(2009, 12 - 1, 20); // Ensure double digits + var dateFormat = this._get(inst, 'dateFormat'); + if (dateFormat.match(/[DM]/)) { + var findMax = function(names) { + var max = 0; + var maxI = 0; + for (var i = 0; i < names.length; i++) { + if (names[i].length > max) { + max = names[i].length; + maxI = i; + } + } + return maxI; + }; + date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? + 'monthNames' : 'monthNamesShort')))); + date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? + 'dayNames' : 'dayNamesShort'))) + 20 - date.getDay()); + } + inst.input.attr('size', this._formatDate(inst, date).length); + } + }, + + /* Attach an inline date picker to a div. */ + _inlineDatepicker: function(target, inst) { + var divSpan = $(target); + if (divSpan.hasClass(this.markerClassName)) + return; + divSpan.addClass(this.markerClassName).append(inst.dpDiv). + bind("setData.datepicker", function(event, key, value){ + inst.settings[key] = value; + }).bind("getData.datepicker", function(event, key){ + return this._get(inst, key); + }); + $.data(target, PROP_NAME, inst); + this._setDate(inst, this._getDefaultDate(inst), true); + this._updateDatepicker(inst); + this._updateAlternate(inst); + //If disabled option is true, disable the datepicker before showing it (see ticket #5665) + if( inst.settings.disabled ) { + this._disableDatepicker( target ); + } + // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements + // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height + inst.dpDiv.css( "display", "block" ); + }, + + /* Pop-up the date picker in a "dialog" box. + @param input element - ignored + @param date string or Date - the initial date to display + @param onSelect function - the function to call when a date is selected + @param settings object - update the dialog date picker instance's settings (anonymous object) + @param pos int[2] - coordinates for the dialog's position within the screen or + event - with x/y coordinates or + leave empty for default (screen centre) + @return the manager object */ + _dialogDatepicker: function(input, date, onSelect, settings, pos) { + var inst = this._dialogInst; // internal instance + if (!inst) { + this.uuid += 1; + var id = 'dp' + this.uuid; + this._dialogInput = $('<input type="text" id="' + id + + '" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'); + this._dialogInput.keydown(this._doKeyDown); + $('body').append(this._dialogInput); + inst = this._dialogInst = this._newInst(this._dialogInput, false); + inst.settings = {}; + $.data(this._dialogInput[0], PROP_NAME, inst); + } + extendRemove(inst.settings, settings || {}); + date = (date && date.constructor == Date ? this._formatDate(inst, date) : date); + this._dialogInput.val(date); + + this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); + if (!this._pos) { + var browserWidth = document.documentElement.clientWidth; + var browserHeight = document.documentElement.clientHeight; + var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; + var scrollY = document.documentElement.scrollTop || document.body.scrollTop; + this._pos = // should use actual width/height below + [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; + } + + // move input on screen for focus, but hidden behind dialog + this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px'); + inst.settings.onSelect = onSelect; + this._inDialog = true; + this.dpDiv.addClass(this._dialogClass); + this._showDatepicker(this._dialogInput[0]); + if ($.blockUI) + $.blockUI(this.dpDiv); + $.data(this._dialogInput[0], PROP_NAME, inst); + return this; + }, + + /* Detach a datepicker from its control. + @param target element - the target input field or division or span */ + _destroyDatepicker: function(target) { + var $target = $(target); + var inst = $.data(target, PROP_NAME); + if (!$target.hasClass(this.markerClassName)) { + return; + } + var nodeName = target.nodeName.toLowerCase(); + $.removeData(target, PROP_NAME); + if (nodeName == 'input') { + inst.append.remove(); + inst.trigger.remove(); + $target.removeClass(this.markerClassName). + unbind('focus', this._showDatepicker). + unbind('keydown', this._doKeyDown). + unbind('keypress', this._doKeyPress). + unbind('keyup', this._doKeyUp); + } else if (nodeName == 'div' || nodeName == 'span') + $target.removeClass(this.markerClassName).empty(); + }, + + /* Enable the date picker to a jQuery selection. + @param target element - the target input field or division or span */ + _enableDatepicker: function(target) { + var $target = $(target); + var inst = $.data(target, PROP_NAME); + if (!$target.hasClass(this.markerClassName)) { + return; + } + var nodeName = target.nodeName.toLowerCase(); + if (nodeName == 'input') { + target.disabled = false; + inst.trigger.filter('button'). + each(function() { this.disabled = false; }).end(). + filter('img').css({opacity: '1.0', cursor: ''}); + } + else if (nodeName == 'div' || nodeName == 'span') { + var inline = $target.children('.' + this._inlineClass); + inline.children().removeClass('ui-state-disabled'); + inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). + removeAttr("disabled"); + } + this._disabledInputs = $.map(this._disabledInputs, + function(value) { return (value == target ? null : value); }); // delete entry + }, + + /* Disable the date picker to a jQuery selection. + @param target element - the target input field or division or span */ + _disableDatepicker: function(target) { + var $target = $(target); + var inst = $.data(target, PROP_NAME); + if (!$target.hasClass(this.markerClassName)) { + return; + } + var nodeName = target.nodeName.toLowerCase(); + if (nodeName == 'input') { + target.disabled = true; + inst.trigger.filter('button'). + each(function() { this.disabled = true; }).end(). + filter('img').css({opacity: '0.5', cursor: 'default'}); + } + else if (nodeName == 'div' || nodeName == 'span') { + var inline = $target.children('.' + this._inlineClass); + inline.children().addClass('ui-state-disabled'); + inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). + attr("disabled", "disabled"); + } + this._disabledInputs = $.map(this._disabledInputs, + function(value) { return (value == target ? null : value); }); // delete entry + this._disabledInputs[this._disabledInputs.length] = target; + }, + + /* Is the first field in a jQuery collection disabled as a datepicker? + @param target element - the target input field or division or span + @return boolean - true if disabled, false if enabled */ + _isDisabledDatepicker: function(target) { + if (!target) { + return false; + } + for (var i = 0; i < this._disabledInputs.length; i++) { + if (this._disabledInputs[i] == target) + return true; + } + return false; + }, + + /* Retrieve the instance data for the target control. + @param target element - the target input field or division or span + @return object - the associated instance data + @throws error if a jQuery problem getting data */ + _getInst: function(target) { + try { + return $.data(target, PROP_NAME); + } + catch (err) { + throw 'Missing instance data for this datepicker'; + } + }, + + /* Update or retrieve the settings for a date picker attached to an input field or division. + @param target element - the target input field or division or span + @param name object - the new settings to update or + string - the name of the setting to change or retrieve, + when retrieving also 'all' for all instance settings or + 'defaults' for all global defaults + @param value any - the new value for the setting + (omit if above is an object or to retrieve a value) */ + _optionDatepicker: function(target, name, value) { + var inst = this._getInst(target); + if (arguments.length == 2 && typeof name == 'string') { + return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) : + (inst ? (name == 'all' ? $.extend({}, inst.settings) : + this._get(inst, name)) : null)); + } + var settings = name || {}; + if (typeof name == 'string') { + settings = {}; + settings[name] = value; + } + if (inst) { + if (this._curInst == inst) { + this._hideDatepicker(); + } + var date = this._getDateDatepicker(target, true); + var minDate = this._getMinMaxDate(inst, 'min'); + var maxDate = this._getMinMaxDate(inst, 'max'); + extendRemove(inst.settings, settings); + // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided + if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined) + inst.settings.minDate = this._formatDate(inst, minDate); + if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined) + inst.settings.maxDate = this._formatDate(inst, maxDate); + this._attachments($(target), inst); + this._autoSize(inst); + this._setDate(inst, date); + this._updateAlternate(inst); + this._updateDatepicker(inst); + } + }, + + // change method deprecated + _changeDatepicker: function(target, name, value) { + this._optionDatepicker(target, name, value); + }, + + /* Redraw the date picker attached to an input field or division. + @param target element - the target input field or division or span */ + _refreshDatepicker: function(target) { + var inst = this._getInst(target); + if (inst) { + this._updateDatepicker(inst); + } + }, + + /* Set the dates for a jQuery selection. + @param target element - the target input field or division or span + @param date Date - the new date */ + _setDateDatepicker: function(target, date) { + var inst = this._getInst(target); + if (inst) { + this._setDate(inst, date); + this._updateDatepicker(inst); + this._updateAlternate(inst); + } + }, + + /* Get the date(s) for the first entry in a jQuery selection. + @param target element - the target input field or division or span + @param noDefault boolean - true if no default date is to be used + @return Date - the current date */ + _getDateDatepicker: function(target, noDefault) { + var inst = this._getInst(target); + if (inst && !inst.inline) + this._setDateFromField(inst, noDefault); + return (inst ? this._getDate(inst) : null); + }, + + /* Handle keystrokes. */ + _doKeyDown: function(event) { + var inst = $.datepicker._getInst(event.target); + var handled = true; + var isRTL = inst.dpDiv.is('.ui-datepicker-rtl'); + inst._keyEvent = true; + if ($.datepicker._datepickerShowing) + switch (event.keyCode) { + case 9: $.datepicker._hideDatepicker(); + handled = false; + break; // hide on tab out + case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' + + $.datepicker._currentClass + ')', inst.dpDiv); + if (sel[0]) + $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); + var onSelect = $.datepicker._get(inst, 'onSelect'); + if (onSelect) { + var dateStr = $.datepicker._formatDate(inst); + + // trigger custom callback + onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); + } + else + $.datepicker._hideDatepicker(); + return false; // don't submit the form + break; // select the value on enter + case 27: $.datepicker._hideDatepicker(); + break; // hide on escape + case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? + -$.datepicker._get(inst, 'stepBigMonths') : + -$.datepicker._get(inst, 'stepMonths')), 'M'); + break; // previous month/year on page up/+ ctrl + case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? + +$.datepicker._get(inst, 'stepBigMonths') : + +$.datepicker._get(inst, 'stepMonths')), 'M'); + break; // next month/year on page down/+ ctrl + case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); + handled = event.ctrlKey || event.metaKey; + break; // clear on ctrl or command +end + case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); + handled = event.ctrlKey || event.metaKey; + break; // current on ctrl or command +home + case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); + handled = event.ctrlKey || event.metaKey; + // -1 day on ctrl or command +left + if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? + -$.datepicker._get(inst, 'stepBigMonths') : + -$.datepicker._get(inst, 'stepMonths')), 'M'); + // next month/year on alt +left on Mac + break; + case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); + handled = event.ctrlKey || event.metaKey; + break; // -1 week on ctrl or command +up + case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); + handled = event.ctrlKey || event.metaKey; + // +1 day on ctrl or command +right + if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? + +$.datepicker._get(inst, 'stepBigMonths') : + +$.datepicker._get(inst, 'stepMonths')), 'M'); + // next month/year on alt +right + break; + case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); + handled = event.ctrlKey || event.metaKey; + break; // +1 week on ctrl or command +down + default: handled = false; + } + else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home + $.datepicker._showDatepicker(this); + else { + handled = false; + } + if (handled) { + event.preventDefault(); + event.stopPropagation(); + } + }, + + /* Filter entered characters - based on date format. */ + _doKeyPress: function(event) { + var inst = $.datepicker._getInst(event.target); + if ($.datepicker._get(inst, 'constrainInput')) { + var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); + var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode); + return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1); + } + }, + + /* Synchronise manual entry and field/alternate field. */ + _doKeyUp: function(event) { + var inst = $.datepicker._getInst(event.target); + if (inst.input.val() != inst.lastVal) { + try { + var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), + (inst.input ? inst.input.val() : null), + $.datepicker._getFormatConfig(inst)); + if (date) { // only if valid + $.datepicker._setDateFromField(inst); + $.datepicker._updateAlternate(inst); + $.datepicker._updateDatepicker(inst); + } + } + catch (err) { + $.datepicker.log(err); + } + } + return true; + }, + + /* Pop-up the date picker for a given input field. + If false returned from beforeShow event handler do not show. + @param input element - the input field attached to the date picker or + event - if triggered by focus */ + _showDatepicker: function(input) { + input = input.target || input; + if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger + input = $('input', input.parentNode)[0]; + if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here + return; + var inst = $.datepicker._getInst(input); + if ($.datepicker._curInst && $.datepicker._curInst != inst) { + $.datepicker._curInst.dpDiv.stop(true, true); + if ( inst && $.datepicker._datepickerShowing ) { + $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); + } + } + var beforeShow = $.datepicker._get(inst, 'beforeShow'); + var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; + if(beforeShowSettings === false){ + //false + return; + } + extendRemove(inst.settings, beforeShowSettings); + inst.lastVal = null; + $.datepicker._lastInput = input; + $.datepicker._setDateFromField(inst); + if ($.datepicker._inDialog) // hide cursor + input.value = ''; + if (!$.datepicker._pos) { // position below input + $.datepicker._pos = $.datepicker._findPos(input); + $.datepicker._pos[1] += input.offsetHeight; // add the height + } + var isFixed = false; + $(input).parents().each(function() { + isFixed |= $(this).css('position') == 'fixed'; + return !isFixed; + }); + if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled + $.datepicker._pos[0] -= document.documentElement.scrollLeft; + $.datepicker._pos[1] -= document.documentElement.scrollTop; + } + var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; + $.datepicker._pos = null; + //to avoid flashes on Firefox + inst.dpDiv.empty(); + // determine sizing offscreen + inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); + $.datepicker._updateDatepicker(inst); + // fix width for dynamic number of date pickers + // and adjust position before showing + offset = $.datepicker._checkOffset(inst, offset, isFixed); + inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? + 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none', + left: offset.left + 'px', top: offset.top + 'px'}); + if (!inst.inline) { + var showAnim = $.datepicker._get(inst, 'showAnim'); + var duration = $.datepicker._get(inst, 'duration'); + var postProcess = function() { + var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only + if( !! cover.length ){ + var borders = $.datepicker._getBorders(inst.dpDiv); + cover.css({left: -borders[0], top: -borders[1], + width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}); + } + }; + inst.dpDiv.zIndex($(input).zIndex()+1); + $.datepicker._datepickerShowing = true; + if ($.effects && $.effects[showAnim]) + inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); + else + inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess); + if (!showAnim || !duration) + postProcess(); + if (inst.input.is(':visible') && !inst.input.is(':disabled')) + inst.input.focus(); + $.datepicker._curInst = inst; + } + }, + + /* Generate the date picker content. */ + _updateDatepicker: function(inst) { + var self = this; + self.maxRows = 4; //Reset the max number of rows being displayed (see #7043) + var borders = $.datepicker._getBorders(inst.dpDiv); + instActive = inst; // for delegate hover events + inst.dpDiv.empty().append(this._generateHTML(inst)); + var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only + if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6 + cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()}) + } + inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover(); + var numMonths = this._getNumberOfMonths(inst); + var cols = numMonths[1]; + var width = 17; + inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width(''); + if (cols > 1) + inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em'); + inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') + + 'Class']('ui-datepicker-multi'); + inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') + + 'Class']('ui-datepicker-rtl'); + if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input && + // #6694 - don't focus the input if it's already focused + // this breaks the change event in IE + inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement) + inst.input.focus(); + // deffered render of the years select (to avoid flashes on Firefox) + if( inst.yearshtml ){ + var origyearshtml = inst.yearshtml; + setTimeout(function(){ + //assure that inst.yearshtml didn't change. + if( origyearshtml === inst.yearshtml && inst.yearshtml ){ + inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml); + } + origyearshtml = inst.yearshtml = null; + }, 0); + } + }, + + /* Retrieve the size of left and top borders for an element. + @param elem (jQuery object) the element of interest + @return (number[2]) the left and top borders */ + _getBorders: function(elem) { + var convert = function(value) { + return {thin: 1, medium: 2, thick: 3}[value] || value; + }; + return [parseFloat(convert(elem.css('border-left-width'))), + parseFloat(convert(elem.css('border-top-width')))]; + }, + + /* Check positioning to remain on screen. */ + _checkOffset: function(inst, offset, isFixed) { + var dpWidth = inst.dpDiv.outerWidth(); + var dpHeight = inst.dpDiv.outerHeight(); + var inputWidth = inst.input ? inst.input.outerWidth() : 0; + var inputHeight = inst.input ? inst.input.outerHeight() : 0; + var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft(); + var viewHeight = document.documentElement.clientHeight + $(document).scrollTop(); + + offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0); + offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0; + offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; + + // now check if datepicker is showing outside window viewport - move to a better place if so. + offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? + Math.abs(offset.left + dpWidth - viewWidth) : 0); + offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? + Math.abs(dpHeight + inputHeight) : 0); + + return offset; + }, + + /* Find an object's position on the screen. */ + _findPos: function(obj) { + var inst = this._getInst(obj); + var isRTL = this._get(inst, 'isRTL'); + while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) { + obj = obj[isRTL ? 'previousSibling' : 'nextSibling']; + } + var position = $(obj).offset(); + return [position.left, position.top]; + }, + + /* Hide the date picker from view. + @param input element - the input field attached to the date picker */ + _hideDatepicker: function(input) { + var inst = this._curInst; + if (!inst || (input && inst != $.data(input, PROP_NAME))) + return; + if (this._datepickerShowing) { + var showAnim = this._get(inst, 'showAnim'); + var duration = this._get(inst, 'duration'); + var postProcess = function() { + $.datepicker._tidyDialog(inst); + }; + if ($.effects && $.effects[showAnim]) + inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess); + else + inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' : + (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess); + if (!showAnim) + postProcess(); + this._datepickerShowing = false; + var onClose = this._get(inst, 'onClose'); + if (onClose) + onClose.apply((inst.input ? inst.input[0] : null), + [(inst.input ? inst.input.val() : ''), inst]); + this._lastInput = null; + if (this._inDialog) { + this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' }); + if ($.blockUI) { + $.unblockUI(); + $('body').append(this.dpDiv); + } + } + this._inDialog = false; + } + }, + + /* Tidy up after a dialog display. */ + _tidyDialog: function(inst) { + inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); + }, + + /* Close date picker if clicked elsewhere. */ + _checkExternalClick: function(event) { + if (!$.datepicker._curInst) + return; + + var $target = $(event.target), + inst = $.datepicker._getInst($target[0]); + + if ( ( ( $target[0].id != $.datepicker._mainDivId && + $target.parents('#' + $.datepicker._mainDivId).length == 0 && + !$target.hasClass($.datepicker.markerClassName) && + !$target.closest("." + $.datepicker._triggerClass).length && + $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || + ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) ) + $.datepicker._hideDatepicker(); + }, + + /* Adjust one of the date sub-fields. */ + _adjustDate: function(id, offset, period) { + var target = $(id); + var inst = this._getInst(target[0]); + if (this._isDisabledDatepicker(target[0])) { + return; + } + this._adjustInstDate(inst, offset + + (period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning + period); + this._updateDatepicker(inst); + }, + + /* Action for current link. */ + _gotoToday: function(id) { + var target = $(id); + var inst = this._getInst(target[0]); + if (this._get(inst, 'gotoCurrent') && inst.currentDay) { + inst.selectedDay = inst.currentDay; + inst.drawMonth = inst.selectedMonth = inst.currentMonth; + inst.drawYear = inst.selectedYear = inst.currentYear; + } + else { + var date = new Date(); + inst.selectedDay = date.getDate(); + inst.drawMonth = inst.selectedMonth = date.getMonth(); + inst.drawYear = inst.selectedYear = date.getFullYear(); + } + this._notifyChange(inst); + this._adjustDate(target); + }, + + /* Action for selecting a new month/year. */ + _selectMonthYear: function(id, select, period) { + var target = $(id); + var inst = this._getInst(target[0]); + inst['selected' + (period == 'M' ? 'Month' : 'Year')] = + inst['draw' + (period == 'M' ? 'Month' : 'Year')] = + parseInt(select.options[select.selectedIndex].value,10); + this._notifyChange(inst); + this._adjustDate(target); + }, + + /* Action for selecting a day. */ + _selectDay: function(id, month, year, td) { + var target = $(id); + if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { + return; + } + var inst = this._getInst(target[0]); + inst.selectedDay = inst.currentDay = $('a', td).html(); + inst.selectedMonth = inst.currentMonth = month; + inst.selectedYear = inst.currentYear = year; + this._selectDate(id, this._formatDate(inst, + inst.currentDay, inst.currentMonth, inst.currentYear)); + }, + + /* Erase the input field and hide the date picker. */ + _clearDate: function(id) { + var target = $(id); + var inst = this._getInst(target[0]); + this._selectDate(target, ''); + }, + + /* Update the input field with the selected date. */ + _selectDate: function(id, dateStr) { + var target = $(id); + var inst = this._getInst(target[0]); + dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); + if (inst.input) + inst.input.val(dateStr); + this._updateAlternate(inst); + var onSelect = this._get(inst, 'onSelect'); + if (onSelect) + onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback + else if (inst.input) + inst.input.trigger('change'); // fire the change event + if (inst.inline) + this._updateDatepicker(inst); + else { + this._hideDatepicker(); + this._lastInput = inst.input[0]; + if (typeof(inst.input[0]) != 'object') + inst.input.focus(); // restore focus + this._lastInput = null; + } + }, + + /* Update any alternate field to synchronise with the main field. */ + _updateAlternate: function(inst) { + var altField = this._get(inst, 'altField'); + if (altField) { // update alternate field too + var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat'); + var date = this._getDate(inst); + var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); + $(altField).each(function() { $(this).val(dateStr); }); + } + }, + + /* Set as beforeShowDay function to prevent selection of weekends. + @param date Date - the date to customise + @return [boolean, string] - is this date selectable?, what is its CSS class? */ + noWeekends: function(date) { + var day = date.getDay(); + return [(day > 0 && day < 6), '']; + }, + + /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. + @param date Date - the date to get the week for + @return number - the number of the week within the year that contains this date */ + iso8601Week: function(date) { + var checkDate = new Date(date.getTime()); + // Find Thursday of this week starting on Monday + checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); + var time = checkDate.getTime(); + checkDate.setMonth(0); // Compare with Jan 1 + checkDate.setDate(1); + return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; + }, + + /* Parse a string value into a date object. + See formatDate below for the possible formats. + + @param format string - the expected format of the date + @param value string - the date in the above format + @param settings Object - attributes include: + shortYearCutoff number - the cutoff year for determining the century (optional) + dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) + dayNames string[7] - names of the days from Sunday (optional) + monthNamesShort string[12] - abbreviated names of the months (optional) + monthNames string[12] - names of the months (optional) + @return Date - the extracted date value or null if value is blank */ + parseDate: function (format, value, settings) { + if (format == null || value == null) + throw 'Invalid arguments'; + value = (typeof value == 'object' ? value.toString() : value + ''); + if (value == '') + return null; + var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff; + shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : + new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); + var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; + var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; + var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; + var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; + var year = -1; + var month = -1; + var day = -1; + var doy = -1; + var literal = false; + // Check whether a format character is doubled + var lookAhead = function(match) { + var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); + if (matches) + iFormat++; + return matches; + }; + // Extract a number from the string value + var getNumber = function(match) { + var isDoubled = lookAhead(match); + var size = (match == '@' ? 14 : (match == '!' ? 20 : + (match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2)))); + var digits = new RegExp('^\\d{1,' + size + '}'); + var num = value.substring(iValue).match(digits); + if (!num) + throw 'Missing number at position ' + iValue; + iValue += num[0].length; + return parseInt(num[0], 10); + }; + // Extract a name from the string value and convert to an index + var getName = function(match, shortNames, longNames) { + var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { + return [ [k, v] ]; + }).sort(function (a, b) { + return -(a[1].length - b[1].length); + }); + var index = -1; + $.each(names, function (i, pair) { + var name = pair[1]; + if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) { + index = pair[0]; + iValue += name.length; + return false; + } + }); + if (index != -1) + return index + 1; + else + throw 'Unknown name at position ' + iValue; + }; + // Confirm that a literal character matches the string value + var checkLiteral = function() { + if (value.charAt(iValue) != format.charAt(iFormat)) + throw 'Unexpected literal at position ' + iValue; + iValue++; + }; + var iValue = 0; + for (var iFormat = 0; iFormat < format.length; iFormat++) { + if (literal) + if (format.charAt(iFormat) == "'" && !lookAhead("'")) + literal = false; + else + checkLiteral(); + else + switch (format.charAt(iFormat)) { + case 'd': + day = getNumber('d'); + break; + case 'D': + getName('D', dayNamesShort, dayNames); + break; + case 'o': + doy = getNumber('o'); + break; + case 'm': + month = getNumber('m'); + break; + case 'M': + month = getName('M', monthNamesShort, monthNames); + break; + case 'y': + year = getNumber('y'); + break; + case '@': + var date = new Date(getNumber('@')); + year = date.getFullYear(); + month = date.getMonth() + 1; + day = date.getDate(); + break; + case '!': + var date = new Date((getNumber('!') - this._ticksTo1970) / 10000); + year = date.getFullYear(); + month = date.getMonth() + 1; + day = date.getDate(); + break; + case "'": + if (lookAhead("'")) + checkLiteral(); + else + literal = true; + break; + default: + checkLiteral(); + } + } + if (iValue < value.length){ + throw "Extra/unparsed characters found in date: " + value.substring(iValue); + } + if (year == -1) + year = new Date().getFullYear(); + else if (year < 100) + year += new Date().getFullYear() - new Date().getFullYear() % 100 + + (year <= shortYearCutoff ? 0 : -100); + if (doy > -1) { + month = 1; + day = doy; + do { + var dim = this._getDaysInMonth(year, month - 1); + if (day <= dim) + break; + month++; + day -= dim; + } while (true); + } + var date = this._daylightSavingAdjust(new Date(year, month - 1, day)); + if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) + throw 'Invalid date'; // E.g. 31/02/00 + return date; + }, + + /* Standard date formats. */ + ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) + COOKIE: 'D, dd M yy', + ISO_8601: 'yy-mm-dd', + RFC_822: 'D, d M y', + RFC_850: 'DD, dd-M-y', + RFC_1036: 'D, d M y', + RFC_1123: 'D, d M yy', + RFC_2822: 'D, d M yy', + RSS: 'D, d M y', // RFC 822 + TICKS: '!', + TIMESTAMP: '@', + W3C: 'yy-mm-dd', // ISO 8601 + + _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), + + /* Format a date object into a string value. + The format can be combinations of the following: + d - day of month (no leading zero) + dd - day of month (two digit) + o - day of year (no leading zeros) + oo - day of year (three digit) + D - day name short + DD - day name long + m - month of year (no leading zero) + mm - month of year (two digit) + M - month name short + MM - month name long + y - year (two digit) + yy - year (four digit) + @ - Unix timestamp (ms since 01/01/1970) + ! - Windows ticks (100ns since 01/01/0001) + '...' - literal text + '' - single quote + + @param format string - the desired format of the date + @param date Date - the date value to format + @param settings Object - attributes include: + dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) + dayNames string[7] - names of the days from Sunday (optional) + monthNamesShort string[12] - abbreviated names of the months (optional) + monthNames string[12] - names of the months (optional) + @return string - the date in the above format */ + formatDate: function (format, date, settings) { + if (!date) + return ''; + var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort; + var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames; + var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort; + var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames; + // Check whether a format character is doubled + var lookAhead = function(match) { + var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); + if (matches) + iFormat++; + return matches; + }; + // Format a number, with leading zero if necessary + var formatNumber = function(match, value, len) { + var num = '' + value; + if (lookAhead(match)) + while (num.length < len) + num = '0' + num; + return num; + }; + // Format a name, short or long as requested + var formatName = function(match, value, shortNames, longNames) { + return (lookAhead(match) ? longNames[value] : shortNames[value]); + }; + var output = ''; + var literal = false; + if (date) + for (var iFormat = 0; iFormat < format.length; iFormat++) { + if (literal) + if (format.charAt(iFormat) == "'" && !lookAhead("'")) + literal = false; + else + output += format.charAt(iFormat); + else + switch (format.charAt(iFormat)) { + case 'd': + output += formatNumber('d', date.getDate(), 2); + break; + case 'D': + output += formatName('D', date.getDay(), dayNamesShort, dayNames); + break; + case 'o': + output += formatNumber('o', + Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); + break; + case 'm': + output += formatNumber('m', date.getMonth() + 1, 2); + break; + case 'M': + output += formatName('M', date.getMonth(), monthNamesShort, monthNames); + break; + case 'y': + output += (lookAhead('y') ? date.getFullYear() : + (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100); + break; + case '@': + output += date.getTime(); + break; + case '!': + output += date.getTime() * 10000 + this._ticksTo1970; + break; + case "'": + if (lookAhead("'")) + output += "'"; + else + literal = true; + break; + default: + output += format.charAt(iFormat); + } + } + return output; + }, + + /* Extract all possible characters from the date format. */ + _possibleChars: function (format) { + var chars = ''; + var literal = false; + // Check whether a format character is doubled + var lookAhead = function(match) { + var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); + if (matches) + iFormat++; + return matches; + }; + for (var iFormat = 0; iFormat < format.length; iFormat++) + if (literal) + if (format.charAt(iFormat) == "'" && !lookAhead("'")) + literal = false; + else + chars += format.charAt(iFormat); + else + switch (format.charAt(iFormat)) { + case 'd': case 'm': case 'y': case '@': + chars += '0123456789'; + break; + case 'D': case 'M': + return null; // Accept anything + case "'": + if (lookAhead("'")) + chars += "'"; + else + literal = true; + break; + default: + chars += format.charAt(iFormat); + } + return chars; + }, + + /* Get a setting value, defaulting if necessary. */ + _get: function(inst, name) { + return inst.settings[name] !== undefined ? + inst.settings[name] : this._defaults[name]; + }, + + /* Parse existing date and initialise date picker. */ + _setDateFromField: function(inst, noDefault) { + if (inst.input.val() == inst.lastVal) { + return; + } + var dateFormat = this._get(inst, 'dateFormat'); + var dates = inst.lastVal = inst.input ? inst.input.val() : null; + var date, defaultDate; + date = defaultDate = this._getDefaultDate(inst); + var settings = this._getFormatConfig(inst); + try { + date = this.parseDate(dateFormat, dates, settings) || defaultDate; + } catch (event) { + this.log(event); + dates = (noDefault ? '' : dates); + } + inst.selectedDay = date.getDate(); + inst.drawMonth = inst.selectedMonth = date.getMonth(); + inst.drawYear = inst.selectedYear = date.getFullYear(); + inst.currentDay = (dates ? date.getDate() : 0); + inst.currentMonth = (dates ? date.getMonth() : 0); + inst.currentYear = (dates ? date.getFullYear() : 0); + this._adjustInstDate(inst); + }, + + /* Retrieve the default date shown on opening. */ + _getDefaultDate: function(inst) { + return this._restrictMinMax(inst, + this._determineDate(inst, this._get(inst, 'defaultDate'), new Date())); + }, + + /* A date may be specified as an exact value or a relative one. */ + _determineDate: function(inst, date, defaultDate) { + var offsetNumeric = function(offset) { + var date = new Date(); + date.setDate(date.getDate() + offset); + return date; + }; + var offsetString = function(offset) { + try { + return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'), + offset, $.datepicker._getFormatConfig(inst)); + } + catch (e) { + // Ignore + } + var date = (offset.toLowerCase().match(/^c/) ? + $.datepicker._getDate(inst) : null) || new Date(); + var year = date.getFullYear(); + var month = date.getMonth(); + var day = date.getDate(); + var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g; + var matches = pattern.exec(offset); + while (matches) { + switch (matches[2] || 'd') { + case 'd' : case 'D' : + day += parseInt(matches[1],10); break; + case 'w' : case 'W' : + day += parseInt(matches[1],10) * 7; break; + case 'm' : case 'M' : + month += parseInt(matches[1],10); + day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); + break; + case 'y': case 'Y' : + year += parseInt(matches[1],10); + day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); + break; + } + matches = pattern.exec(offset); + } + return new Date(year, month, day); + }; + var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) : + (typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); + newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate); + if (newDate) { + newDate.setHours(0); + newDate.setMinutes(0); + newDate.setSeconds(0); + newDate.setMilliseconds(0); + } + return this._daylightSavingAdjust(newDate); + }, + + /* Handle switch to/from daylight saving. + Hours may be non-zero on daylight saving cut-over: + > 12 when midnight changeover, but then cannot generate + midnight datetime, so jump to 1AM, otherwise reset. + @param date (Date) the date to check + @return (Date) the corrected date */ + _daylightSavingAdjust: function(date) { + if (!date) return null; + date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); + return date; + }, + + /* Set the date(s) directly. */ + _setDate: function(inst, date, noChange) { + var clear = !date; + var origMonth = inst.selectedMonth; + var origYear = inst.selectedYear; + var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); + inst.selectedDay = inst.currentDay = newDate.getDate(); + inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); + inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); + if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange) + this._notifyChange(inst); + this._adjustInstDate(inst); + if (inst.input) { + inst.input.val(clear ? '' : this._formatDate(inst)); + } + }, + + /* Retrieve the date(s) directly. */ + _getDate: function(inst) { + var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null : + this._daylightSavingAdjust(new Date( + inst.currentYear, inst.currentMonth, inst.currentDay))); + return startDate; + }, + + /* Generate the HTML for the current state of the date picker. */ + _generateHTML: function(inst) { + var today = new Date(); + today = this._daylightSavingAdjust( + new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time + var isRTL = this._get(inst, 'isRTL'); + var showButtonPanel = this._get(inst, 'showButtonPanel'); + var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext'); + var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat'); + var numMonths = this._getNumberOfMonths(inst); + var showCurrentAtPos = this._get(inst, 'showCurrentAtPos'); + var stepMonths = this._get(inst, 'stepMonths'); + var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1); + var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : + new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); + var minDate = this._getMinMaxDate(inst, 'min'); + var maxDate = this._getMinMaxDate(inst, 'max'); + var drawMonth = inst.drawMonth - showCurrentAtPos; + var drawYear = inst.drawYear; + if (drawMonth < 0) { + drawMonth += 12; + drawYear--; + } + if (maxDate) { + var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), + maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); + maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); + while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { + drawMonth--; + if (drawMonth < 0) { + drawMonth = 11; + drawYear--; + } + } + } + inst.drawMonth = drawMonth; + inst.drawYear = drawYear; + var prevText = this._get(inst, 'prevText'); + prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, + this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), + this._getFormatConfig(inst))); + var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? + '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid + + '.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' + + ' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' : + (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>')); + var nextText = this._get(inst, 'nextText'); + nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, + this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), + this._getFormatConfig(inst))); + var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? + '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid + + '.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' + + ' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' : + (hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>')); + var currentText = this._get(inst, 'currentText'); + var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today); + currentText = (!navigationAsDateFormat ? currentText : + this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); + var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid + + '.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : ''); + var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') + + (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid + + '.datepicker._gotoToday(\'#' + inst.id + '\');"' + + '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : ''; + var firstDay = parseInt(this._get(inst, 'firstDay'),10); + firstDay = (isNaN(firstDay) ? 0 : firstDay); + var showWeek = this._get(inst, 'showWeek'); + var dayNames = this._get(inst, 'dayNames'); + var dayNamesShort = this._get(inst, 'dayNamesShort'); + var dayNamesMin = this._get(inst, 'dayNamesMin'); + var monthNames = this._get(inst, 'monthNames'); + var monthNamesShort = this._get(inst, 'monthNamesShort'); + var beforeShowDay = this._get(inst, 'beforeShowDay'); + var showOtherMonths = this._get(inst, 'showOtherMonths'); + var selectOtherMonths = this._get(inst, 'selectOtherMonths'); + var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week; + var defaultDate = this._getDefaultDate(inst); + var html = ''; + for (var row = 0; row < numMonths[0]; row++) { + var group = ''; + this.maxRows = 4; + for (var col = 0; col < numMonths[1]; col++) { + var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); + var cornerClass = ' ui-corner-all'; + var calender = ''; + if (isMultiMonth) { + calender += '<div class="ui-datepicker-group'; + if (numMonths[1] > 1) + switch (col) { + case 0: calender += ' ui-datepicker-group-first'; + cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break; + case numMonths[1]-1: calender += ' ui-datepicker-group-last'; + cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break; + default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break; + } + calender += '">'; + } + calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' + + (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') + + (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') + + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, + row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers + '</div><table class="ui-datepicker-calendar"><thead>' + + '<tr>'; + var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : ''); + for (var dow = 0; dow < 7; dow++) { // days of the week + var day = (dow + firstDay) % 7; + thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' + + '<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>'; + } + calender += thead + '</tr></thead><tbody>'; + var daysInMonth = this._getDaysInMonth(drawYear, drawMonth); + if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth) + inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); + var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; + var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate + var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) + this.maxRows = numRows; + var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); + for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows + calender += '<tr>'; + var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + + this._get(inst, 'calculateWeek')(printDate) + '</td>'); + for (var dow = 0; dow < 7; dow++) { // create date picker days + var daySettings = (beforeShowDay ? + beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']); + var otherMonth = (printDate.getMonth() != drawMonth); + var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || + (minDate && printDate < minDate) || (maxDate && printDate > maxDate); + tbody += '<td class="' + + ((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends + (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months + ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key + (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? + // or defaultDate is current printedDate and defaultDate is selectedDate + ' ' + this._dayOverClass : '') + // highlight selected day + (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days + (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates + (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day + (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) + ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title + (unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' + + inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions + (otherMonth && !showOtherMonths ? ' ' : // display for other months + (unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' + + (printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') + + (printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day + (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months + '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date + printDate.setDate(printDate.getDate() + 1); + printDate = this._daylightSavingAdjust(printDate); + } + calender += tbody + '</tr>'; + } + drawMonth++; + if (drawMonth > 11) { + drawMonth = 0; + drawYear++; + } + calender += '</tbody></table>' + (isMultiMonth ? '</div>' + + ((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : ''); + group += calender; + } + html += group; + } + html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ? + '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); + inst._keyEvent = false; + return html; + }, + + /* Generate the month and year header. */ + _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, + secondary, monthNames, monthNamesShort) { + var changeMonth = this._get(inst, 'changeMonth'); + var changeYear = this._get(inst, 'changeYear'); + var showMonthAfterYear = this._get(inst, 'showMonthAfterYear'); + var html = '<div class="ui-datepicker-title">'; + var monthHtml = ''; + // month selection + if (secondary || !changeMonth) + monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>'; + else { + var inMinYear = (minDate && minDate.getFullYear() == drawYear); + var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear); + monthHtml += '<select class="ui-datepicker-month" ' + + 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' + + '>'; + for (var month = 0; month < 12; month++) { + if ((!inMinYear || month >= minDate.getMonth()) && + (!inMaxYear || month <= maxDate.getMonth())) + monthHtml += '<option value="' + month + '"' + + (month == drawMonth ? ' selected="selected"' : '') + + '>' + monthNamesShort[month] + '</option>'; + } + monthHtml += '</select>'; + } + if (!showMonthAfterYear) + html += monthHtml + (secondary || !(changeMonth && changeYear) ? ' ' : ''); + // year selection + if ( !inst.yearshtml ) { + inst.yearshtml = ''; + if (secondary || !changeYear) + html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; + else { + // determine range of years to display + var years = this._get(inst, 'yearRange').split(':'); + var thisYear = new Date().getFullYear(); + var determineYear = function(value) { + var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) : + (value.match(/[+-].*/) ? thisYear + parseInt(value, 10) : + parseInt(value, 10))); + return (isNaN(year) ? thisYear : year); + }; + var year = determineYear(years[0]); + var endYear = Math.max(year, determineYear(years[1] || '')); + year = (minDate ? Math.max(year, minDate.getFullYear()) : year); + endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); + inst.yearshtml += '<select class="ui-datepicker-year" ' + + 'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' + + '>'; + for (; year <= endYear; year++) { + inst.yearshtml += '<option value="' + year + '"' + + (year == drawYear ? ' selected="selected"' : '') + + '>' + year + '</option>'; + } + inst.yearshtml += '</select>'; + + html += inst.yearshtml; + inst.yearshtml = null; + } + } + html += this._get(inst, 'yearSuffix'); + if (showMonthAfterYear) + html += (secondary || !(changeMonth && changeYear) ? ' ' : '') + monthHtml; + html += '</div>'; // Close datepicker_header + return html; + }, + + /* Adjust one of the date sub-fields. */ + _adjustInstDate: function(inst, offset, period) { + var year = inst.drawYear + (period == 'Y' ? offset : 0); + var month = inst.drawMonth + (period == 'M' ? offset : 0); + var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + + (period == 'D' ? offset : 0); + var date = this._restrictMinMax(inst, + this._daylightSavingAdjust(new Date(year, month, day))); + inst.selectedDay = date.getDate(); + inst.drawMonth = inst.selectedMonth = date.getMonth(); + inst.drawYear = inst.selectedYear = date.getFullYear(); + if (period == 'M' || period == 'Y') + this._notifyChange(inst); + }, + + /* Ensure a date is within any min/max bounds. */ + _restrictMinMax: function(inst, date) { + var minDate = this._getMinMaxDate(inst, 'min'); + var maxDate = this._getMinMaxDate(inst, 'max'); + var newDate = (minDate && date < minDate ? minDate : date); + newDate = (maxDate && newDate > maxDate ? maxDate : newDate); + return newDate; + }, + + /* Notify change of month/year. */ + _notifyChange: function(inst) { + var onChange = this._get(inst, 'onChangeMonthYear'); + if (onChange) + onChange.apply((inst.input ? inst.input[0] : null), + [inst.selectedYear, inst.selectedMonth + 1, inst]); + }, + + /* Determine the number of months to show. */ + _getNumberOfMonths: function(inst) { + var numMonths = this._get(inst, 'numberOfMonths'); + return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); + }, + + /* Determine the current maximum date - ensure no time components are set. */ + _getMinMaxDate: function(inst, minMax) { + return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); + }, + + /* Find the number of days in a given month. */ + _getDaysInMonth: function(year, month) { + return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); + }, + + /* Find the day of the week of the first of a month. */ + _getFirstDayOfMonth: function(year, month) { + return new Date(year, month, 1).getDay(); + }, + + /* Determines if we should allow a "next/prev" month display change. */ + _canAdjustMonth: function(inst, offset, curYear, curMonth) { + var numMonths = this._getNumberOfMonths(inst); + var date = this._daylightSavingAdjust(new Date(curYear, + curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); + if (offset < 0) + date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); + return this._isInRange(inst, date); + }, + + /* Is the given date in the accepted range? */ + _isInRange: function(inst, date) { + var minDate = this._getMinMaxDate(inst, 'min'); + var maxDate = this._getMinMaxDate(inst, 'max'); + return ((!minDate || date.getTime() >= minDate.getTime()) && + (!maxDate || date.getTime() <= maxDate.getTime())); + }, + + /* Provide the configuration settings for formatting/parsing. */ + _getFormatConfig: function(inst) { + var shortYearCutoff = this._get(inst, 'shortYearCutoff'); + shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff : + new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); + return {shortYearCutoff: shortYearCutoff, + dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'), + monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')}; + }, + + /* Format the given date for display. */ + _formatDate: function(inst, day, month, year) { + if (!day) { + inst.currentDay = inst.selectedDay; + inst.currentMonth = inst.selectedMonth; + inst.currentYear = inst.selectedYear; + } + var date = (day ? (typeof day == 'object' ? day : + this._daylightSavingAdjust(new Date(year, month, day))) : + this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); + return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst)); + } +}); + +/* + * Bind hover events for datepicker elements. + * Done via delegate so the binding only occurs once in the lifetime of the parent div. + * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. + */ +function bindHover(dpDiv) { + var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; + return dpDiv.bind('mouseout', function(event) { + var elem = $( event.target ).closest( selector ); + if ( !elem.length ) { + return; + } + elem.removeClass( "ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover" ); + }) + .bind('mouseover', function(event) { + var elem = $( event.target ).closest( selector ); + if ($.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0]) || + !elem.length ) { + return; + } + elem.parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); + elem.addClass('ui-state-hover'); + if (elem.hasClass('ui-datepicker-prev')) elem.addClass('ui-datepicker-prev-hover'); + if (elem.hasClass('ui-datepicker-next')) elem.addClass('ui-datepicker-next-hover'); + }); +} + +/* jQuery extend now ignores nulls! */ +function extendRemove(target, props) { + $.extend(target, props); + for (var name in props) + if (props[name] == null || props[name] == undefined) + target[name] = props[name]; + return target; +}; + +/* Determine whether an object is an array. */ +function isArray(a) { + return (a && (($.browser.safari && typeof a == 'object' && a.length) || + (a.constructor && a.constructor.toString().match(/\Array\(\)/)))); +}; + +/* Invoke the datepicker functionality. + @param options string - a command, optionally followed by additional parameters or + Object - settings for attaching new datepicker functionality + @return jQuery object */ +$.fn.datepicker = function(options){ + + /* Verify an empty collection wasn't passed - Fixes #6976 */ + if ( !this.length ) { + return this; + } + + /* Initialise the date picker. */ + if (!$.datepicker.initialized) { + $(document).mousedown($.datepicker._checkExternalClick). + find('body').append($.datepicker.dpDiv); + $.datepicker.initialized = true; + } + + var otherArgs = Array.prototype.slice.call(arguments, 1); + if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget')) + return $.datepicker['_' + options + 'Datepicker']. + apply($.datepicker, [this[0]].concat(otherArgs)); + if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string') + return $.datepicker['_' + options + 'Datepicker']. + apply($.datepicker, [this[0]].concat(otherArgs)); + return this.each(function() { + typeof options == 'string' ? + $.datepicker['_' + options + 'Datepicker']. + apply($.datepicker, [this].concat(otherArgs)) : + $.datepicker._attachDatepicker(this, options); + }); +}; + +$.datepicker = new Datepicker(); // singleton instance +$.datepicker.initialized = false; +$.datepicker.uuid = new Date().getTime(); +$.datepicker.version = "1.8.20"; + +// Workaround for #4055 +// Add another global to avoid noConflict issues with inline event handlers +window['DP_jQuery_' + dpuuid] = $; + +})(jQuery); + +(function( $, undefined ) { + +var uiDialogClasses = + 'ui-dialog ' + + 'ui-widget ' + + 'ui-widget-content ' + + 'ui-corner-all ', + sizeRelatedOptions = { + buttons: true, + height: true, + maxHeight: true, + maxWidth: true, + minHeight: true, + minWidth: true, + width: true + }, + resizableRelatedOptions = { + maxHeight: true, + maxWidth: true, + minHeight: true, + minWidth: true + }, + // support for jQuery 1.3.2 - handle common attrFn methods for dialog + attrFn = $.attrFn || { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true, + click: true + }; + +$.widget("ui.dialog", { + options: { + autoOpen: true, + buttons: {}, + closeOnEscape: true, + closeText: 'close', + dialogClass: '', + draggable: true, + hide: null, + height: 'auto', + maxHeight: false, + maxWidth: false, + minHeight: 150, + minWidth: 150, + modal: false, + position: { + my: 'center', + at: 'center', + collision: 'fit', + // ensure that the titlebar is never outside the document + using: function(pos) { + var topOffset = $(this).css(pos).offset().top; + if (topOffset < 0) { + $(this).css('top', pos.top - topOffset); + } + } + }, + resizable: true, + show: null, + stack: true, + title: '', + width: 300, + zIndex: 1000 + }, + + _create: function() { + this.originalTitle = this.element.attr('title'); + // #5742 - .attr() might return a DOMElement + if ( typeof this.originalTitle !== "string" ) { + this.originalTitle = ""; + } + + this.options.title = this.options.title || this.originalTitle; + var self = this, + options = self.options, + + title = options.title || ' ', + titleId = $.ui.dialog.getTitleId(self.element), + + uiDialog = (self.uiDialog = $('<div></div>')) + .appendTo(document.body) + .hide() + .addClass(uiDialogClasses + options.dialogClass) + .css({ + zIndex: options.zIndex + }) + // setting tabIndex makes the div focusable + // setting outline to 0 prevents a border on focus in Mozilla + .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { + if (options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && + event.keyCode === $.ui.keyCode.ESCAPE) { + + self.close(event); + event.preventDefault(); + } + }) + .attr({ + role: 'dialog', + 'aria-labelledby': titleId + }) + .mousedown(function(event) { + self.moveToTop(false, event); + }), + + uiDialogContent = self.element + .show() + .removeAttr('title') + .addClass( + 'ui-dialog-content ' + + 'ui-widget-content') + .appendTo(uiDialog), + + uiDialogTitlebar = (self.uiDialogTitlebar = $('<div></div>')) + .addClass( + 'ui-dialog-titlebar ' + + 'ui-widget-header ' + + 'ui-corner-all ' + + 'ui-helper-clearfix' + ) + .prependTo(uiDialog), + + uiDialogTitlebarClose = $('<a href="#"></a>') + .addClass( + 'ui-dialog-titlebar-close ' + + 'ui-corner-all' + ) + .attr('role', 'button') + .hover( + function() { + uiDialogTitlebarClose.addClass('ui-state-hover'); + }, + function() { + uiDialogTitlebarClose.removeClass('ui-state-hover'); + } + ) + .focus(function() { + uiDialogTitlebarClose.addClass('ui-state-focus'); + }) + .blur(function() { + uiDialogTitlebarClose.removeClass('ui-state-focus'); + }) + .click(function(event) { + self.close(event); + return false; + }) + .appendTo(uiDialogTitlebar), + + uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('<span></span>')) + .addClass( + 'ui-icon ' + + 'ui-icon-closethick' + ) + .text(options.closeText) + .appendTo(uiDialogTitlebarClose), + + uiDialogTitle = $('<span></span>') + .addClass('ui-dialog-title') + .attr('id', titleId) + .html(title) + .prependTo(uiDialogTitlebar); + + //handling of deprecated beforeclose (vs beforeClose) option + //Ticket #4669 http://dev.jqueryui.com/ticket/4669 + //TODO: remove in 1.9pre + if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) { + options.beforeClose = options.beforeclose; + } + + uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); + + if (options.draggable && $.fn.draggable) { + self._makeDraggable(); + } + if (options.resizable && $.fn.resizable) { + self._makeResizable(); + } + + self._createButtons(options.buttons); + self._isOpen = false; + + if ($.fn.bgiframe) { + uiDialog.bgiframe(); + } + }, + + _init: function() { + if ( this.options.autoOpen ) { + this.open(); + } + }, + + destroy: function() { + var self = this; + + if (self.overlay) { + self.overlay.destroy(); + } + self.uiDialog.hide(); + self.element + .unbind('.dialog') + .removeData('dialog') + .removeClass('ui-dialog-content ui-widget-content') + .hide().appendTo('body'); + self.uiDialog.remove(); + + if (self.originalTitle) { + self.element.attr('title', self.originalTitle); + } + + return self; + }, + + widget: function() { + return this.uiDialog; + }, + + close: function(event) { + var self = this, + maxZ, thisZ; + + if (false === self._trigger('beforeClose', event)) { + return; + } + + if (self.overlay) { + self.overlay.destroy(); + } + self.uiDialog.unbind('keypress.ui-dialog'); + + self._isOpen = false; + + if (self.options.hide) { + self.uiDialog.hide(self.options.hide, function() { + self._trigger('close', event); + }); + } else { + self.uiDialog.hide(); + self._trigger('close', event); + } + + $.ui.dialog.overlay.resize(); + + // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) + if (self.options.modal) { + maxZ = 0; + $('.ui-dialog').each(function() { + if (this !== self.uiDialog[0]) { + thisZ = $(this).css('z-index'); + if(!isNaN(thisZ)) { + maxZ = Math.max(maxZ, thisZ); + } + } + }); + $.ui.dialog.maxZ = maxZ; + } + + return self; + }, + + isOpen: function() { + return this._isOpen; + }, + + // the force parameter allows us to move modal dialogs to their correct + // position on open + moveToTop: function(force, event) { + var self = this, + options = self.options, + saveScroll; + + if ((options.modal && !force) || + (!options.stack && !options.modal)) { + return self._trigger('focus', event); + } + + if (options.zIndex > $.ui.dialog.maxZ) { + $.ui.dialog.maxZ = options.zIndex; + } + if (self.overlay) { + $.ui.dialog.maxZ += 1; + self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ); + } + + //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. + // http://ui.jquery.com/bugs/ticket/3193 + saveScroll = { scrollTop: self.element.scrollTop(), scrollLeft: self.element.scrollLeft() }; + $.ui.dialog.maxZ += 1; + self.uiDialog.css('z-index', $.ui.dialog.maxZ); + self.element.attr(saveScroll); + self._trigger('focus', event); + + return self; + }, + + open: function() { + if (this._isOpen) { return; } + + var self = this, + options = self.options, + uiDialog = self.uiDialog; + + self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null; + self._size(); + self._position(options.position); + uiDialog.show(options.show); + self.moveToTop(true); + + // prevent tabbing out of modal dialogs + if ( options.modal ) { + uiDialog.bind( "keydown.ui-dialog", function( event ) { + if ( event.keyCode !== $.ui.keyCode.TAB ) { + return; + } + + var tabbables = $(':tabbable', this), + first = tabbables.filter(':first'), + last = tabbables.filter(':last'); + + if (event.target === last[0] && !event.shiftKey) { + first.focus(1); + return false; + } else if (event.target === first[0] && event.shiftKey) { + last.focus(1); + return false; + } + }); + } + + // set focus to the first tabbable element in the content area or the first button + // if there are no tabbable elements, set focus on the dialog itself + $(self.element.find(':tabbable').get().concat( + uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat( + uiDialog.get()))).eq(0).focus(); + + self._isOpen = true; + self._trigger('open'); + + return self; + }, + + _createButtons: function(buttons) { + var self = this, + hasButtons = false, + uiDialogButtonPane = $('<div></div>') + .addClass( + 'ui-dialog-buttonpane ' + + 'ui-widget-content ' + + 'ui-helper-clearfix' + ), + uiButtonSet = $( "<div></div>" ) + .addClass( "ui-dialog-buttonset" ) + .appendTo( uiDialogButtonPane ); + + // if we already have a button pane, remove it + self.uiDialog.find('.ui-dialog-buttonpane').remove(); + + if (typeof buttons === 'object' && buttons !== null) { + $.each(buttons, function() { + return !(hasButtons = true); + }); + } + if (hasButtons) { + $.each(buttons, function(name, props) { + props = $.isFunction( props ) ? + { click: props, text: name } : + props; + var button = $('<button type="button"></button>') + .click(function() { + props.click.apply(self.element[0], arguments); + }) + .appendTo(uiButtonSet); + // can't use .attr( props, true ) with jQuery 1.3.2. + $.each( props, function( key, value ) { + if ( key === "click" ) { + return; + } + if ( key in attrFn ) { + button[ key ]( value ); + } else { + button.attr( key, value ); + } + }); + if ($.fn.button) { + button.button(); + } + }); + uiDialogButtonPane.appendTo(self.uiDialog); + } + }, + + _makeDraggable: function() { + var self = this, + options = self.options, + doc = $(document), + heightBeforeDrag; + + function filteredUi(ui) { + return { + position: ui.position, + offset: ui.offset + }; + } + + self.uiDialog.draggable({ + cancel: '.ui-dialog-content, .ui-dialog-titlebar-close', + handle: '.ui-dialog-titlebar', + containment: 'document', + start: function(event, ui) { + heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height(); + $(this).height($(this).height()).addClass("ui-dialog-dragging"); + self._trigger('dragStart', event, filteredUi(ui)); + }, + drag: function(event, ui) { + self._trigger('drag', event, filteredUi(ui)); + }, + stop: function(event, ui) { + options.position = [ui.position.left - doc.scrollLeft(), + ui.position.top - doc.scrollTop()]; + $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); + self._trigger('dragStop', event, filteredUi(ui)); + $.ui.dialog.overlay.resize(); + } + }); + }, + + _makeResizable: function(handles) { + handles = (handles === undefined ? this.options.resizable : handles); + var self = this, + options = self.options, + // .ui-resizable has position: relative defined in the stylesheet + // but dialogs have to use absolute or fixed positioning + position = self.uiDialog.css('position'), + resizeHandles = (typeof handles === 'string' ? + handles : + 'n,e,s,w,se,sw,ne,nw' + ); + + function filteredUi(ui) { + return { + originalPosition: ui.originalPosition, + originalSize: ui.originalSize, + position: ui.position, + size: ui.size + }; + } + + self.uiDialog.resizable({ + cancel: '.ui-dialog-content', + containment: 'document', + alsoResize: self.element, + maxWidth: options.maxWidth, + maxHeight: options.maxHeight, + minWidth: options.minWidth, + minHeight: self._minHeight(), + handles: resizeHandles, + start: function(event, ui) { + $(this).addClass("ui-dialog-resizing"); + self._trigger('resizeStart', event, filteredUi(ui)); + }, + resize: function(event, ui) { + self._trigger('resize', event, filteredUi(ui)); + }, + stop: function(event, ui) { + $(this).removeClass("ui-dialog-resizing"); + options.height = $(this).height(); + options.width = $(this).width(); + self._trigger('resizeStop', event, filteredUi(ui)); + $.ui.dialog.overlay.resize(); + } + }) + .css('position', position) + .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); + }, + + _minHeight: function() { + var options = this.options; + + if (options.height === 'auto') { + return options.minHeight; + } else { + return Math.min(options.minHeight, options.height); + } + }, + + _position: function(position) { + var myAt = [], + offset = [0, 0], + isVisible; + + if (position) { + // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( + // if (typeof position == 'string' || $.isArray(position)) { + // myAt = $.isArray(position) ? position : position.split(' '); + + if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) { + myAt = position.split ? position.split(' ') : [position[0], position[1]]; + if (myAt.length === 1) { + myAt[1] = myAt[0]; + } + + $.each(['left', 'top'], function(i, offsetPosition) { + if (+myAt[i] === myAt[i]) { + offset[i] = myAt[i]; + myAt[i] = offsetPosition; + } + }); + + position = { + my: myAt.join(" "), + at: myAt.join(" "), + offset: offset.join(" ") + }; + } + + position = $.extend({}, $.ui.dialog.prototype.options.position, position); + } else { + position = $.ui.dialog.prototype.options.position; + } + + // need to show the dialog to get the actual offset in the position plugin + isVisible = this.uiDialog.is(':visible'); + if (!isVisible) { + this.uiDialog.show(); + } + this.uiDialog + // workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781 + .css({ top: 0, left: 0 }) + .position($.extend({ of: window }, position)); + if (!isVisible) { + this.uiDialog.hide(); + } + }, + + _setOptions: function( options ) { + var self = this, + resizableOptions = {}, + resize = false; + + $.each( options, function( key, value ) { + self._setOption( key, value ); + + if ( key in sizeRelatedOptions ) { + resize = true; + } + if ( key in resizableRelatedOptions ) { + resizableOptions[ key ] = value; + } + }); + + if ( resize ) { + this._size(); + } + if ( this.uiDialog.is( ":data(resizable)" ) ) { + this.uiDialog.resizable( "option", resizableOptions ); + } + }, + + _setOption: function(key, value){ + var self = this, + uiDialog = self.uiDialog; + + switch (key) { + //handling of deprecated beforeclose (vs beforeClose) option + //Ticket #4669 http://dev.jqueryui.com/ticket/4669 + //TODO: remove in 1.9pre + case "beforeclose": + key = "beforeClose"; + break; + case "buttons": + self._createButtons(value); + break; + case "closeText": + // ensure that we always pass a string + self.uiDialogTitlebarCloseText.text("" + value); + break; + case "dialogClass": + uiDialog + .removeClass(self.options.dialogClass) + .addClass(uiDialogClasses + value); + break; + case "disabled": + if (value) { + uiDialog.addClass('ui-dialog-disabled'); + } else { + uiDialog.removeClass('ui-dialog-disabled'); + } + break; + case "draggable": + var isDraggable = uiDialog.is( ":data(draggable)" ); + if ( isDraggable && !value ) { + uiDialog.draggable( "destroy" ); + } + + if ( !isDraggable && value ) { + self._makeDraggable(); + } + break; + case "position": + self._position(value); + break; + case "resizable": + // currently resizable, becoming non-resizable + var isResizable = uiDialog.is( ":data(resizable)" ); + if (isResizable && !value) { + uiDialog.resizable('destroy'); + } + + // currently resizable, changing handles + if (isResizable && typeof value === 'string') { + uiDialog.resizable('option', 'handles', value); + } + + // currently non-resizable, becoming resizable + if (!isResizable && value !== false) { + self._makeResizable(value); + } + break; + case "title": + // convert whatever was passed in o a string, for html() to not throw up + $(".ui-dialog-title", self.uiDialogTitlebar).html("" + (value || ' ')); + break; + } + + $.Widget.prototype._setOption.apply(self, arguments); + }, + + _size: function() { + /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content + * divs will both have width and height set, so we need to reset them + */ + var options = this.options, + nonContentHeight, + minContentHeight, + isVisible = this.uiDialog.is( ":visible" ); + + // reset content sizing + this.element.show().css({ + width: 'auto', + minHeight: 0, + height: 0 + }); + + if (options.minWidth > options.width) { + options.width = options.minWidth; + } + + // reset wrapper sizing + // determine the height of all the non-content elements + nonContentHeight = this.uiDialog.css({ + height: 'auto', + width: options.width + }) + .height(); + minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); + + if ( options.height === "auto" ) { + // only needed for IE6 support + if ( $.support.minHeight ) { + this.element.css({ + minHeight: minContentHeight, + height: "auto" + }); + } else { + this.uiDialog.show(); + var autoHeight = this.element.css( "height", "auto" ).height(); + if ( !isVisible ) { + this.uiDialog.hide(); + } + this.element.height( Math.max( autoHeight, minContentHeight ) ); + } + } else { + this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); + } + + if (this.uiDialog.is(':data(resizable)')) { + this.uiDialog.resizable('option', 'minHeight', this._minHeight()); + } + } +}); + +$.extend($.ui.dialog, { + version: "1.8.20", + + uuid: 0, + maxZ: 0, + + getTitleId: function($el) { + var id = $el.attr('id'); + if (!id) { + this.uuid += 1; + id = this.uuid; + } + return 'ui-dialog-title-' + id; + }, + + overlay: function(dialog) { + this.$el = $.ui.dialog.overlay.create(dialog); + } +}); + +$.extend($.ui.dialog.overlay, { + instances: [], + // reuse old instances due to IE memory leak with alpha transparency (see #5185) + oldInstances: [], + maxZ: 0, + events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), + function(event) { return event + '.dialog-overlay'; }).join(' '), + create: function(dialog) { + if (this.instances.length === 0) { + // prevent use of anchors and inputs + // we use a setTimeout in case the overlay is created from an + // event that we're going to be cancelling (see #2804) + setTimeout(function() { + // handle $(el).dialog().dialog('close') (see #4065) + if ($.ui.dialog.overlay.instances.length) { + $(document).bind($.ui.dialog.overlay.events, function(event) { + // stop events if the z-index of the target is < the z-index of the overlay + // we cannot return true when we don't want to cancel the event (#3523) + if ($(event.target).zIndex() < $.ui.dialog.overlay.maxZ) { + return false; + } + }); + } + }, 1); + + // allow closing by pressing the escape key + $(document).bind('keydown.dialog-overlay', function(event) { + if (dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && + event.keyCode === $.ui.keyCode.ESCAPE) { + + dialog.close(event); + event.preventDefault(); + } + }); + + // handle window resize + $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); + } + + var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay')) + .appendTo(document.body) + .css({ + width: this.width(), + height: this.height() + }); + + if ($.fn.bgiframe) { + $el.bgiframe(); + } + + this.instances.push($el); + return $el; + }, + + destroy: function($el) { + var indexOf = $.inArray($el, this.instances); + if (indexOf != -1){ + this.oldInstances.push(this.instances.splice(indexOf, 1)[0]); + } + + if (this.instances.length === 0) { + $([document, window]).unbind('.dialog-overlay'); + } + + $el.remove(); + + // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) + var maxZ = 0; + $.each(this.instances, function() { + maxZ = Math.max(maxZ, this.css('z-index')); + }); + this.maxZ = maxZ; + }, + + height: function() { + var scrollHeight, + offsetHeight; + // handle IE 6 + if ($.browser.msie && $.browser.version < 7) { + scrollHeight = Math.max( + document.documentElement.scrollHeight, + document.body.scrollHeight + ); + offsetHeight = Math.max( + document.documentElement.offsetHeight, + document.body.offsetHeight + ); + + if (scrollHeight < offsetHeight) { + return $(window).height() + 'px'; + } else { + return scrollHeight + 'px'; + } + // handle "good" browsers + } else { + return $(document).height() + 'px'; + } + }, + + width: function() { + var scrollWidth, + offsetWidth; + // handle IE + if ( $.browser.msie ) { + scrollWidth = Math.max( + document.documentElement.scrollWidth, + document.body.scrollWidth + ); + offsetWidth = Math.max( + document.documentElement.offsetWidth, + document.body.offsetWidth + ); + + if (scrollWidth < offsetWidth) { + return $(window).width() + 'px'; + } else { + return scrollWidth + 'px'; + } + // handle "good" browsers + } else { + return $(document).width() + 'px'; + } + }, + + resize: function() { + /* If the dialog is draggable and the user drags it past the + * right edge of the window, the document becomes wider so we + * need to stretch the overlay. If the user then drags the + * dialog back to the left, the document will become narrower, + * so we need to shrink the overlay to the appropriate size. + * This is handled by shrinking the overlay before setting it + * to the full document size. + */ + var $overlays = $([]); + $.each($.ui.dialog.overlay.instances, function() { + $overlays = $overlays.add(this); + }); + + $overlays.css({ + width: 0, + height: 0 + }).css({ + width: $.ui.dialog.overlay.width(), + height: $.ui.dialog.overlay.height() + }); + } +}); + +$.extend($.ui.dialog.overlay.prototype, { + destroy: function() { + $.ui.dialog.overlay.destroy(this.$el); + } +}); + +}(jQuery)); + +(function( $, undefined ) { + +$.ui = $.ui || {}; + +var horizontalPositions = /left|center|right/, + verticalPositions = /top|center|bottom/, + center = "center", + support = {}, + _position = $.fn.position, + _offset = $.fn.offset; + +$.fn.position = function( options ) { + if ( !options || !options.of ) { + return _position.apply( this, arguments ); + } + + // make a copy, we don't want to modify arguments + options = $.extend( {}, options ); + + var target = $( options.of ), + targetElem = target[0], + collision = ( options.collision || "flip" ).split( " " ), + offset = options.offset ? options.offset.split( " " ) : [ 0, 0 ], + targetWidth, + targetHeight, + basePosition; + + if ( targetElem.nodeType === 9 ) { + targetWidth = target.width(); + targetHeight = target.height(); + basePosition = { top: 0, left: 0 }; + // TODO: use $.isWindow() in 1.9 + } else if ( targetElem.setTimeout ) { + targetWidth = target.width(); + targetHeight = target.height(); + basePosition = { top: target.scrollTop(), left: target.scrollLeft() }; + } else if ( targetElem.preventDefault ) { + // force left top to allow flipping + options.at = "left top"; + targetWidth = targetHeight = 0; + basePosition = { top: options.of.pageY, left: options.of.pageX }; + } else { + targetWidth = target.outerWidth(); + targetHeight = target.outerHeight(); + basePosition = target.offset(); + } + + // force my and at to have valid horizontal and veritcal positions + // if a value is missing or invalid, it will be converted to center + $.each( [ "my", "at" ], function() { + var pos = ( options[this] || "" ).split( " " ); + if ( pos.length === 1) { + pos = horizontalPositions.test( pos[0] ) ? + pos.concat( [center] ) : + verticalPositions.test( pos[0] ) ? + [ center ].concat( pos ) : + [ center, center ]; + } + pos[ 0 ] = horizontalPositions.test( pos[0] ) ? pos[ 0 ] : center; + pos[ 1 ] = verticalPositions.test( pos[1] ) ? pos[ 1 ] : center; + options[ this ] = pos; + }); + + // normalize collision option + if ( collision.length === 1 ) { + collision[ 1 ] = collision[ 0 ]; + } + + // normalize offset option + offset[ 0 ] = parseInt( offset[0], 10 ) || 0; + if ( offset.length === 1 ) { + offset[ 1 ] = offset[ 0 ]; + } + offset[ 1 ] = parseInt( offset[1], 10 ) || 0; + + if ( options.at[0] === "right" ) { + basePosition.left += targetWidth; + } else if ( options.at[0] === center ) { + basePosition.left += targetWidth / 2; + } + + if ( options.at[1] === "bottom" ) { + basePosition.top += targetHeight; + } else if ( options.at[1] === center ) { + basePosition.top += targetHeight / 2; + } + + basePosition.left += offset[ 0 ]; + basePosition.top += offset[ 1 ]; + + return this.each(function() { + var elem = $( this ), + elemWidth = elem.outerWidth(), + elemHeight = elem.outerHeight(), + marginLeft = parseInt( $.curCSS( this, "marginLeft", true ) ) || 0, + marginTop = parseInt( $.curCSS( this, "marginTop", true ) ) || 0, + collisionWidth = elemWidth + marginLeft + + ( parseInt( $.curCSS( this, "marginRight", true ) ) || 0 ), + collisionHeight = elemHeight + marginTop + + ( parseInt( $.curCSS( this, "marginBottom", true ) ) || 0 ), + position = $.extend( {}, basePosition ), + collisionPosition; + + if ( options.my[0] === "right" ) { + position.left -= elemWidth; + } else if ( options.my[0] === center ) { + position.left -= elemWidth / 2; + } + + if ( options.my[1] === "bottom" ) { + position.top -= elemHeight; + } else if ( options.my[1] === center ) { + position.top -= elemHeight / 2; + } + + // prevent fractions if jQuery version doesn't support them (see #5280) + if ( !support.fractions ) { + position.left = Math.round( position.left ); + position.top = Math.round( position.top ); + } + + collisionPosition = { + left: position.left - marginLeft, + top: position.top - marginTop + }; + + $.each( [ "left", "top" ], function( i, dir ) { + if ( $.ui.position[ collision[i] ] ) { + $.ui.position[ collision[i] ][ dir ]( position, { + targetWidth: targetWidth, + targetHeight: targetHeight, + elemWidth: elemWidth, + elemHeight: elemHeight, + collisionPosition: collisionPosition, + collisionWidth: collisionWidth, + collisionHeight: collisionHeight, + offset: offset, + my: options.my, + at: options.at + }); + } + }); + + if ( $.fn.bgiframe ) { + elem.bgiframe(); + } + elem.offset( $.extend( position, { using: options.using } ) ); + }); +}; + +$.ui.position = { + fit: { + left: function( position, data ) { + var win = $( window ), + over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft(); + position.left = over > 0 ? position.left - over : Math.max( position.left - data.collisionPosition.left, position.left ); + }, + top: function( position, data ) { + var win = $( window ), + over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop(); + position.top = over > 0 ? position.top - over : Math.max( position.top - data.collisionPosition.top, position.top ); + } + }, + + flip: { + left: function( position, data ) { + if ( data.at[0] === center ) { + return; + } + var win = $( window ), + over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft(), + myOffset = data.my[ 0 ] === "left" ? + -data.elemWidth : + data.my[ 0 ] === "right" ? + data.elemWidth : + 0, + atOffset = data.at[ 0 ] === "left" ? + data.targetWidth : + -data.targetWidth, + offset = -2 * data.offset[ 0 ]; + position.left += data.collisionPosition.left < 0 ? + myOffset + atOffset + offset : + over > 0 ? + myOffset + atOffset + offset : + 0; + }, + top: function( position, data ) { + if ( data.at[1] === center ) { + return; + } + var win = $( window ), + over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop(), + myOffset = data.my[ 1 ] === "top" ? + -data.elemHeight : + data.my[ 1 ] === "bottom" ? + data.elemHeight : + 0, + atOffset = data.at[ 1 ] === "top" ? + data.targetHeight : + -data.targetHeight, + offset = -2 * data.offset[ 1 ]; + position.top += data.collisionPosition.top < 0 ? + myOffset + atOffset + offset : + over > 0 ? + myOffset + atOffset + offset : + 0; + } + } +}; + +// offset setter from jQuery 1.4 +if ( !$.offset.setOffset ) { + $.offset.setOffset = function( elem, options ) { + // set position first, in-case top/left are set even on static elem + if ( /static/.test( $.curCSS( elem, "position" ) ) ) { + elem.style.position = "relative"; + } + var curElem = $( elem ), + curOffset = curElem.offset(), + curTop = parseInt( $.curCSS( elem, "top", true ), 10 ) || 0, + curLeft = parseInt( $.curCSS( elem, "left", true ), 10) || 0, + props = { + top: (options.top - curOffset.top) + curTop, + left: (options.left - curOffset.left) + curLeft + }; + + if ( 'using' in options ) { + options.using.call( elem, props ); + } else { + curElem.css( props ); + } + }; + + $.fn.offset = function( options ) { + var elem = this[ 0 ]; + if ( !elem || !elem.ownerDocument ) { return null; } + if ( options ) { + return this.each(function() { + $.offset.setOffset( this, options ); + }); + } + return _offset.call( this ); + }; +} + +// fraction support test (older versions of jQuery don't support fractions) +(function () { + var body = document.getElementsByTagName( "body" )[ 0 ], + div = document.createElement( "div" ), + testElement, testElementParent, testElementStyle, offset, offsetTotal; + + //Create a "fake body" for testing based on method used in jQuery.support + testElement = document.createElement( body ? "div" : "body" ); + testElementStyle = { + visibility: "hidden", + width: 0, + height: 0, + border: 0, + margin: 0, + background: "none" + }; + if ( body ) { + $.extend( testElementStyle, { + position: "absolute", + left: "-1000px", + top: "-1000px" + }); + } + for ( var i in testElementStyle ) { + testElement.style[ i ] = testElementStyle[ i ]; + } + testElement.appendChild( div ); + testElementParent = body || document.documentElement; + testElementParent.insertBefore( testElement, testElementParent.firstChild ); + + div.style.cssText = "position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;"; + + offset = $( div ).offset( function( _, offset ) { + return offset; + }).offset(); + + testElement.innerHTML = ""; + testElementParent.removeChild( testElement ); + + offsetTotal = offset.top + offset.left + ( body ? 2000 : 0 ); + support.fractions = offsetTotal > 21 && offsetTotal < 22; +})(); + +}( jQuery )); + +(function( $, undefined ) { + +$.widget( "ui.progressbar", { + options: { + value: 0, + max: 100 + }, + + min: 0, + + _create: function() { + this.element + .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) + .attr({ + role: "progressbar", + "aria-valuemin": this.min, + "aria-valuemax": this.options.max, + "aria-valuenow": this._value() + }); + + this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) + .appendTo( this.element ); + + this.oldValue = this._value(); + this._refreshValue(); + }, + + destroy: function() { + this.element + .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) + .removeAttr( "role" ) + .removeAttr( "aria-valuemin" ) + .removeAttr( "aria-valuemax" ) + .removeAttr( "aria-valuenow" ); + + this.valueDiv.remove(); + + $.Widget.prototype.destroy.apply( this, arguments ); + }, + + value: function( newValue ) { + if ( newValue === undefined ) { + return this._value(); + } + + this._setOption( "value", newValue ); + return this; + }, + + _setOption: function( key, value ) { + if ( key === "value" ) { + this.options.value = value; + this._refreshValue(); + if ( this._value() === this.options.max ) { + this._trigger( "complete" ); + } + } + + $.Widget.prototype._setOption.apply( this, arguments ); + }, + + _value: function() { + var val = this.options.value; + // normalize invalid value + if ( typeof val !== "number" ) { + val = 0; + } + return Math.min( this.options.max, Math.max( this.min, val ) ); + }, + + _percentage: function() { + return 100 * this._value() / this.options.max; + }, + + _refreshValue: function() { + var value = this.value(); + var percentage = this._percentage(); + + if ( this.oldValue !== value ) { + this.oldValue = value; + this._trigger( "change" ); + } + + this.valueDiv + .toggle( value > this.min ) + .toggleClass( "ui-corner-right", value === this.options.max ) + .width( percentage.toFixed(0) + "%" ); + this.element.attr( "aria-valuenow", value ); + } +}); + +$.extend( $.ui.progressbar, { + version: "1.8.20" +}); + +})( jQuery ); + +(function( $, undefined ) { + +// number of pages in a slider +// (how many times can you page up/down to go through the whole range) +var numPages = 5; + +$.widget( "ui.slider", $.ui.mouse, { + + widgetEventPrefix: "slide", + + options: { + animate: false, + distance: 0, + max: 100, + min: 0, + orientation: "horizontal", + range: false, + step: 1, + value: 0, + values: null + }, + + _create: function() { + var self = this, + o = this.options, + existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), + handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", + handleCount = ( o.values && o.values.length ) || 1, + handles = []; + + this._keySliding = false; + this._mouseSliding = false; + this._animateOff = true; + this._handleIndex = null; + this._detectOrientation(); + this._mouseInit(); + + this.element + .addClass( "ui-slider" + + " ui-slider-" + this.orientation + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all" + + ( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) ); + + this.range = $([]); + + if ( o.range ) { + if ( o.range === true ) { + if ( !o.values ) { + o.values = [ this._valueMin(), this._valueMin() ]; + } + if ( o.values.length && o.values.length !== 2 ) { + o.values = [ o.values[0], o.values[0] ]; + } + } + + this.range = $( "<div></div>" ) + .appendTo( this.element ) + .addClass( "ui-slider-range" + + // note: this isn't the most fittingly semantic framework class for this element, + // but worked best visually with a variety of themes + " ui-widget-header" + + ( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) ); + } + + for ( var i = existingHandles.length; i < handleCount; i += 1 ) { + handles.push( handle ); + } + + this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( self.element ) ); + + this.handle = this.handles.eq( 0 ); + + this.handles.add( this.range ).filter( "a" ) + .click(function( event ) { + event.preventDefault(); + }) + .hover(function() { + if ( !o.disabled ) { + $( this ).addClass( "ui-state-hover" ); + } + }, function() { + $( this ).removeClass( "ui-state-hover" ); + }) + .focus(function() { + if ( !o.disabled ) { + $( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" ); + $( this ).addClass( "ui-state-focus" ); + } else { + $( this ).blur(); + } + }) + .blur(function() { + $( this ).removeClass( "ui-state-focus" ); + }); + + this.handles.each(function( i ) { + $( this ).data( "index.ui-slider-handle", i ); + }); + + this.handles + .keydown(function( event ) { + var index = $( this ).data( "index.ui-slider-handle" ), + allowed, + curVal, + newVal, + step; + + if ( self.options.disabled ) { + return; + } + + switch ( event.keyCode ) { + case $.ui.keyCode.HOME: + case $.ui.keyCode.END: + case $.ui.keyCode.PAGE_UP: + case $.ui.keyCode.PAGE_DOWN: + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + event.preventDefault(); + if ( !self._keySliding ) { + self._keySliding = true; + $( this ).addClass( "ui-state-active" ); + allowed = self._start( event, index ); + if ( allowed === false ) { + return; + } + } + break; + } + + step = self.options.step; + if ( self.options.values && self.options.values.length ) { + curVal = newVal = self.values( index ); + } else { + curVal = newVal = self.value(); + } + + switch ( event.keyCode ) { + case $.ui.keyCode.HOME: + newVal = self._valueMin(); + break; + case $.ui.keyCode.END: + newVal = self._valueMax(); + break; + case $.ui.keyCode.PAGE_UP: + newVal = self._trimAlignValue( curVal + ( (self._valueMax() - self._valueMin()) / numPages ) ); + break; + case $.ui.keyCode.PAGE_DOWN: + newVal = self._trimAlignValue( curVal - ( (self._valueMax() - self._valueMin()) / numPages ) ); + break; + case $.ui.keyCode.UP: + case $.ui.keyCode.RIGHT: + if ( curVal === self._valueMax() ) { + return; + } + newVal = self._trimAlignValue( curVal + step ); + break; + case $.ui.keyCode.DOWN: + case $.ui.keyCode.LEFT: + if ( curVal === self._valueMin() ) { + return; + } + newVal = self._trimAlignValue( curVal - step ); + break; + } + + self._slide( event, index, newVal ); + }) + .keyup(function( event ) { + var index = $( this ).data( "index.ui-slider-handle" ); + + if ( self._keySliding ) { + self._keySliding = false; + self._stop( event, index ); + self._change( event, index ); + $( this ).removeClass( "ui-state-active" ); + } + + }); + + this._refreshValue(); + + this._animateOff = false; + }, + + destroy: function() { + this.handles.remove(); + this.range.remove(); + + this.element + .removeClass( "ui-slider" + + " ui-slider-horizontal" + + " ui-slider-vertical" + + " ui-slider-disabled" + + " ui-widget" + + " ui-widget-content" + + " ui-corner-all" ) + .removeData( "slider" ) + .unbind( ".slider" ); + + this._mouseDestroy(); + + return this; + }, + + _mouseCapture: function( event ) { + var o = this.options, + position, + normValue, + distance, + closestHandle, + self, + index, + allowed, + offset, + mouseOverHandle; + + if ( o.disabled ) { + return false; + } + + this.elementSize = { + width: this.element.outerWidth(), + height: this.element.outerHeight() + }; + this.elementOffset = this.element.offset(); + + position = { x: event.pageX, y: event.pageY }; + normValue = this._normValueFromMouse( position ); + distance = this._valueMax() - this._valueMin() + 1; + self = this; + this.handles.each(function( i ) { + var thisDistance = Math.abs( normValue - self.values(i) ); + if ( distance > thisDistance ) { + distance = thisDistance; + closestHandle = $( this ); + index = i; + } + }); + + // workaround for bug #3736 (if both handles of a range are at 0, + // the first is always used as the one with least distance, + // and moving it is obviously prevented by preventing negative ranges) + if( o.range === true && this.values(1) === o.min ) { + index += 1; + closestHandle = $( this.handles[index] ); + } + + allowed = this._start( event, index ); + if ( allowed === false ) { + return false; + } + this._mouseSliding = true; + + self._handleIndex = index; + + closestHandle + .addClass( "ui-state-active" ) + .focus(); + + offset = closestHandle.offset(); + mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" ); + this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { + left: event.pageX - offset.left - ( closestHandle.width() / 2 ), + top: event.pageY - offset.top - + ( closestHandle.height() / 2 ) - + ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - + ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) + }; + + if ( !this.handles.hasClass( "ui-state-hover" ) ) { + this._slide( event, index, normValue ); + } + this._animateOff = true; + return true; + }, + + _mouseStart: function( event ) { + return true; + }, + + _mouseDrag: function( event ) { + var position = { x: event.pageX, y: event.pageY }, + normValue = this._normValueFromMouse( position ); + + this._slide( event, this._handleIndex, normValue ); + + return false; + }, + + _mouseStop: function( event ) { + this.handles.removeClass( "ui-state-active" ); + this._mouseSliding = false; + + this._stop( event, this._handleIndex ); + this._change( event, this._handleIndex ); + + this._handleIndex = null; + this._clickOffset = null; + this._animateOff = false; + + return false; + }, + + _detectOrientation: function() { + this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; + }, + + _normValueFromMouse: function( position ) { + var pixelTotal, + pixelMouse, + percentMouse, + valueTotal, + valueMouse; + + if ( this.orientation === "horizontal" ) { + pixelTotal = this.elementSize.width; + pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); + } else { + pixelTotal = this.elementSize.height; + pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); + } + + percentMouse = ( pixelMouse / pixelTotal ); + if ( percentMouse > 1 ) { + percentMouse = 1; + } + if ( percentMouse < 0 ) { + percentMouse = 0; + } + if ( this.orientation === "vertical" ) { + percentMouse = 1 - percentMouse; + } + + valueTotal = this._valueMax() - this._valueMin(); + valueMouse = this._valueMin() + percentMouse * valueTotal; + + return this._trimAlignValue( valueMouse ); + }, + + _start: function( event, index ) { + var uiHash = { + handle: this.handles[ index ], + value: this.value() + }; + if ( this.options.values && this.options.values.length ) { + uiHash.value = this.values( index ); + uiHash.values = this.values(); + } + return this._trigger( "start", event, uiHash ); + }, + + _slide: function( event, index, newVal ) { + var otherVal, + newValues, + allowed; + + if ( this.options.values && this.options.values.length ) { + otherVal = this.values( index ? 0 : 1 ); + + if ( ( this.options.values.length === 2 && this.options.range === true ) && + ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) + ) { + newVal = otherVal; + } + + if ( newVal !== this.values( index ) ) { + newValues = this.values(); + newValues[ index ] = newVal; + // A slide can be canceled by returning false from the slide callback + allowed = this._trigger( "slide", event, { + handle: this.handles[ index ], + value: newVal, + values: newValues + } ); + otherVal = this.values( index ? 0 : 1 ); + if ( allowed !== false ) { + this.values( index, newVal, true ); + } + } + } else { + if ( newVal !== this.value() ) { + // A slide can be canceled by returning false from the slide callback + allowed = this._trigger( "slide", event, { + handle: this.handles[ index ], + value: newVal + } ); + if ( allowed !== false ) { + this.value( newVal ); + } + } + } + }, + + _stop: function( event, index ) { + var uiHash = { + handle: this.handles[ index ], + value: this.value() + }; + if ( this.options.values && this.options.values.length ) { + uiHash.value = this.values( index ); + uiHash.values = this.values(); + } + + this._trigger( "stop", event, uiHash ); + }, + + _change: function( event, index ) { + if ( !this._keySliding && !this._mouseSliding ) { + var uiHash = { + handle: this.handles[ index ], + value: this.value() + }; + if ( this.options.values && this.options.values.length ) { + uiHash.value = this.values( index ); + uiHash.values = this.values(); + } + + this._trigger( "change", event, uiHash ); + } + }, + + value: function( newValue ) { + if ( arguments.length ) { + this.options.value = this._trimAlignValue( newValue ); + this._refreshValue(); + this._change( null, 0 ); + return; + } + + return this._value(); + }, + + values: function( index, newValue ) { + var vals, + newValues, + i; + + if ( arguments.length > 1 ) { + this.options.values[ index ] = this._trimAlignValue( newValue ); + this._refreshValue(); + this._change( null, index ); + return; + } + + if ( arguments.length ) { + if ( $.isArray( arguments[ 0 ] ) ) { + vals = this.options.values; + newValues = arguments[ 0 ]; + for ( i = 0; i < vals.length; i += 1 ) { + vals[ i ] = this._trimAlignValue( newValues[ i ] ); + this._change( null, i ); + } + this._refreshValue(); + } else { + if ( this.options.values && this.options.values.length ) { + return this._values( index ); + } else { + return this.value(); + } + } + } else { + return this._values(); + } + }, + + _setOption: function( key, value ) { + var i, + valsLength = 0; + + if ( $.isArray( this.options.values ) ) { + valsLength = this.options.values.length; + } + + $.Widget.prototype._setOption.apply( this, arguments ); + + switch ( key ) { + case "disabled": + if ( value ) { + this.handles.filter( ".ui-state-focus" ).blur(); + this.handles.removeClass( "ui-state-hover" ); + this.handles.propAttr( "disabled", true ); + this.element.addClass( "ui-disabled" ); + } else { + this.handles.propAttr( "disabled", false ); + this.element.removeClass( "ui-disabled" ); + } + break; + case "orientation": + this._detectOrientation(); + this.element + .removeClass( "ui-slider-horizontal ui-slider-vertical" ) + .addClass( "ui-slider-" + this.orientation ); + this._refreshValue(); + break; + case "value": + this._animateOff = true; + this._refreshValue(); + this._change( null, 0 ); + this._animateOff = false; + break; + case "values": + this._animateOff = true; + this._refreshValue(); + for ( i = 0; i < valsLength; i += 1 ) { + this._change( null, i ); + } + this._animateOff = false; + break; + } + }, + + //internal value getter + // _value() returns value trimmed by min and max, aligned by step + _value: function() { + var val = this.options.value; + val = this._trimAlignValue( val ); + + return val; + }, + + //internal values getter + // _values() returns array of values trimmed by min and max, aligned by step + // _values( index ) returns single value trimmed by min and max, aligned by step + _values: function( index ) { + var val, + vals, + i; + + if ( arguments.length ) { + val = this.options.values[ index ]; + val = this._trimAlignValue( val ); + + return val; + } else { + // .slice() creates a copy of the array + // this copy gets trimmed by min and max and then returned + vals = this.options.values.slice(); + for ( i = 0; i < vals.length; i+= 1) { + vals[ i ] = this._trimAlignValue( vals[ i ] ); + } + + return vals; + } + }, + + // returns the step-aligned value that val is closest to, between (inclusive) min and max + _trimAlignValue: function( val ) { + if ( val <= this._valueMin() ) { + return this._valueMin(); + } + if ( val >= this._valueMax() ) { + return this._valueMax(); + } + var step = ( this.options.step > 0 ) ? this.options.step : 1, + valModStep = (val - this._valueMin()) % step, + alignValue = val - valModStep; + + if ( Math.abs(valModStep) * 2 >= step ) { + alignValue += ( valModStep > 0 ) ? step : ( -step ); + } + + // Since JavaScript has problems with large floats, round + // the final value to 5 digits after the decimal point (see #4124) + return parseFloat( alignValue.toFixed(5) ); + }, + + _valueMin: function() { + return this.options.min; + }, + + _valueMax: function() { + return this.options.max; + }, + + _refreshValue: function() { + var oRange = this.options.range, + o = this.options, + self = this, + animate = ( !this._animateOff ) ? o.animate : false, + valPercent, + _set = {}, + lastValPercent, + value, + valueMin, + valueMax; + + if ( this.options.values && this.options.values.length ) { + this.handles.each(function( i, j ) { + valPercent = ( self.values(i) - self._valueMin() ) / ( self._valueMax() - self._valueMin() ) * 100; + _set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; + $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); + if ( self.options.range === true ) { + if ( self.orientation === "horizontal" ) { + if ( i === 0 ) { + self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); + } + if ( i === 1 ) { + self.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + } else { + if ( i === 0 ) { + self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); + } + if ( i === 1 ) { + self.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + } + } + lastValPercent = valPercent; + }); + } else { + value = this.value(); + valueMin = this._valueMin(); + valueMax = this._valueMax(); + valPercent = ( valueMax !== valueMin ) ? + ( value - valueMin ) / ( valueMax - valueMin ) * 100 : + 0; + _set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; + this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); + + if ( oRange === "min" && this.orientation === "horizontal" ) { + this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); + } + if ( oRange === "max" && this.orientation === "horizontal" ) { + this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + if ( oRange === "min" && this.orientation === "vertical" ) { + this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); + } + if ( oRange === "max" && this.orientation === "vertical" ) { + this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); + } + } + } + +}); + +$.extend( $.ui.slider, { + version: "1.8.20" +}); + +}(jQuery)); + +(function( $, undefined ) { + +var tabId = 0, + listId = 0; + +function getNextTabId() { + return ++tabId; +} + +function getNextListId() { + return ++listId; +} + +$.widget( "ui.tabs", { + options: { + add: null, + ajaxOptions: null, + cache: false, + cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } + collapsible: false, + disable: null, + disabled: [], + enable: null, + event: "click", + fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 } + idPrefix: "ui-tabs-", + load: null, + panelTemplate: "<div></div>", + remove: null, + select: null, + show: null, + spinner: "<em>Loading…</em>", + tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>" + }, + + _create: function() { + this._tabify( true ); + }, + + _setOption: function( key, value ) { + if ( key == "selected" ) { + if (this.options.collapsible && value == this.options.selected ) { + return; + } + this.select( value ); + } else { + this.options[ key ] = value; + this._tabify(); + } + }, + + _tabId: function( a ) { + return a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF-]/g, "" ) || + this.options.idPrefix + getNextTabId(); + }, + + _sanitizeSelector: function( hash ) { + // we need this because an id may contain a ":" + return hash.replace( /:/g, "\\:" ); + }, + + _cookie: function() { + var cookie = this.cookie || + ( this.cookie = this.options.cookie.name || "ui-tabs-" + getNextListId() ); + return $.cookie.apply( null, [ cookie ].concat( $.makeArray( arguments ) ) ); + }, + + _ui: function( tab, panel ) { + return { + tab: tab, + panel: panel, + index: this.anchors.index( tab ) + }; + }, + + _cleanup: function() { + // restore all former loading tabs labels + this.lis.filter( ".ui-state-processing" ) + .removeClass( "ui-state-processing" ) + .find( "span:data(label.tabs)" ) + .each(function() { + var el = $( this ); + el.html( el.data( "label.tabs" ) ).removeData( "label.tabs" ); + }); + }, + + _tabify: function( init ) { + var self = this, + o = this.options, + fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash + + this.list = this.element.find( "ol,ul" ).eq( 0 ); + this.lis = $( " > li:has(a[href])", this.list ); + this.anchors = this.lis.map(function() { + return $( "a", this )[ 0 ]; + }); + this.panels = $( [] ); + + this.anchors.each(function( i, a ) { + var href = $( a ).attr( "href" ); + // For dynamically created HTML that contains a hash as href IE < 8 expands + // such href to the full page url with hash and then misinterprets tab as ajax. + // Same consideration applies for an added tab with a fragment identifier + // since a[href=#fragment-identifier] does unexpectedly not match. + // Thus normalize href attribute... + var hrefBase = href.split( "#" )[ 0 ], + baseEl; + if ( hrefBase && ( hrefBase === location.toString().split( "#" )[ 0 ] || + ( baseEl = $( "base" )[ 0 ]) && hrefBase === baseEl.href ) ) { + href = a.hash; + a.href = href; + } + + // inline tab + if ( fragmentId.test( href ) ) { + self.panels = self.panels.add( self.element.find( self._sanitizeSelector( href ) ) ); + // remote tab + // prevent loading the page itself if href is just "#" + } else if ( href && href !== "#" ) { + // required for restore on destroy + $.data( a, "href.tabs", href ); + + // TODO until #3808 is fixed strip fragment identifier from url + // (IE fails to load from such url) + $.data( a, "load.tabs", href.replace( /#.*$/, "" ) ); + + var id = self._tabId( a ); + a.href = "#" + id; + var $panel = self.element.find( "#" + id ); + if ( !$panel.length ) { + $panel = $( o.panelTemplate ) + .attr( "id", id ) + .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) + .insertAfter( self.panels[ i - 1 ] || self.list ); + $panel.data( "destroy.tabs", true ); + } + self.panels = self.panels.add( $panel ); + // invalid tab href + } else { + o.disabled.push( i ); + } + }); + + // initialization from scratch + if ( init ) { + // attach necessary classes for styling + this.element.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ); + this.list.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ); + this.lis.addClass( "ui-state-default ui-corner-top" ); + this.panels.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ); + + // Selected tab + // use "selected" option or try to retrieve: + // 1. from fragment identifier in url + // 2. from cookie + // 3. from selected class attribute on <li> + if ( o.selected === undefined ) { + if ( location.hash ) { + this.anchors.each(function( i, a ) { + if ( a.hash == location.hash ) { + o.selected = i; + return false; + } + }); + } + if ( typeof o.selected !== "number" && o.cookie ) { + o.selected = parseInt( self._cookie(), 10 ); + } + if ( typeof o.selected !== "number" && this.lis.filter( ".ui-tabs-selected" ).length ) { + o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) ); + } + o.selected = o.selected || ( this.lis.length ? 0 : -1 ); + } else if ( o.selected === null ) { // usage of null is deprecated, TODO remove in next release + o.selected = -1; + } + + // sanity check - default to first tab... + o.selected = ( ( o.selected >= 0 && this.anchors[ o.selected ] ) || o.selected < 0 ) + ? o.selected + : 0; + + // Take disabling tabs via class attribute from HTML + // into account and update option properly. + // A selected tab cannot become disabled. + o.disabled = $.unique( o.disabled.concat( + $.map( this.lis.filter( ".ui-state-disabled" ), function( n, i ) { + return self.lis.index( n ); + }) + ) ).sort(); + + if ( $.inArray( o.selected, o.disabled ) != -1 ) { + o.disabled.splice( $.inArray( o.selected, o.disabled ), 1 ); + } + + // highlight selected tab + this.panels.addClass( "ui-tabs-hide" ); + this.lis.removeClass( "ui-tabs-selected ui-state-active" ); + // check for length avoids error when initializing empty list + if ( o.selected >= 0 && this.anchors.length ) { + self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) ).removeClass( "ui-tabs-hide" ); + this.lis.eq( o.selected ).addClass( "ui-tabs-selected ui-state-active" ); + + // seems to be expected behavior that the show callback is fired + self.element.queue( "tabs", function() { + self._trigger( "show", null, + self._ui( self.anchors[ o.selected ], self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) )[ 0 ] ) ); + }); + + this.load( o.selected ); + } + + // clean up to avoid memory leaks in certain versions of IE 6 + // TODO: namespace this event + $( window ).bind( "unload", function() { + self.lis.add( self.anchors ).unbind( ".tabs" ); + self.lis = self.anchors = self.panels = null; + }); + // update selected after add/remove + } else { + o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) ); + } + + // update collapsible + // TODO: use .toggleClass() + this.element[ o.collapsible ? "addClass" : "removeClass" ]( "ui-tabs-collapsible" ); + + // set or update cookie after init and add/remove respectively + if ( o.cookie ) { + this._cookie( o.selected, o.cookie ); + } + + // disable tabs + for ( var i = 0, li; ( li = this.lis[ i ] ); i++ ) { + $( li )[ $.inArray( i, o.disabled ) != -1 && + // TODO: use .toggleClass() + !$( li ).hasClass( "ui-tabs-selected" ) ? "addClass" : "removeClass" ]( "ui-state-disabled" ); + } + + // reset cache if switching from cached to not cached + if ( o.cache === false ) { + this.anchors.removeData( "cache.tabs" ); + } + + // remove all handlers before, tabify may run on existing tabs after add or option change + this.lis.add( this.anchors ).unbind( ".tabs" ); + + if ( o.event !== "mouseover" ) { + var addState = function( state, el ) { + if ( el.is( ":not(.ui-state-disabled)" ) ) { + el.addClass( "ui-state-" + state ); + } + }; + var removeState = function( state, el ) { + el.removeClass( "ui-state-" + state ); + }; + this.lis.bind( "mouseover.tabs" , function() { + addState( "hover", $( this ) ); + }); + this.lis.bind( "mouseout.tabs", function() { + removeState( "hover", $( this ) ); + }); + this.anchors.bind( "focus.tabs", function() { + addState( "focus", $( this ).closest( "li" ) ); + }); + this.anchors.bind( "blur.tabs", function() { + removeState( "focus", $( this ).closest( "li" ) ); + }); + } + + // set up animations + var hideFx, showFx; + if ( o.fx ) { + if ( $.isArray( o.fx ) ) { + hideFx = o.fx[ 0 ]; + showFx = o.fx[ 1 ]; + } else { + hideFx = showFx = o.fx; + } + } + + // Reset certain styles left over from animation + // and prevent IE's ClearType bug... + function resetStyle( $el, fx ) { + $el.css( "display", "" ); + if ( !$.support.opacity && fx.opacity ) { + $el[ 0 ].style.removeAttribute( "filter" ); + } + } + + // Show a tab... + var showTab = showFx + ? function( clicked, $show ) { + $( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" ); + $show.hide().removeClass( "ui-tabs-hide" ) // avoid flicker that way + .animate( showFx, showFx.duration || "normal", function() { + resetStyle( $show, showFx ); + self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) ); + }); + } + : function( clicked, $show ) { + $( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" ); + $show.removeClass( "ui-tabs-hide" ); + self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) ); + }; + + // Hide a tab, $show is optional... + var hideTab = hideFx + ? function( clicked, $hide ) { + $hide.animate( hideFx, hideFx.duration || "normal", function() { + self.lis.removeClass( "ui-tabs-selected ui-state-active" ); + $hide.addClass( "ui-tabs-hide" ); + resetStyle( $hide, hideFx ); + self.element.dequeue( "tabs" ); + }); + } + : function( clicked, $hide, $show ) { + self.lis.removeClass( "ui-tabs-selected ui-state-active" ); + $hide.addClass( "ui-tabs-hide" ); + self.element.dequeue( "tabs" ); + }; + + // attach tab event handler, unbind to avoid duplicates from former tabifying... + this.anchors.bind( o.event + ".tabs", function() { + var el = this, + $li = $(el).closest( "li" ), + $hide = self.panels.filter( ":not(.ui-tabs-hide)" ), + $show = self.element.find( self._sanitizeSelector( el.hash ) ); + + // If tab is already selected and not collapsible or tab disabled or + // or is already loading or click callback returns false stop here. + // Check if click handler returns false last so that it is not executed + // for a disabled or loading tab! + if ( ( $li.hasClass( "ui-tabs-selected" ) && !o.collapsible) || + $li.hasClass( "ui-state-disabled" ) || + $li.hasClass( "ui-state-processing" ) || + self.panels.filter( ":animated" ).length || + self._trigger( "select", null, self._ui( this, $show[ 0 ] ) ) === false ) { + this.blur(); + return false; + } + + o.selected = self.anchors.index( this ); + + self.abort(); + + // if tab may be closed + if ( o.collapsible ) { + if ( $li.hasClass( "ui-tabs-selected" ) ) { + o.selected = -1; + + if ( o.cookie ) { + self._cookie( o.selected, o.cookie ); + } + + self.element.queue( "tabs", function() { + hideTab( el, $hide ); + }).dequeue( "tabs" ); + + this.blur(); + return false; + } else if ( !$hide.length ) { + if ( o.cookie ) { + self._cookie( o.selected, o.cookie ); + } + + self.element.queue( "tabs", function() { + showTab( el, $show ); + }); + + // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171 + self.load( self.anchors.index( this ) ); + + this.blur(); + return false; + } + } + + if ( o.cookie ) { + self._cookie( o.selected, o.cookie ); + } + + // show new tab + if ( $show.length ) { + if ( $hide.length ) { + self.element.queue( "tabs", function() { + hideTab( el, $hide ); + }); + } + self.element.queue( "tabs", function() { + showTab( el, $show ); + }); + + self.load( self.anchors.index( this ) ); + } else { + throw "jQuery UI Tabs: Mismatching fragment identifier."; + } + + // Prevent IE from keeping other link focussed when using the back button + // and remove dotted border from clicked link. This is controlled via CSS + // in modern browsers; blur() removes focus from address bar in Firefox + // which can become a usability and annoying problem with tabs('rotate'). + if ( $.browser.msie ) { + this.blur(); + } + }); + + // disable click in any case + this.anchors.bind( "click.tabs", function(){ + return false; + }); + }, + + _getIndex: function( index ) { + // meta-function to give users option to provide a href string instead of a numerical index. + // also sanitizes numerical indexes to valid values. + if ( typeof index == "string" ) { + index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); + } + + return index; + }, + + destroy: function() { + var o = this.options; + + this.abort(); + + this.element + .unbind( ".tabs" ) + .removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ) + .removeData( "tabs" ); + + this.list.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ); + + this.anchors.each(function() { + var href = $.data( this, "href.tabs" ); + if ( href ) { + this.href = href; + } + var $this = $( this ).unbind( ".tabs" ); + $.each( [ "href", "load", "cache" ], function( i, prefix ) { + $this.removeData( prefix + ".tabs" ); + }); + }); + + this.lis.unbind( ".tabs" ).add( this.panels ).each(function() { + if ( $.data( this, "destroy.tabs" ) ) { + $( this ).remove(); + } else { + $( this ).removeClass([ + "ui-state-default", + "ui-corner-top", + "ui-tabs-selected", + "ui-state-active", + "ui-state-hover", + "ui-state-focus", + "ui-state-disabled", + "ui-tabs-panel", + "ui-widget-content", + "ui-corner-bottom", + "ui-tabs-hide" + ].join( " " ) ); + } + }); + + if ( o.cookie ) { + this._cookie( null, o.cookie ); + } + + return this; + }, + + add: function( url, label, index ) { + if ( index === undefined ) { + index = this.anchors.length; + } + + var self = this, + o = this.options, + $li = $( o.tabTemplate.replace( /#\{href\}/g, url ).replace( /#\{label\}/g, label ) ), + id = !url.indexOf( "#" ) ? url.replace( "#", "" ) : this._tabId( $( "a", $li )[ 0 ] ); + + $li.addClass( "ui-state-default ui-corner-top" ).data( "destroy.tabs", true ); + + // try to find an existing element before creating a new one + var $panel = self.element.find( "#" + id ); + if ( !$panel.length ) { + $panel = $( o.panelTemplate ) + .attr( "id", id ) + .data( "destroy.tabs", true ); + } + $panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide" ); + + if ( index >= this.lis.length ) { + $li.appendTo( this.list ); + $panel.appendTo( this.list[ 0 ].parentNode ); + } else { + $li.insertBefore( this.lis[ index ] ); + $panel.insertBefore( this.panels[ index ] ); + } + + o.disabled = $.map( o.disabled, function( n, i ) { + return n >= index ? ++n : n; + }); + + this._tabify(); + + if ( this.anchors.length == 1 ) { + o.selected = 0; + $li.addClass( "ui-tabs-selected ui-state-active" ); + $panel.removeClass( "ui-tabs-hide" ); + this.element.queue( "tabs", function() { + self._trigger( "show", null, self._ui( self.anchors[ 0 ], self.panels[ 0 ] ) ); + }); + + this.load( 0 ); + } + + this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); + return this; + }, + + remove: function( index ) { + index = this._getIndex( index ); + var o = this.options, + $li = this.lis.eq( index ).remove(), + $panel = this.panels.eq( index ).remove(); + + // If selected tab was removed focus tab to the right or + // in case the last tab was removed the tab to the left. + if ( $li.hasClass( "ui-tabs-selected" ) && this.anchors.length > 1) { + this.select( index + ( index + 1 < this.anchors.length ? 1 : -1 ) ); + } + + o.disabled = $.map( + $.grep( o.disabled, function(n, i) { + return n != index; + }), + function( n, i ) { + return n >= index ? --n : n; + }); + + this._tabify(); + + this._trigger( "remove", null, this._ui( $li.find( "a" )[ 0 ], $panel[ 0 ] ) ); + return this; + }, + + enable: function( index ) { + index = this._getIndex( index ); + var o = this.options; + if ( $.inArray( index, o.disabled ) == -1 ) { + return; + } + + this.lis.eq( index ).removeClass( "ui-state-disabled" ); + o.disabled = $.grep( o.disabled, function( n, i ) { + return n != index; + }); + + this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); + return this; + }, + + disable: function( index ) { + index = this._getIndex( index ); + var self = this, o = this.options; + // cannot disable already selected tab + if ( index != o.selected ) { + this.lis.eq( index ).addClass( "ui-state-disabled" ); + + o.disabled.push( index ); + o.disabled.sort(); + + this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); + } + + return this; + }, + + select: function( index ) { + index = this._getIndex( index ); + if ( index == -1 ) { + if ( this.options.collapsible && this.options.selected != -1 ) { + index = this.options.selected; + } else { + return this; + } + } + this.anchors.eq( index ).trigger( this.options.event + ".tabs" ); + return this; + }, + + load: function( index ) { + index = this._getIndex( index ); + var self = this, + o = this.options, + a = this.anchors.eq( index )[ 0 ], + url = $.data( a, "load.tabs" ); + + this.abort(); + + // not remote or from cache + if ( !url || this.element.queue( "tabs" ).length !== 0 && $.data( a, "cache.tabs" ) ) { + this.element.dequeue( "tabs" ); + return; + } + + // load remote from here on + this.lis.eq( index ).addClass( "ui-state-processing" ); + + if ( o.spinner ) { + var span = $( "span", a ); + span.data( "label.tabs", span.html() ).html( o.spinner ); + } + + this.xhr = $.ajax( $.extend( {}, o.ajaxOptions, { + url: url, + success: function( r, s ) { + self.element.find( self._sanitizeSelector( a.hash ) ).html( r ); + + // take care of tab labels + self._cleanup(); + + if ( o.cache ) { + $.data( a, "cache.tabs", true ); + } + + self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) ); + try { + o.ajaxOptions.success( r, s ); + } + catch ( e ) {} + }, + error: function( xhr, s, e ) { + // take care of tab labels + self._cleanup(); + + self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) ); + try { + // Passing index avoid a race condition when this method is + // called after the user has selected another tab. + // Pass the anchor that initiated this request allows + // loadError to manipulate the tab content panel via $(a.hash) + o.ajaxOptions.error( xhr, s, index, a ); + } + catch ( e ) {} + } + } ) ); + + // last, so that load event is fired before show... + self.element.dequeue( "tabs" ); + + return this; + }, + + abort: function() { + // stop possibly running animations + this.element.queue( [] ); + this.panels.stop( false, true ); + + // "tabs" queue must not contain more than two elements, + // which are the callbacks for the latest clicked tab... + this.element.queue( "tabs", this.element.queue( "tabs" ).splice( -2, 2 ) ); + + // terminate pending requests from other tabs + if ( this.xhr ) { + this.xhr.abort(); + delete this.xhr; + } + + // take care of tab labels + this._cleanup(); + return this; + }, + + url: function( index, url ) { + this.anchors.eq( index ).removeData( "cache.tabs" ).data( "load.tabs", url ); + return this; + }, + + length: function() { + return this.anchors.length; + } +}); + +$.extend( $.ui.tabs, { + version: "1.8.20" +}); + +/* + * Tabs Extensions + */ + +/* + * Rotate + */ +$.extend( $.ui.tabs.prototype, { + rotation: null, + rotate: function( ms, continuing ) { + var self = this, + o = this.options; + + var rotate = self._rotate || ( self._rotate = function( e ) { + clearTimeout( self.rotation ); + self.rotation = setTimeout(function() { + var t = o.selected; + self.select( ++t < self.anchors.length ? t : 0 ); + }, ms ); + + if ( e ) { + e.stopPropagation(); + } + }); + + var stop = self._unrotate || ( self._unrotate = !continuing + ? function(e) { + if (e.clientX) { // in case of a true click + self.rotate(null); + } + } + : function( e ) { + rotate(); + }); + + // start rotation + if ( ms ) { + this.element.bind( "tabsshow", rotate ); + this.anchors.bind( o.event + ".tabs", stop ); + rotate(); + // stop rotation + } else { + clearTimeout( self.rotation ); + this.element.unbind( "tabsshow", rotate ); + this.anchors.unbind( o.event + ".tabs", stop ); + delete this._rotate; + delete this._unrotate; + } + + return this; + } +}); + +})( jQuery ); diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery-ui-1.8.20.min.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery-ui-1.8.20.min.js new file mode 100644 index 0000000..e1d2668 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery-ui-1.8.20.min.js @@ -0,0 +1,5 @@ +/*! jQuery UI - v1.8.20 - 2012-04-30 +* https://github.com/jquery/jquery-ui +* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.effects.core.js, jquery.effects.blind.js, jquery.effects.bounce.js, jquery.effects.clip.js, jquery.effects.drop.js, jquery.effects.explode.js, jquery.effects.fade.js, jquery.effects.fold.js, jquery.effects.highlight.js, jquery.effects.pulsate.js, jquery.effects.scale.js, jquery.effects.shake.js, jquery.effects.slide.js, jquery.effects.transfer.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.tabs.js +* Copyright (c) 2012 AUTHORS.txt; Licensed MIT */ +(function(a,b){function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f=b.parentNode,g=f.name,h;return!b.href||!g||f.nodeName.toLowerCase()!=="map"?!1:(h=a("img[usemap=#"+g+"]")[0],!!h&&d(h))}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}function d(b){return!a(b).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}a.ui=a.ui||{};if(a.ui.version)return;a.extend(a.ui,{version:"1.8.20",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return typeof b=="number"?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;return a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?b=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):b=this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0),/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length){var d=a(this[0]),e,f;while(d.length&&d[0]!==document){e=d.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){f=parseInt(d.css("zIndex"),10);if(!isNaN(f)&&f!==0)return f}d=d.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a.each(["Width","Height"],function(c,d){function h(b,c,d,f){return a.each(e,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),f&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)}),c}var e=d==="Width"?["Left","Right"]:["Top","Bottom"],f=d.toLowerCase(),g={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){return c===b?g["inner"+d].call(this):this.each(function(){a(this).css(f,h(this,c)+"px")})},a.fn["outer"+d]=function(b,c){return typeof b!="number"?g["outer"+d].call(this,b):this.each(function(){a(this).css(f,h(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));c.offsetHeight,a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=c.offsetHeight===100,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(!d||!a.element[0].parentNode)return;for(var e=0;e<d.length;e++)a.options[d[e][0]]&&d[e][1].apply(a.element,c)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(b,c){if(a(b).css("overflow")==="hidden")return!1;var d=c&&c==="left"?"scrollLeft":"scrollTop",e=!1;return b[d]>0?!0:(b[d]=1,e=b[d]>0,b[d]=0,e)},isOverAxis:function(a,b,c){return a>b&&a<b+c},isOver:function(b,c,d,e,f,g){return a.ui.isOverAxis(b,d,f)&&a.ui.isOverAxis(c,e,g)}})})(jQuery),function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d=0,e;(e=b[d])!=null;d++)try{a(e).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e=b.split(".")[0],f;b=b.split(".")[1],f=e+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][f]=function(c){return!!a.data(c,b)},a[e]=a[e]||{},a[e][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[e][b].prototype=a.extend(!0,g,{namespace:e,widgetName:b,widgetEventPrefix:a[e][b].prototype.widgetEventPrefix||b,widgetBaseClass:f},d),a.widget.bridge(b,a[e][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f=typeof e=="string",g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&e.charAt(0)==="_"?h:(f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;if(f!==d&&f!==b)return h=f,!1}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled "+"ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(arguments.length===0)return a.extend({},this.options);if(typeof c=="string"){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,a==="disabled"&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled"+" "+"ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent;if(f)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a,b){var c=!1;a(document).mouseup(function(a){c=!1}),a.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var b=this;this.element.bind("mousedown."+this.widgetName,function(a){return b._mouseDown(a)}).bind("click."+this.widgetName,function(c){if(!0===a.data(c.target,b.widgetName+".preventClickEvent"))return a.removeData(c.target,b.widgetName+".preventClickEvent"),c.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(b){if(c)return;this._mouseStarted&&this._mouseUp(b),this._mouseDownEvent=b;var d=this,e=b.which==1,f=typeof this.options.cancel=="string"&&b.target.nodeName?a(b.target).closest(this.options.cancel).length:!1;if(!e||f||!this._mouseCapture(b))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){d.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)){this._mouseStarted=this._mouseStart(b)!==!1;if(!this._mouseStarted)return b.preventDefault(),!0}return!0===a.data(b.target,this.widgetName+".preventClickEvent")&&a.removeData(b.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(a){return d._mouseMove(a)},this._mouseUpDelegate=function(a){return d._mouseUp(a)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),b.preventDefault(),c=!0,!0},_mouseMove:function(b){return!a.browser.msie||document.documentMode>=9||!!b.button?this._mouseStarted?(this._mouseDrag(b),b.preventDefault()):(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b)),!this._mouseStarted):this._mouseUp(b)},_mouseUp:function(b){return a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b)),!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(a){return this.mouseDelayMet},_mouseStart:function(a){},_mouseDrag:function(a){},_mouseStop:function(a){},_mouseCapture:function(a){return!0}})}(jQuery),function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},destroy:function(){if(!this.element.data("draggable"))return;return this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this},_mouseCapture:function(b){var c=this.options;return this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(b),this.handle?(c.iframeFix&&a(c.iframeFix===!0?"iframe":c.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(a(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(b){var c=this.options;return this.helper=this._createHelper(b),this._cacheHelperProportions(),a.ui.ddmanager&&(a.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,c.cursorAt&&this._adjustOffsetFromHelper(c.cursorAt),c.containment&&this._setContainment(),this._trigger("start",b)===!1?(this._clear(),!1):(this._cacheHelperProportions(),a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.helper.addClass("ui-draggable-dragging"),this._mouseDrag(b,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,b),!0)},_mouseDrag:function(b,c){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute");if(!c){var d=this._uiHash();if(this._trigger("drag",b,d)===!1)return this._mouseUp({}),!1;this.position=d.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";return a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),!1},_mouseStop:function(b){var c=!1;a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,b)),this.dropped&&(c=this.dropped,this.dropped=!1);var d=this.element[0],e=!1;while(d&&(d=d.parentNode))d==document&&(e=!0);if(!e&&this.options.helper==="original")return!1;if(this.options.revert=="invalid"&&!c||this.options.revert=="valid"&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)){var f=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){f._trigger("stop",b)!==!1&&f._clear()})}else this._trigger("stop",b)!==!1&&this._clear();return!1},_mouseUp:function(b){return this.options.iframeFix===!0&&a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b),a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?!0:!1;return a(this.options.handle,this.element).find("*").andSelf().each(function(){this==b.target&&(c=!0)}),c},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b])):c.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return d.parents("body").length||d.appendTo(c.appendTo=="parent"?this.element[0].parentNode:c.appendTo),d[0]!=this.element[0]&&!/(fixed|absolute)/.test(d.css("position"))&&d.css("position","absolute"),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[b.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,b.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(b.containment=="document"?0:a(window).scrollLeft())+a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(b.containment=="document"?0:a(window).scrollTop())+(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)&&b.containment.constructor!=Array){var c=a(b.containment),d=c[0];if(!d)return;var e=c.offset(),f=a(d).css("overflow")!="hidden";this.containment=[(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0),(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0),(f?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(f?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=c}else b.containment.constructor==Array&&(this.containment=b.containment)},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName),f=b.pageX,g=b.pageY;if(this.originalPosition){var h;if(this.containment){if(this.relative_container){var i=this.relative_container.offset();h=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]}else h=this.containment;b.pageX-this.offset.click.left<h[0]&&(f=h[0]+this.offset.click.left),b.pageY-this.offset.click.top<h[1]&&(g=h[1]+this.offset.click.top),b.pageX-this.offset.click.left>h[2]&&(f=h[2]+this.offset.click.left),b.pageY-this.offset.click.top>h[3]&&(g=h[3]+this.offset.click.top)}if(c.grid){var j=c.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY;g=h?j-this.offset.click.top<h[1]||j-this.offset.click.top>h[3]?j-this.offset.click.top<h[1]?j+c.grid[1]:j-c.grid[1]:j:j;var k=c.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0]:this.originalPageX;f=h?k-this.offset.click.left<h[0]||k-this.offset.click.left>h[2]?k-this.offset.click.left<h[0]?k+c.grid[0]:k-c.grid[0]:k:k}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(b,c,d){return d=d||this._uiHash(),a.ui.plugin.call(this,b,[c,d]),b=="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),a.Widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(a){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),a.extend(a.ui.draggable,{version:"1.8.20"}),a.ui.plugin.add("draggable","connectToSortable",{start:function(b,c){var d=a(this).data("draggable"),e=d.options,f=a.extend({},c,{item:d.element});d.sortables=[],a(e.connectToSortable).each(function(){var c=a.data(this,"sortable");c&&!c.options.disabled&&(d.sortables.push({instance:c,shouldRevert:c.options.revert}),c.refreshPositions(),c._trigger("activate",b,f))})},stop:function(b,c){var d=a(this).data("draggable"),e=a.extend({},c,{item:d.element});a.each(d.sortables,function(){this.instance.isOver?(this.instance.isOver=0,d.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(b),this.instance.options.helper=this.instance.options._helper,d.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",b,e))})},drag:function(b,c){var d=a(this).data("draggable"),e=this,f=function(b){var c=this.offset.click.top,d=this.offset.click.left,e=this.positionAbs.top,f=this.positionAbs.left,g=b.height,h=b.width,i=b.top,j=b.left;return a.ui.isOver(e+c,f+d,i,j,g,h)};a.each(d.sortables,function(f){this.instance.positionAbs=d.positionAbs,this.instance.helperProportions=d.helperProportions,this.instance.offset.click=d.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=a(e).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return c.helper[0]},b.target=this.instance.currentItem[0],this.instance._mouseCapture(b,!0),this.instance._mouseStart(b,!0,!0),this.instance.offset.click.top=d.offset.click.top,this.instance.offset.click.left=d.offset.click.left,this.instance.offset.parent.left-=d.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=d.offset.parent.top-this.instance.offset.parent.top,d._trigger("toSortable",b),d.dropped=this.instance.element,d.currentItem=d.element,this.instance.fromOutside=d),this.instance.currentItem&&this.instance._mouseDrag(b)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",b,this.instance._uiHash(this.instance)),this.instance._mouseStop(b,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),d._trigger("fromSortable",b),d.dropped=!1)})}}),a.ui.plugin.add("draggable","cursor",{start:function(b,c){var d=a("body"),e=a(this).data("draggable").options;d.css("cursor")&&(e._cursor=d.css("cursor")),d.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;d._cursor&&a("body").css("cursor",d._cursor)}}),a.ui.plugin.add("draggable","opacity",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("opacity")&&(e._opacity=d.css("opacity")),d.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;d._opacity&&a(c.helper).css("opacity",d._opacity)}}),a.ui.plugin.add("draggable","scroll",{start:function(b,c){var d=a(this).data("draggable");d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"&&(d.overflowOffset=d.scrollParent.offset())},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=!1;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!e.axis||e.axis!="x")d.overflowOffset.top+d.scrollParent[0].offsetHeight-b.pageY<e.scrollSensitivity?d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop+e.scrollSpeed:b.pageY-d.overflowOffset.top<e.scrollSensitivity&&(d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop-e.scrollSpeed);if(!e.axis||e.axis!="y")d.overflowOffset.left+d.scrollParent[0].offsetWidth-b.pageX<e.scrollSensitivity?d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft+e.scrollSpeed:b.pageX-d.overflowOffset.left<e.scrollSensitivity&&(d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft-e.scrollSpeed)}else{if(!e.axis||e.axis!="x")b.pageY-a(document).scrollTop()<e.scrollSensitivity?f=a(document).scrollTop(a(document).scrollTop()-e.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<e.scrollSensitivity&&(f=a(document).scrollTop(a(document).scrollTop()+e.scrollSpeed));if(!e.axis||e.axis!="y")b.pageX-a(document).scrollLeft()<e.scrollSensitivity?f=a(document).scrollLeft(a(document).scrollLeft()-e.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<e.scrollSensitivity&&(f=a(document).scrollLeft(a(document).scrollLeft()+e.scrollSpeed))}f!==!1&&a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(d,b)}}),a.ui.plugin.add("draggable","snap",{start:function(b,c){var d=a(this).data("draggable"),e=d.options;d.snapElements=[],a(e.snap.constructor!=String?e.snap.items||":data(draggable)":e.snap).each(function(){var b=a(this),c=b.offset();this!=d.element[0]&&d.snapElements.push({item:this,width:b.outerWidth(),height:b.outerHeight(),top:c.top,left:c.left})})},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=e.snapTolerance,g=c.offset.left,h=g+d.helperProportions.width,i=c.offset.top,j=i+d.helperProportions.height;for(var k=d.snapElements.length-1;k>=0;k--){var l=d.snapElements[k].left,m=l+d.snapElements[k].width,n=d.snapElements[k].top,o=n+d.snapElements[k].height;if(!(l-f<g&&g<m+f&&n-f<i&&i<o+f||l-f<g&&g<m+f&&n-f<j&&j<o+f||l-f<h&&h<m+f&&n-f<i&&i<o+f||l-f<h&&h<m+f&&n-f<j&&j<o+f)){d.snapElements[k].snapping&&d.options.snap.release&&d.options.snap.release.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=!1;continue}if(e.snapMode!="inner"){var p=Math.abs(n-j)<=f,q=Math.abs(o-i)<=f,r=Math.abs(l-h)<=f,s=Math.abs(m-g)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n-d.helperProportions.height,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l-d.helperProportions.width}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m}).left-d.margins.left)}var t=p||q||r||s;if(e.snapMode!="outer"){var p=Math.abs(n-i)<=f,q=Math.abs(o-j)<=f,r=Math.abs(l-g)<=f,s=Math.abs(m-h)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o-d.helperProportions.height,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m-d.helperProportions.width}).left-d.margins.left)}!d.snapElements[k].snapping&&(p||q||r||s||t)&&d.options.snap.snap&&d.options.snap.snap.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=p||q||r||s||t}}}),a.ui.plugin.add("draggable","stack",{start:function(b,c){var d=a(this).data("draggable").options,e=a.makeArray(a(d.stack)).sort(function(b,c){return(parseInt(a(b).css("zIndex"),10)||0)-(parseInt(a(c).css("zIndex"),10)||0)});if(!e.length)return;var f=parseInt(e[0].style.zIndex)||0;a(e).each(function(a){this.style.zIndex=f+a}),this[0].style.zIndex=f+e.length}}),a.ui.plugin.add("draggable","zIndex",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("zIndex")&&(e._zIndex=d.css("zIndex")),d.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;d._zIndex&&a(c.helper).css("zIndex",d._zIndex)}})}(jQuery),function(a,b){a.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var b=this.options,c=b.accept;this.isover=0,this.isout=1,this.accept=a.isFunction(c)?c:function(a){return a.is(c)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},a.ui.ddmanager.droppables[b.scope]=a.ui.ddmanager.droppables[b.scope]||[],a.ui.ddmanager.droppables[b.scope].push(this),b.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){var b=a.ui.ddmanager.droppables[this.options.scope];for(var c=0;c<b.length;c++)b[c]==this&&b.splice(c,1);return this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable"),this},_setOption:function(b,c){b=="accept"&&(this.accept=a.isFunction(c)?c:function(a){return a.is(c)}),a.Widget.prototype._setOption.apply(this,arguments)},_activate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),c&&this._trigger("activate",b,this.ui(c))},_deactivate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),c&&this._trigger("deactivate",b,this.ui(c))},_over:function(b){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return;this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",b,this.ui(c)))},_out:function(b){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return;this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",b,this.ui(c)))},_drop:function(b,c){var d=c||a.ui.ddmanager.current;if(!d||(d.currentItem||d.element)[0]==this.element[0])return!1;var e=!1;return this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var b=a.data(this,"droppable");if(b.options.greedy&&!b.options.disabled&&b.options.scope==d.options.scope&&b.accept.call(b.element[0],d.currentItem||d.element)&&a.ui.intersect(d,a.extend(b,{offset:b.element.offset()}),b.options.tolerance))return e=!0,!1}),e?!1:this.accept.call(this.element[0],d.currentItem||d.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",b,this.ui(d)),this.element):!1},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}}),a.extend(a.ui.droppable,{version:"1.8.20"}),a.ui.intersect=function(b,c,d){if(!c.offset)return!1;var e=(b.positionAbs||b.position.absolute).left,f=e+b.helperProportions.width,g=(b.positionAbs||b.position.absolute).top,h=g+b.helperProportions.height,i=c.offset.left,j=i+c.proportions.width,k=c.offset.top,l=k+c.proportions.height;switch(d){case"fit":return i<=e&&f<=j&&k<=g&&h<=l;case"intersect":return i<e+b.helperProportions.width/2&&f-b.helperProportions.width/2<j&&k<g+b.helperProportions.height/2&&h-b.helperProportions.height/2<l;case"pointer":var m=(b.positionAbs||b.position.absolute).left+(b.clickOffset||b.offset.click).left,n=(b.positionAbs||b.position.absolute).top+(b.clickOffset||b.offset.click).top,o=a.ui.isOver(n,m,k,i,c.proportions.height,c.proportions.width);return o;case"touch":return(g>=k&&g<=l||h>=k&&h<=l||g<k&&h>l)&&(e>=i&&e<=j||f>=i&&f<=j||e<i&&f>j);default:return!1}},a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(b,c){var d=a.ui.ddmanager.droppables[b.options.scope]||[],e=c?c.type:null,f=(b.currentItem||b.element).find(":data(droppable)").andSelf();g:for(var h=0;h<d.length;h++){if(d[h].options.disabled||b&&!d[h].accept.call(d[h].element[0],b.currentItem||b.element))continue;for(var i=0;i<f.length;i++)if(f[i]==d[h].element[0]){d[h].proportions.height=0;continue g}d[h].visible=d[h].element.css("display")!="none";if(!d[h].visible)continue;e=="mousedown"&&d[h]._activate.call(d[h],c),d[h].offset=d[h].element.offset(),d[h].proportions={width:d[h].element[0].offsetWidth,height:d[h].element[0].offsetHeight}}},drop:function(b,c){var d=!1;return a.each(a.ui.ddmanager.droppables[b.options.scope]||[],function(){if(!this.options)return;!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)&&(d=this._drop.call(this,c)||d),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],b.currentItem||b.element)&&(this.isout=1,this.isover=0,this._deactivate.call(this,c))}),d},dragStart:function(b,c){b.element.parents(":not(body,html)").bind("scroll.droppable",function(){b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)})},drag:function(b,c){b.options.refreshPositions&&a.ui.ddmanager.prepareOffsets(b,c),a.each(a.ui.ddmanager.droppables[b.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var d=a.ui.intersect(b,this,this.options.tolerance),e=!d&&this.isover==1?"isout":d&&this.isover==0?"isover":null;if(!e)return;var f;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");g.length&&(f=a.data(g[0],"droppable"),f.greedyChild=e=="isover"?1:0)}f&&e=="isover"&&(f.isover=0,f.isout=1,f._out.call(f,c)),this[e]=1,this[e=="isout"?"isover":"isout"]=0,this[e=="isover"?"_over":"_out"].call(this,c),f&&e=="isout"&&(f.isout=0,f.isover=1,f._over.call(f,c))})},dragStop:function(b,c){b.element.parents(":not(body,html)").unbind("scroll.droppable"),b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)}}}(jQuery),function(a,b){a.widget("ui.resizable",a.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var b=this,c=this.options;this.element.addClass("ui-resizable"),a.extend(this,{_aspectRatio:!!c.aspectRatio,aspectRatio:c.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:c.helper||c.ghost||c.animate?c.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(a('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=c.handles||(a(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var d=this.handles.split(",");this.handles={};for(var e=0;e<d.length;e++){var f=a.trim(d[e]),g="ui-resizable-"+f,h=a('<div class="ui-resizable-handle '+g+'"></div>');h.css({zIndex:c.zIndex}),"se"==f&&h.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[f]=".ui-resizable-"+f,this.element.append(h)}}this._renderAxis=function(b){b=b||this.element;for(var c in this.handles){this.handles[c].constructor==String&&(this.handles[c]=a(this.handles[c],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var d=a(this.handles[c],this.element),e=0;e=/sw|ne|nw|se|n|s/.test(c)?d.outerHeight():d.outerWidth();var f=["padding",/ne|nw|n/.test(c)?"Top":/se|sw|s/.test(c)?"Bottom":/^e$/.test(c)?"Right":"Left"].join("");b.css(f,e),this._proportionallyResize()}if(!a(this.handles[c]).length)continue}},this._renderAxis(this.element),this._handles=a(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!b.resizing){if(this.className)var a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=a&&a[1]?a[1]:"se"}}),c.autoHide&&(this._handles.hide(),a(this.element).addClass("ui-resizable-autohide").hover(function(){if(c.disabled)return;a(this).removeClass("ui-resizable-autohide"),b._handles.show()},function(){if(c.disabled)return;b.resizing||(a(this).addClass("ui-resizable-autohide"),b._handles.hide())})),this._mouseInit()},destroy:function(){this._mouseDestroy();var b=function(b){a(b).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){b(this.element);var c=this.element;c.after(this.originalElement.css({position:c.css("position"),width:c.outerWidth(),height:c.outerHeight(),top:c.css("top"),left:c.css("left")})).remove()}return this.originalElement.css("resize",this.originalResizeStyle),b(this.originalElement),this},_mouseCapture:function(b){var c=!1;for(var d in this.handles)a(this.handles[d])[0]==b.target&&(c=!0);return!this.options.disabled&&c},_mouseStart:function(b){var d=this.options,e=this.element.position(),f=this.element;this.resizing=!0,this.documentScroll={top:a(document).scrollTop(),left:a(document).scrollLeft()},(f.is(".ui-draggable")||/absolute/.test(f.css("position")))&&f.css({position:"absolute",top:e.top,left:e.left}),this._renderProxy();var g=c(this.helper.css("left")),h=c(this.helper.css("top"));d.containment&&(g+=a(d.containment).scrollLeft()||0,h+=a(d.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:g,top:h},this.size=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalSize=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalPosition={left:g,top:h},this.sizeDiff={width:f.outerWidth()-f.width(),height:f.outerHeight()-f.height()},this.originalMousePosition={left:b.pageX,top:b.pageY},this.aspectRatio=typeof d.aspectRatio=="number"?d.aspectRatio:this.originalSize.width/this.originalSize.height||1;var i=a(".ui-resizable-"+this.axis).css("cursor");return a("body").css("cursor",i=="auto"?this.axis+"-resize":i),f.addClass("ui-resizable-resizing"),this._propagate("start",b),!0},_mouseDrag:function(b){var c=this.helper,d=this.options,e={},f=this,g=this.originalMousePosition,h=this.axis,i=b.pageX-g.left||0,j=b.pageY-g.top||0,k=this._change[h];if(!k)return!1;var l=k.apply(this,[b,i,j]),m=a.browser.msie&&a.browser.version<7,n=this.sizeDiff;this._updateVirtualBoundaries(b.shiftKey);if(this._aspectRatio||b.shiftKey)l=this._updateRatio(l,b);return l=this._respectSize(l,b),this._propagate("resize",b),c.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",b,this.ui()),!1},_mouseStop:function(b){this.resizing=!1;var c=this.options,d=this;if(this._helper){var e=this._proportionallyResizeElements,f=e.length&&/textarea/i.test(e[0].nodeName),g=f&&a.ui.hasScroll(e[0],"left")?0:d.sizeDiff.height,h=f?0:d.sizeDiff.width,i={width:d.helper.width()-h,height:d.helper.height()-g},j=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,k=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;c.animate||this.element.css(a.extend(i,{top:k,left:j})),d.helper.height(d.size.height),d.helper.width(d.size.width),this._helper&&!c.animate&&this._proportionallyResize()}return a("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",b),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(a){var b=this.options,c,e,f,g,h;h={minWidth:d(b.minWidth)?b.minWidth:0,maxWidth:d(b.maxWidth)?b.maxWidth:Infinity,minHeight:d(b.minHeight)?b.minHeight:0,maxHeight:d(b.maxHeight)?b.maxHeight:Infinity};if(this._aspectRatio||a)c=h.minHeight*this.aspectRatio,f=h.minWidth/this.aspectRatio,e=h.maxHeight*this.aspectRatio,g=h.maxWidth/this.aspectRatio,c>h.minWidth&&(h.minWidth=c),f>h.minHeight&&(h.minHeight=f),e<h.maxWidth&&(h.maxWidth=e),g<h.maxHeight&&(h.maxHeight=g);this._vBoundaries=h},_updateCache:function(a){var b=this.options;this.offset=this.helper.offset(),d(a.left)&&(this.position.left=a.left),d(a.top)&&(this.position.top=a.top),d(a.height)&&(this.size.height=a.height),d(a.width)&&(this.size.width=a.width)},_updateRatio:function(a,b){var c=this.options,e=this.position,f=this.size,g=this.axis;return d(a.height)?a.width=a.height*this.aspectRatio:d(a.width)&&(a.height=a.width/this.aspectRatio),g=="sw"&&(a.left=e.left+(f.width-a.width),a.top=null),g=="nw"&&(a.top=e.top+(f.height-a.height),a.left=e.left+(f.width-a.width)),a},_respectSize:function(a,b){var c=this.helper,e=this._vBoundaries,f=this._aspectRatio||b.shiftKey,g=this.axis,h=d(a.width)&&e.maxWidth&&e.maxWidth<a.width,i=d(a.height)&&e.maxHeight&&e.maxHeight<a.height,j=d(a.width)&&e.minWidth&&e.minWidth>a.width,k=d(a.height)&&e.minHeight&&e.minHeight>a.height;j&&(a.width=e.minWidth),k&&(a.height=e.minHeight),h&&(a.width=e.maxWidth),i&&(a.height=e.maxHeight);var l=this.originalPosition.left+this.originalSize.width,m=this.position.top+this.size.height,n=/sw|nw|w/.test(g),o=/nw|ne|n/.test(g);j&&n&&(a.left=l-e.minWidth),h&&n&&(a.left=l-e.maxWidth),k&&o&&(a.top=m-e.minHeight),i&&o&&(a.top=m-e.maxHeight);var p=!a.width&&!a.height;return p&&!a.left&&a.top?a.top=null:p&&!a.top&&a.left&&(a.left=null),a},_proportionallyResize:function(){var b=this.options;if(!this._proportionallyResizeElements.length)return;var c=this.helper||this.element;for(var d=0;d<this._proportionallyResizeElements.length;d++){var e=this._proportionallyResizeElements[d];if(!this.borderDif){var f=[e.css("borderTopWidth"),e.css("borderRightWidth"),e.css("borderBottomWidth"),e.css("borderLeftWidth")],g=[e.css("paddingTop"),e.css("paddingRight"),e.css("paddingBottom"),e.css("paddingLeft")];this.borderDif=a.map(f,function(a,b){var c=parseInt(a,10)||0,d=parseInt(g[b],10)||0;return c+d})}if(!a.browser.msie||!a(c).is(":hidden")&&!a(c).parents(":hidden").length)e.css({height:c.height()-this.borderDif[0]-this.borderDif[2]||0,width:c.width()-this.borderDif[1]-this.borderDif[3]||0});else continue}},_renderProxy:function(){var b=this.element,c=this.options;this.elementOffset=b.offset();if(this._helper){this.helper=this.helper||a('<div style="overflow:hidden;"></div>');var d=a.browser.msie&&a.browser.version<7,e=d?1:0,f=d?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+f,height:this.element.outerHeight()+f,position:"absolute",left:this.elementOffset.left-e+"px",top:this.elementOffset.top-e+"px",zIndex:++c.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(a,b,c){return{width:this.originalSize.width+b}},w:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{left:f.left+b,width:e.width-b}},n:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{top:f.top+c,height:e.height-c}},s:function(a,b,c){return{height:this.originalSize.height+c}},se:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},sw:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,c,d]))},ne:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},nw:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,c,d]))}},_propagate:function(b,c){a.ui.plugin.call(this,b,[c,this.ui()]),b!="resize"&&this._trigger(b,c,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),a.extend(a.ui.resizable,{version:"1.8.20"}),a.ui.plugin.add("resizable","alsoResize",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=function(b){a(b).each(function(){var b=a(this);b.data("resizable-alsoresize",{width:parseInt(b.width(),10),height:parseInt(b.height(),10),left:parseInt(b.css("left"),10),top:parseInt(b.css("top"),10)})})};typeof e.alsoResize=="object"&&!e.alsoResize.parentNode?e.alsoResize.length?(e.alsoResize=e.alsoResize[0],f(e.alsoResize)):a.each(e.alsoResize,function(a){f(a)}):f(e.alsoResize)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.originalSize,g=d.originalPosition,h={height:d.size.height-f.height||0,width:d.size.width-f.width||0,top:d.position.top-g.top||0,left:d.position.left-g.left||0},i=function(b,d){a(b).each(function(){var b=a(this),e=a(this).data("resizable-alsoresize"),f={},g=d&&d.length?d:b.parents(c.originalElement[0]).length?["width","height"]:["width","height","top","left"];a.each(g,function(a,b){var c=(e[b]||0)+(h[b]||0);c&&c>=0&&(f[b]=c||null)}),b.css(f)})};typeof e.alsoResize=="object"&&!e.alsoResize.nodeType?a.each(e.alsoResize,function(a,b){i(a,b)}):i(e.alsoResize)},stop:function(b,c){a(this).removeData("resizable-alsoresize")}}),a.ui.plugin.add("resizable","animate",{stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d._proportionallyResizeElements,g=f.length&&/textarea/i.test(f[0].nodeName),h=g&&a.ui.hasScroll(f[0],"left")?0:d.sizeDiff.height,i=g?0:d.sizeDiff.width,j={width:d.size.width-i,height:d.size.height-h},k=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,l=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;d.element.animate(a.extend(j,l&&k?{top:l,left:k}:{}),{duration:e.animateDuration,easing:e.animateEasing,step:function(){var c={width:parseInt(d.element.css("width"),10),height:parseInt(d.element.css("height"),10),top:parseInt(d.element.css("top"),10),left:parseInt(d.element.css("left"),10)};f&&f.length&&a(f[0]).css({width:c.width,height:c.height}),d._updateCache(c),d._propagate("resize",b)}})}}),a.ui.plugin.add("resizable","containment",{start:function(b,d){var e=a(this).data("resizable"),f=e.options,g=e.element,h=f.containment,i=h instanceof a?h.get(0):/parent/.test(h)?g.parent().get(0):h;if(!i)return;e.containerElement=a(i);if(/document/.test(h)||h==document)e.containerOffset={left:0,top:0},e.containerPosition={left:0,top:0},e.parentData={element:a(document),left:0,top:0,width:a(document).width(),height:a(document).height()||document.body.parentNode.scrollHeight};else{var j=a(i),k=[];a(["Top","Right","Left","Bottom"]).each(function(a,b){k[a]=c(j.css("padding"+b))}),e.containerOffset=j.offset(),e.containerPosition=j.position(),e.containerSize={height:j.innerHeight()-k[3],width:j.innerWidth()-k[1]};var l=e.containerOffset,m=e.containerSize.height,n=e.containerSize.width,o=a.ui.hasScroll(i,"left")?i.scrollWidth:n,p=a.ui.hasScroll(i)?i.scrollHeight:m;e.parentData={element:i,left:l.left,top:l.top,width:o,height:p}}},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.containerSize,g=d.containerOffset,h=d.size,i=d.position,j=d._aspectRatio||b.shiftKey,k={top:0,left:0},l=d.containerElement;l[0]!=document&&/static/.test(l.css("position"))&&(k=g),i.left<(d._helper?g.left:0)&&(d.size.width=d.size.width+(d._helper?d.position.left-g.left:d.position.left-k.left),j&&(d.size.height=d.size.width/d.aspectRatio),d.position.left=e.helper?g.left:0),i.top<(d._helper?g.top:0)&&(d.size.height=d.size.height+(d._helper?d.position.top-g.top:d.position.top),j&&(d.size.width=d.size.height*d.aspectRatio),d.position.top=d._helper?g.top:0),d.offset.left=d.parentData.left+d.position.left,d.offset.top=d.parentData.top+d.position.top;var m=Math.abs((d._helper?d.offset.left-k.left:d.offset.left-k.left)+d.sizeDiff.width),n=Math.abs((d._helper?d.offset.top-k.top:d.offset.top-g.top)+d.sizeDiff.height),o=d.containerElement.get(0)==d.element.parent().get(0),p=/relative|absolute/.test(d.containerElement.css("position"));o&&p&&(m-=d.parentData.left),m+d.size.width>=d.parentData.width&&(d.size.width=d.parentData.width-m,j&&(d.size.height=d.size.width/d.aspectRatio)),n+d.size.height>=d.parentData.height&&(d.size.height=d.parentData.height-n,j&&(d.size.width=d.size.height*d.aspectRatio))},stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.position,g=d.containerOffset,h=d.containerPosition,i=d.containerElement,j=a(d.helper),k=j.offset(),l=j.outerWidth()-d.sizeDiff.width,m=j.outerHeight()-d.sizeDiff.height;d._helper&&!e.animate&&/relative/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m}),d._helper&&!e.animate&&/static/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m})}}),a.ui.plugin.add("resizable","ghost",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size;d.ghost=d.originalElement.clone(),d.ghost.css({opacity:.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof e.ghost=="string"?e.ghost:""),d.ghost.appendTo(d.helper)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})},stop:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.helper&&d.helper.get(0).removeChild(d.ghost.get(0))}}),a.ui.plugin.add("resizable","grid",{resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size,g=d.originalSize,h=d.originalPosition,i=d.axis,j=e._aspectRatio||b.shiftKey;e.grid=typeof e.grid=="number"?[e.grid,e.grid]:e.grid;var k=Math.round((f.width-g.width)/(e.grid[0]||1))*(e.grid[0]||1),l=Math.round((f.height-g.height)/(e.grid[1]||1))*(e.grid[1]||1);/^(se|s|e)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l):/^(ne)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l):/^(sw)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.left=h.left-k):(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l,d.position.left=h.left-k)}});var c=function(a){return parseInt(a,10)||0},d=function(a){return!isNaN(parseInt(a,10))}}(jQuery),function(a,b){a.widget("ui.selectable",a.ui.mouse,{options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var b=this;this.element.addClass("ui-selectable"),this.dragged=!1;var c;this.refresh=function(){c=a(b.options.filter,b.element[0]),c.addClass("ui-selectee"),c.each(function(){var b=a(this),c=b.offset();a.data(this,"selectable-item",{element:this,$element:b,left:c.left,top:c.top,right:c.left+b.outerWidth(),bottom:c.top+b.outerHeight(),startselected:!1,selected:b.hasClass("ui-selected"),selecting:b.hasClass("ui-selecting"),unselecting:b.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=c.addClass("ui-selectee"),this._mouseInit(),this.helper=a("<div class='ui-selectable-helper'></div>")},destroy:function(){return this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable"),this._mouseDestroy(),this},_mouseStart:function(b){var c=this;this.opos=[b.pageX,b.pageY];if(this.options.disabled)return;var d=this.options;this.selectees=a(d.filter,this.element[0]),this._trigger("start",b),a(d.appendTo).append(this.helper),this.helper.css({left:b.clientX,top:b.clientY,width:0,height:0}),d.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var d=a.data(this,"selectable-item");d.startselected=!0,!b.metaKey&&!b.ctrlKey&&(d.$element.removeClass("ui-selected"),d.selected=!1,d.$element.addClass("ui-unselecting"),d.unselecting=!0,c._trigger("unselecting",b,{unselecting:d.element}))}),a(b.target).parents().andSelf().each(function(){var d=a.data(this,"selectable-item");if(d){var e=!b.metaKey&&!b.ctrlKey||!d.$element.hasClass("ui-selected");return d.$element.removeClass(e?"ui-unselecting":"ui-selected").addClass(e?"ui-selecting":"ui-unselecting"),d.unselecting=!e,d.selecting=e,d.selected=e,e?c._trigger("selecting",b,{selecting:d.element}):c._trigger("unselecting",b,{unselecting:d.element}),!1}})},_mouseDrag:function(b){var c=this;this.dragged=!0;if(this.options.disabled)return;var d=this.options,e=this.opos[0],f=this.opos[1],g=b.pageX,h=b.pageY;if(e>g){var i=g;g=e,e=i}if(f>h){var i=h;h=f,f=i}return this.helper.css({left:e,top:f,width:g-e,height:h-f}),this.selectees.each(function(){var i=a.data(this,"selectable-item");if(!i||i.element==c.element[0])return;var j=!1;d.tolerance=="touch"?j=!(i.left>g||i.right<e||i.top>h||i.bottom<f):d.tolerance=="fit"&&(j=i.left>e&&i.right<g&&i.top>f&&i.bottom<h),j?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,c._trigger("selecting",b,{selecting:i.element}))):(i.selecting&&((b.metaKey||b.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),c._trigger("unselecting",b,{unselecting:i.element}))),i.selected&&!b.metaKey&&!b.ctrlKey&&!i.startselected&&(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,c._trigger("unselecting",b,{unselecting:i.element})))}),!1},_mouseStop:function(b){var c=this;this.dragged=!1;var d=this.options;return a(".ui-unselecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-unselecting"),d.unselecting=!1,d.startselected=!1,c._trigger("unselected",b,{unselected:d.element})}),a(".ui-selecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected"),d.selecting=!1,d.selected=!0,d.startselected=!0,c._trigger("selected",b,{selected:d.element})}),this._trigger("stop",b),this.helper.remove(),!1}}),a.extend(a.ui.selectable,{version:"1.8.20"})}(jQuery),function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var a=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){a.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--)this.items[b].item.removeData(this.widgetName+"-item");return this},_setOption:function(b,c){b==="disabled"?(this.options[b]=c,this.widget()[c?"addClass":"removeClass"]("ui-sortable-disabled")):a.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(b,c){var d=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(b);var e=null,f=this,g=a(b.target).parents().each(function(){if(a.data(this,d.widgetName+"-item")==f)return e=a(this),!1});a.data(b.target,d.widgetName+"-item")==f&&(e=a(b.target));if(!e)return!1;if(this.options.handle&&!c){var h=!1;a(this.options.handle,e).find("*").andSelf().each(function(){this==b.target&&(h=!0)});if(!h)return!1}return this.currentItem=e,this._removeCurrentsFromItems(),!0},_mouseStart:function(b,c,d){var e=this.options,f=this;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(b),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),e.containment&&this._setContainment(),e.cursor&&(a("body").css("cursor")&&(this._storedCursor=a("body").css("cursor")),a("body").css("cursor",e.cursor)),e.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",e.opacity)),e.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",e.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",b,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!d)for(var g=this.containers.length-1;g>=0;g--)this.containers[g]._trigger("activate",b,f._uiHash(this));return a.ui.ddmanager&&(a.ui.ddmanager.current=this),a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(b),!0},_mouseDrag:function(b){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var c=this.options,d=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-b.pageY<c.scrollSensitivity?this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop+c.scrollSpeed:b.pageY-this.overflowOffset.top<c.scrollSensitivity&&(this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop-c.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-b.pageX<c.scrollSensitivity?this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft+c.scrollSpeed:b.pageX-this.overflowOffset.left<c.scrollSensitivity&&(this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft-c.scrollSpeed)):(b.pageY-a(document).scrollTop()<c.scrollSensitivity?d=a(document).scrollTop(a(document).scrollTop()-c.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<c.scrollSensitivity&&(d=a(document).scrollTop(a(document).scrollTop()+c.scrollSpeed)),b.pageX-a(document).scrollLeft()<c.scrollSensitivity?d=a(document).scrollLeft(a(document).scrollLeft()-c.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<c.scrollSensitivity&&(d=a(document).scrollLeft(a(document).scrollLeft()+c.scrollSpeed))),d!==!1&&a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],g=f.item[0],h=this._intersectsWithPointer(f);if(!h)continue;if(g!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=g&&!a.ui.contains(this.placeholder[0],g)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],g):!0)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f))this._rearrange(b,f);else break;this._trigger("change",b,this._uiHash());break}}return this._contactContainers(b),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),this._trigger("sort",b,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(b,c){if(!b)return;a.ui.ddmanager&&!this.options.dropBehaviour&&a.ui.ddmanager.drop(this,b);if(this.options.revert){var d=this,e=d.placeholder.offset();d.reverting=!0,a(this.helper).animate({left:e.left-this.offset.parent.left-d.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-d.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){d._clear(b)})}else this._clear(b,c);return!1},cancel:function(){var b=this;if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("deactivate",null,b._uiHash(this)),this.containers[c].containerCache.over&&(this.containers[c]._trigger("out",null,b._uiHash(this)),this.containers[c].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),a.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?a(this.domPosition.prev).after(this.currentItem):a(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},a(c).each(function(){var c=(a(b.item||this).attr(b.attribute||"id")||"").match(b.expression||/(.+)[-=_](.+)/);c&&d.push((b.key||c[1]+"[]")+"="+(b.key&&b.expression?c[1]:c[2]))}),!d.length&&b.key&&d.push(b.key+"="),d.join("&")},toArray:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},c.each(function(){d.push(a(b.item||this).attr(b.attribute||"id")||"")}),d},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,d=this.positionAbs.top,e=d+this.helperProportions.height,f=a.left,g=f+a.width,h=a.top,i=h+a.height,j=this.offset.click.top,k=this.offset.click.left,l=d+j>h&&d+j<i&&b+k>f&&b+k<g;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?l:f<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<g&&h<d+this.helperProportions.height/2&&e-this.helperProportions.height/2<i},_intersectsWithPointer:function(b){var c=this.options.axis==="x"||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top,b.height),d=this.options.axis==="y"||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left,b.width),e=c&&d,f=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();return e?this.floating?g&&g=="right"||f=="down"?2:1:f&&(f=="down"?2:1):!1},_intersectsWithSides:function(b){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top+b.height/2,b.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left+b.width/2,b.width),e=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();return this.floating&&f?f=="right"&&d||f=="left"&&!d:e&&(e=="down"&&c||e=="up"&&!c)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){return this._refreshItems(a),this.refreshPositions(),this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(b){var c=this,d=[],e=[],f=this._connectWith();if(f&&b)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&e.push([a.isFunction(j.options.items)?j.options.items.call(j.element):a(j.options.items,j.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),j])}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var g=e.length-1;g>=0;g--)e[g][0].each(function(){d.push(this)});return a(d)},_removeCurrentsFromItems:function(){var a=this.currentItem.find(":data("+this.widgetName+"-item)");for(var b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(b){this.items=[],this.containers=[this];var c=this.items,d=this,e=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]],f=this._connectWith();if(f&&this.ready)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&(e.push([a.isFunction(j.options.items)?j.options.items.call(j.element[0],b,{item:this.currentItem}):a(j.options.items,j.element),j]),this.containers.push(j))}}for(var g=e.length-1;g>=0;g--){var k=e[g][1],l=e[g][0];for(var i=0,m=l.length;i<m;i++){var n=a(l[i]);n.data(this.widgetName+"-item",k),c.push({item:n,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var c=this.items.length-1;c>=0;c--){var d=this.items[c];if(d.instance!=this.currentContainer&&this.currentContainer&&d.item[0]!=this.currentItem[0])continue;var e=this.options.toleranceElement?a(this.options.toleranceElement,d.item):d.item;b||(d.width=e.outerWidth(),d.height=e.outerHeight());var f=e.offset();d.left=f.left,d.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var c=this.containers.length-1;c>=0;c--){var f=this.containers[c].element.offset();this.containers[c].containerCache.left=f.left,this.containers[c].containerCache.top=f.top,this.containers[c].containerCache.width=this.containers[c].element.outerWidth(),this.containers[c].containerCache.height=this.containers[c].element.outerHeight()}return this},_createPlaceholder:function(b){var c=b||this,d=c.options;if(!d.placeholder||d.placeholder.constructor==String){var e=d.placeholder;d.placeholder={element:function(){var b=a(document.createElement(c.currentItem[0].nodeName)).addClass(e||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return e||(b.style.visibility="hidden"),b},update:function(a,b){if(e&&!d.forcePlaceholderSize)return;b.height()||b.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10)),b.width()||b.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}c.placeholder=a(d.placeholder.element.call(c.element,c.currentItem)),c.currentItem.after(c.placeholder),d.placeholder.update(c,c.placeholder)},_contactContainers:function(b){var c=null,d=null;for(var e=this.containers.length-1;e>=0;e--){if(a.ui.contains(this.currentItem[0],this.containers[e].element[0]))continue;if(this._intersectsWith(this.containers[e].containerCache)){if(c&&a.ui.contains(this.containers[e].element[0],c.element[0]))continue;c=this.containers[e],d=e}else this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",b,this._uiHash(this)),this.containers[e].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1;else if(this.currentContainer!=this.containers[d]){var f=1e4,g=null,h=this.positionAbs[this.containers[d].floating?"left":"top"];for(var i=this.items.length-1;i>=0;i--){if(!a.ui.contains(this.containers[d].element[0],this.items[i].item[0]))continue;var j=this.items[i][this.containers[d].floating?"left":"top"];Math.abs(j-h)<f&&(f=Math.abs(j-h),g=this.items[i])}if(!g&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[d],g?this._rearrange(b,g,null,!0):this._rearrange(b,null,this.containers[d].element,!0),this._trigger("change",b,this._uiHash()),this.containers[d]._trigger("change",b,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1}},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b,this.currentItem])):c.helper=="clone"?this.currentItem.clone():this.currentItem;return d.parents("body").length||a(c.appendTo!="parent"?c.appendTo:this.currentItem[0].parentNode)[0].appendChild(d[0]),d[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(d[0].style.width==""||c.forceHelperSize)&&d.width(this.currentItem.width()),(d[0].style.height==""||c.forceHelperSize)&&d.height(this.currentItem.height()),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)){var c=a(b.containment)[0],d=a(b.containment).offset(),e=a(c).css("overflow")!="hidden";this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(e?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(e?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var f=b.pageX,g=b.pageY;if(this.originalPosition){this.containment&&(b.pageX-this.offset.click.left<this.containment[0]&&(f=this.containment[0]+this.offset.click.left),b.pageY-this.offset.click.top<this.containment[1]&&(g=this.containment[1]+this.offset.click.top),b.pageX-this.offset.click.left>this.containment[2]&&(f=this.containment[2]+this.offset.click.left),b.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top));if(c.grid){var h=this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1];g=this.containment?h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3]?h-this.offset.click.top<this.containment[1]?h+c.grid[1]:h-c.grid[1]:h:h;var i=this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0];f=this.containment?i-this.offset.click.left<this.containment[0]||i-this.offset.click.left>this.containment[2]?i-this.offset.click.left<this.containment[0]?i+c.grid[0]:i-c.grid[0]:i:i}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_rearrange:function(a,b,c,d){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var e=this,f=this.counter;window.setTimeout(function(){f==e.counter&&e.refreshPositions(!d)},0)},_clear:function(b,c){this.reverting=!1;var d=[],e=this;!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var f in this._storedCSS)if(this._storedCSS[f]=="auto"||this._storedCSS[f]=="static")this._storedCSS[f]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!c&&d.push(function(a){this._trigger("receive",a,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!c&&d.push(function(a){this._trigger("update",a,this._uiHash())});if(!a.ui.contains(this.element[0],this.currentItem[0])){c||d.push(function(a){this._trigger("remove",a,this._uiHash())});for(var f=this.containers.length-1;f>=0;f--)a.ui.contains(this.containers[f].element[0],this.currentItem[0])&&!c&&(d.push(function(a){return function(b){a._trigger("receive",b,this._uiHash(this))}}.call(this,this.containers[f])),d.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.containers[f])))}for(var f=this.containers.length-1;f>=0;f--)c||d.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over&&(d.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over=0);this._storedCursor&&a("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!c){this._trigger("beforeStop",b,this._uiHash());for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return!1}c||this._trigger("beforeStop",b,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!c){for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){a.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(b){var c=b||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:b?b.element:null}}}),a.extend(a.ui.sortable,{version:"1.8.20"})}(jQuery),jQuery.effects||function(a,b){function c(b){var c;return b&&b.constructor==Array&&b.length==3?b:(c=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b))?[parseInt(c[1],10),parseInt(c[2],10),parseInt(c[3],10)]:(c=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b))?[parseFloat(c[1])*2.55,parseFloat(c[2])*2.55,parseFloat(c[3])*2.55]:(c=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b))?[parseInt(c[1],16),parseInt(c[2],16),parseInt(c[3],16)]:(c=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b))?[parseInt(c[1]+c[1],16),parseInt(c[2]+c[2],16),parseInt(c[3]+c[3],16)]:(c=/rgba\(0, 0, 0, 0\)/.exec(b))?e.transparent:e[a.trim(b).toLowerCase()]}function d(b,d){var e;do{e=a.curCSS(b,d);if(e!=""&&e!="transparent"||a.nodeName(b,"body"))break;d="backgroundColor"}while(b=b.parentNode);return c(e)}function h(){var a=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,b={},c,d;if(a&&a.length&&a[0]&&a[a[0]]){var e=a.length;while(e--)c=a[e],typeof a[c]=="string"&&(d=c.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()}),b[d]=a[c])}else for(c in a)typeof a[c]=="string"&&(b[c]=a[c]);return b}function i(b){var c,d;for(c in b)d=b[c],(d==null||a.isFunction(d)||c in g||/scrollbar/.test(c)||!/color/i.test(c)&&isNaN(parseFloat(d)))&&delete b[c];return b}function j(a,b){var c={_:0},d;for(d in b)a[d]!=b[d]&&(c[d]=b[d]);return c}function k(b,c,d,e){typeof b=="object"&&(e=c,d=null,c=b,b=c.effect),a.isFunction(c)&&(e=c,d=null,c={});if(typeof c=="number"||a.fx.speeds[c])e=d,d=c,c={};return a.isFunction(d)&&(e=d,d=null),c=c||{},d=d||c.duration,d=a.fx.off?0:typeof d=="number"?d:d in a.fx.speeds?a.fx.speeds[d]:a.fx.speeds._default,e=e||c.complete,[b,c,d,e]}function l(b){return!b||typeof b=="number"||a.fx.speeds[b]?!0:typeof b=="string"&&!a.effects[b]?!0:!1}a.effects={},a.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,e){a.fx.step[e]=function(a){a.colorInit||(a.start=d(a.elem,e),a.end=c(a.end),a.colorInit=!0),a.elem.style[e]="rgb("+Math.max(Math.min(parseInt(a.pos*(a.end[0]-a.start[0])+a.start[0],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[1]-a.start[1])+a.start[1],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[2]-a.start[2])+a.start[2],10),255),0)+")"}});var e={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},f=["add","remove","toggle"],g={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};a.effects.animateClass=function(b,c,d,e){return a.isFunction(d)&&(e=d,d=null),this.queue(function(){var g=a(this),k=g.attr("style")||" ",l=i(h.call(this)),m,n=g.attr("class")||"";a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),m=i(h.call(this)),g.attr("class",n),g.animate(j(l,m),{queue:!1,duration:c,easing:d,complete:function(){a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),typeof g.attr("style")=="object"?(g.attr("style").cssText="",g.attr("style").cssText=k):g.attr("style",k),e&&e.apply(this,arguments),a.dequeue(this)}})})},a.fn.extend({_addClass:a.fn.addClass,addClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{add:b},c,d,e]):this._addClass(b)},_removeClass:a.fn.removeClass,removeClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{remove:b},c,d,e]):this._removeClass(b)},_toggleClass:a.fn.toggleClass,toggleClass:function(c,d,e,f,g){return typeof d=="boolean"||d===b?e?a.effects.animateClass.apply(this,[d?{add:c}:{remove:c},e,f,g]):this._toggleClass(c,d):a.effects.animateClass.apply(this,[{toggle:c},d,e,f])},switchClass:function(b,c,d,e,f){return a.effects.animateClass.apply(this,[{add:c,remove:b},d,e,f])}}),a.extend(a.effects,{version:"1.8.20",save:function(a,b){for(var c=0;c<b.length;c++)b[c]!==null&&a.data("ec.storage."+b[c],a[0].style[b[c]])},restore:function(a,b){for(var c=0;c<b.length;c++)b[c]!==null&&a.css(b[c],a.data("ec.storage."+b[c]))},setMode:function(a,b){return b=="toggle"&&(b=a.is(":hidden")?"show":"hide"),b},getBaseline:function(a,b){var c,d;switch(a[0]){case"top":c=0;break;case"middle":c=.5;break;case"bottom":c=1;break;default:c=a[0]/b.height}switch(a[1]){case"left":d=0;break;case"center":d=.5;break;case"right":d=1;break;default:d=a[1]/b.width}return{x:d,y:c}},createWrapper:function(b){if(b.parent().is(".ui-effects-wrapper"))return b.parent();var c={width:b.outerWidth(!0),height:b.outerHeight(!0),"float":b.css("float")},d=a("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e=document.activeElement;return b.wrap(d),(b[0]===e||a.contains(b[0],e))&&a(e).focus(),d=b.parent(),b.css("position")=="static"?(d.css({position:"relative"}),b.css({position:"relative"})):(a.extend(c,{position:b.css("position"),zIndex:b.css("z-index")}),a.each(["top","left","bottom","right"],function(a,d){c[d]=b.css(d),isNaN(parseInt(c[d],10))&&(c[d]="auto")}),b.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),d.css(c).show()},removeWrapper:function(b){var c,d=document.activeElement;return b.parent().is(".ui-effects-wrapper")?(c=b.parent().replaceWith(b),(b[0]===d||a.contains(b[0],d))&&a(d).focus(),c):b},setTransition:function(b,c,d,e){return e=e||{},a.each(c,function(a,c){var f=b.cssUnit(c);f[0]>0&&(e[c]=f[0]*d+f[1])}),e}}),a.fn.extend({effect:function(b,c,d,e){var f=k.apply(this,arguments),g={options:f[1],duration:f[2],callback:f[3]},h=g.options.mode,i=a.effects[b];return a.fx.off||!i?h?this[h](g.duration,g.callback):this.each(function(){g.callback&&g.callback.call(this)}):i.call(this,g)},_show:a.fn.show,show:function(a){if(l(a))return this._show.apply(this,arguments);var b=k.apply(this,arguments);return b[1].mode="show",this.effect.apply(this,b)},_hide:a.fn.hide,hide:function(a){if(l(a))return this._hide.apply(this,arguments);var b=k.apply(this,arguments);return b[1].mode="hide",this.effect.apply(this,b)},__toggle:a.fn.toggle,toggle:function(b){if(l(b)||typeof b=="boolean"||a.isFunction(b))return this.__toggle.apply(this,arguments);var c=k.apply(this,arguments);return c[1].mode="toggle",this.effect.apply(this,c)},cssUnit:function(b){var c=this.css(b),d=[];return a.each(["em","px","%","pt"],function(a,b){c.indexOf(b)>0&&(d=[parseFloat(c),b])}),d}}),a.easing.jswing=a.easing.swing,a.extend(a.easing,{def:"easeOutQuad",swing:function(b,c,d,e,f){return a.easing[a.easing.def](b,c,d,e,f)},easeInQuad:function(a,b,c,d,e){return d*(b/=e)*b+c},easeOutQuad:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c},easeInOutQuad:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b+c:-d/2*(--b*(b-2)-1)+c},easeInCubic:function(a,b,c,d,e){return d*(b/=e)*b*b+c},easeOutCubic:function(a,b,c,d,e){return d*((b=b/e-1)*b*b+1)+c},easeInOutCubic:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b+c:d/2*((b-=2)*b*b+2)+c},easeInQuart:function(a,b,c,d,e){return d*(b/=e)*b*b*b+c},easeOutQuart:function(a,b,c,d,e){return-d*((b=b/e-1)*b*b*b-1)+c},easeInOutQuart:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b*b+c:-d/2*((b-=2)*b*b*b-2)+c},easeInQuint:function(a,b,c,d,e){return d*(b/=e)*b*b*b*b+c},easeOutQuint:function(a,b,c,d,e){return d*((b=b/e-1)*b*b*b*b+1)+c},easeInOutQuint:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b*b*b+c:d/2*((b-=2)*b*b*b*b+2)+c},easeInSine:function(a,b,c,d,e){return-d*Math.cos(b/e*(Math.PI/2))+d+c},easeOutSine:function(a,b,c,d,e){return d*Math.sin(b/e*(Math.PI/2))+c},easeInOutSine:function(a,b,c,d,e){return-d/2*(Math.cos(Math.PI*b/e)-1)+c},easeInExpo:function(a,b,c,d,e){return b==0?c:d*Math.pow(2,10*(b/e-1))+c},easeOutExpo:function(a,b,c,d,e){return b==e?c+d:d*(-Math.pow(2,-10*b/e)+1)+c},easeInOutExpo:function(a,b,c,d,e){return b==0?c:b==e?c+d:(b/=e/2)<1?d/2*Math.pow(2,10*(b-1))+c:d/2*(-Math.pow(2,-10*--b)+2)+c},easeInCirc:function(a,b,c,d,e){return-d*(Math.sqrt(1-(b/=e)*b)-1)+c},easeOutCirc:function(a,b,c,d,e){return d*Math.sqrt(1-(b=b/e-1)*b)+c},easeInOutCirc:function(a,b,c,d,e){return(b/=e/2)<1?-d/2*(Math.sqrt(1-b*b)-1)+c:d/2*(Math.sqrt(1-(b-=2)*b)+1)+c},easeInElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e)==1)return c+d;g||(g=e*.3);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g))+c},easeOutElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e)==1)return c+d;g||(g=e*.3);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*b)*Math.sin((b*e-f)*2*Math.PI/g)+d+c},easeInOutElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e/2)==2)return c+d;g||(g=e*.3*1.5);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return b<1?-0.5*h*Math.pow(2,10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g)+c:h*Math.pow(2,-10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g)*.5+d+c},easeInBack:function(a,c,d,e,f,g){return g==b&&(g=1.70158),e*(c/=f)*c*((g+1)*c-g)+d},easeOutBack:function(a,c,d,e,f,g){return g==b&&(g=1.70158),e*((c=c/f-1)*c*((g+1)*c+g)+1)+d},easeInOutBack:function(a,c,d,e,f,g){return g==b&&(g=1.70158),(c/=f/2)<1?e/2*c*c*(((g*=1.525)+1)*c-g)+d:e/2*((c-=2)*c*(((g*=1.525)+1)*c+g)+2)+d},easeInBounce:function(b,c,d,e,f){return e-a.easing.easeOutBounce(b,f-c,0,e,f)+d},easeOutBounce:function(a,b,c,d,e){return(b/=e)<1/2.75?d*7.5625*b*b+c:b<2/2.75?d*(7.5625*(b-=1.5/2.75)*b+.75)+c:b<2.5/2.75?d*(7.5625*(b-=2.25/2.75)*b+.9375)+c:d*(7.5625*(b-=2.625/2.75)*b+.984375)+c},easeInOutBounce:function(b,c,d,e,f){return c<f/2?a.easing.easeInBounce(b,c*2,0,e,f)*.5+d:a.easing.easeOutBounce(b,c*2-f,0,e,f)*.5+e*.5+d}})}(jQuery),function(a,b){a.effects.blind=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"vertical";a.effects.save(c,d),c.show();var g=a.effects.createWrapper(c).css({overflow:"hidden"}),h=f=="vertical"?"height":"width",i=f=="vertical"?g.height():g.width();e=="show"&&g.css(h,0);var j={};j[h]=e=="show"?i:0,g.animate(j,b.duration,b.options.easing,function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}}(jQuery),function(a,b){a.effects.bounce=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"effect"),f=b.options.direction||"up",g=b.options.distance||20,h=b.options.times||5,i=b.duration||250;/show|hide/.test(e)&&d.push("opacity"),a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var j=f=="up"||f=="down"?"top":"left",k=f=="up"||f=="left"?"pos":"neg",g=b.options.distance||(j=="top"?c.outerHeight({margin:!0})/3:c.outerWidth({margin:!0})/3);e=="show"&&c.css("opacity",0).css(j,k=="pos"?-g:g),e=="hide"&&(g=g/(h*2)),e!="hide"&&h--;if(e=="show"){var l={opacity:1};l[j]=(k=="pos"?"+=":"-=")+g,c.animate(l,i/2,b.options.easing),g=g/2,h--}for(var m=0;m<h;m++){var n={},p={};n[j]=(k=="pos"?"-=":"+=")+g,p[j]=(k=="pos"?"+=":"-=")+g,c.animate(n,i/2,b.options.easing).animate(p,i/2,b.options.easing),g=e=="hide"?g*2:g/2}if(e=="hide"){var l={opacity:0};l[j]=(k=="pos"?"-=":"+=")+g,c.animate(l,i/2,b.options.easing,function(){c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)})}else{var n={},p={};n[j]=(k=="pos"?"-=":"+=")+g,p[j]=(k=="pos"?"+=":"-=")+g,c.animate(n,i/2,b.options.easing).animate(p,i/2,b.options.easing,function(){a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)})}c.queue("fx",function(){c.dequeue()}),c.dequeue()})}}(jQuery),function(a,b){a.effects.clip=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","height","width"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"vertical";a.effects.save(c,d),c.show();var g=a.effects.createWrapper(c).css({overflow:"hidden"}),h=c[0].tagName=="IMG"?g:c,i={size:f=="vertical"?"height":"width",position:f=="vertical"?"top":"left"},j=f=="vertical"?h.height():h.width();e=="show"&&(h.css(i.size,0),h.css(i.position,j/2));var k={};k[i.size]=e=="show"?j:0,k[i.position]=e=="show"?0:j/2,h.animate(k,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.drop=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","opacity"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"left";a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var g=f=="up"||f=="down"?"top":"left",h=f=="up"||f=="left"?"pos":"neg",i=b.options.distance||(g=="top"?c.outerHeight({margin:!0})/2:c.outerWidth({margin:!0})/2);e=="show"&&c.css("opacity",0).css(g,h=="pos"?-i:i);var j={opacity:e=="show"?1:0};j[g]=(e=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i,c.animate(j,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.explode=function(b){return this.queue(function(){var c=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3,d=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3;b.options.mode=b.options.mode=="toggle"?a(this).is(":visible")?"hide":"show":b.options.mode;var e=a(this).show().css("visibility","hidden"),f=e.offset();f.top-=parseInt(e.css("marginTop"),10)||0,f.left-=parseInt(e.css("marginLeft"),10)||0;var g=e.outerWidth(!0),h=e.outerHeight(!0);for(var i=0;i<c;i++)for(var j=0;j<d;j++)e.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-j*(g/d),top:-i*(h/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:g/d,height:h/c,left:f.left+j*(g/d)+(b.options.mode=="show"?(j-Math.floor(d/2))*(g/d):0),top:f.top+i*(h/c)+(b.options.mode=="show"?(i-Math.floor(c/2))*(h/c):0),opacity:b.options.mode=="show"?0:1}).animate({left:f.left+j*(g/d)+(b.options.mode=="show"?0:(j-Math.floor(d/2))*(g/d)),top:f.top+i*(h/c)+(b.options.mode=="show"?0:(i-Math.floor(c/2))*(h/c)),opacity:b.options.mode=="show"?1:0},b.duration||500);setTimeout(function(){b.options.mode=="show"?e.css({visibility:"visible"}):e.css({visibility:"visible"}).hide(),b.callback&&b.callback.apply(e[0]),e.dequeue(),a("div.ui-effects-explode").remove()},b.duration||500)})}}(jQuery),function(a,b){a.effects.fade=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"hide");c.animate({opacity:d},{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.fold=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.size||15,g=!!b.options.horizFirst,h=b.duration?b.duration/2:a.fx.speeds._default/2;a.effects.save(c,d),c.show();var i=a.effects.createWrapper(c).css({overflow:"hidden"}),j=e=="show"!=g,k=j?["width","height"]:["height","width"],l=j?[i.width(),i.height()]:[i.height(),i.width()],m=/([0-9]+)%/.exec(f);m&&(f=parseInt(m[1],10)/100*l[e=="hide"?0:1]),e=="show"&&i.css(g?{height:0,width:f}:{height:f,width:0});var n={},p={};n[k[0]]=e=="show"?l[0]:f,p[k[1]]=e=="show"?l[1]:0,i.animate(n,h,b.options.easing).animate(p,h,b.options.easing,function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}}(jQuery),function(a,b){a.effects.highlight=function(b){return this.queue(function(){var c=a(this),d=["backgroundImage","backgroundColor","opacity"],e=a.effects.setMode(c,b.options.mode||"show"),f={backgroundColor:c.css("backgroundColor")};e=="hide"&&(f.opacity=0),a.effects.save(c,d),c.show().css({backgroundImage:"none",backgroundColor:b.options.color||"#ffff99"}).animate(f,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),e=="show"&&!a.support.opacity&&this.style.removeAttribute("filter"),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.pulsate=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"show"),e=(b.options.times||5)*2-1,f=b.duration?b.duration/2:a.fx.speeds._default/2,g=c.is(":visible"),h=0;g||(c.css("opacity",0).show(),h=1),(d=="hide"&&g||d=="show"&&!g)&&e--;for(var i=0;i<e;i++)c.animate({opacity:h},f,b.options.easing),h=(h+1)%2;c.animate({opacity:h},f,b.options.easing,function(){h==0&&c.hide(),b.callback&&b.callback.apply(this,arguments)}),c.queue("fx",function(){c.dequeue()}).dequeue()})}}(jQuery),function(a,b){a.effects.puff=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"hide"),e=parseInt(b.options.percent,10)||150,f=e/100,g={height:c.height(),width:c.width()};a.extend(b.options,{fade:!0,mode:d,percent:d=="hide"?e:100,from:d=="hide"?g:{height:g.height*f,width:g.width*f}}),c.effect("scale",b.options,b.duration,b.callback),c.dequeue()})},a.effects.scale=function(b){return this.queue(function(){var c=a(this),d=a.extend(!0,{},b.options),e=a.effects.setMode(c,b.options.mode||"effect"),f=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:e=="hide"?0:100),g=b.options.direction||"both",h=b.options.origin;e!="effect"&&(d.origin=h||["middle","center"],d.restore=!0);var i={height:c.height(),width:c.width()};c.from=b.options.from||(e=="show"?{height:0,width:0}:i);var j={y:g!="horizontal"?f/100:1,x:g!="vertical"?f/100:1};c.to={height:i.height*j.y,width:i.width*j.x},b.options.fade&&(e=="show"&&(c.from.opacity=0,c.to.opacity=1),e=="hide"&&(c.from.opacity=1,c.to.opacity=0)),d.from=c.from,d.to=c.to,d.mode=e,c.effect("size",d,b.duration,b.callback),c.dequeue()})},a.effects.size=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","width","height","overflow","opacity"],e=["position","top","bottom","left","right","overflow","opacity"],f=["width","height","overflow"],g=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],i=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],j=a.effects.setMode(c,b.options.mode||"effect"),k=b.options.restore||!1,l=b.options.scale||"both",m=b.options.origin,n={height:c.height(),width:c.width()};c.from=b.options.from||n,c.to=b.options.to||n;if(m){var p=a.effects.getBaseline(m,n);c.from.top=(n.height-c.from.height)*p.y,c.from.left=(n.width-c.from.width)*p.x,c.to.top=(n.height-c.to.height)*p.y,c.to.left=(n.width-c.to.width)*p.x}var q={from:{y:c.from.height/n.height,x:c.from.width/n.width},to:{y:c.to.height/n.height,x:c.to.width/n.width}};if(l=="box"||l=="both")q.from.y!=q.to.y&&(d=d.concat(h),c.from=a.effects.setTransition(c,h,q.from.y,c.from),c.to=a.effects.setTransition(c,h,q.to.y,c.to)),q.from.x!=q.to.x&&(d=d.concat(i),c.from=a.effects.setTransition(c,i,q.from.x,c.from),c.to=a.effects.setTransition(c,i,q.to.x,c.to));(l=="content"||l=="both")&&q.from.y!=q.to.y&&(d=d.concat(g),c.from=a.effects.setTransition(c,g,q.from.y,c.from),c.to=a.effects.setTransition(c,g,q.to.y,c.to)),a.effects.save(c,k?d:e),c.show(),a.effects.createWrapper(c),c.css("overflow","hidden").css(c.from);if(l=="content"||l=="both")h=h.concat(["marginTop","marginBottom"]).concat(g),i=i.concat(["marginLeft","marginRight"]),f=d.concat(h).concat(i),c.find("*[width]").each(function(){var c=a(this);k&&a.effects.save(c,f);var d={height:c.height(),width:c.width()};c.from={height:d.height*q.from.y,width:d.width*q.from.x},c.to={height:d.height*q.to.y,width:d.width*q.to.x},q.from.y!=q.to.y&&(c.from=a.effects.setTransition(c,h,q.from.y,c.from),c.to=a.effects.setTransition(c,h,q.to.y,c.to)),q.from.x!=q.to.x&&(c.from=a.effects.setTransition(c,i,q.from.x,c.from),c.to=a.effects.setTransition(c,i,q.to.x,c.to)),c.css(c.from),c.animate(c.to,b.duration,b.options.easing,function(){k&&a.effects.restore(c,f)})});c.animate(c.to,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){c.to.opacity===0&&c.css("opacity",c.from.opacity),j=="hide"&&c.hide(),a.effects.restore(c,k?d:e),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.shake=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"effect"),f=b.options.direction||"left",g=b.options.distance||20,h=b.options.times||3,i=b.duration||b.options.duration||140;a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var j=f=="up"||f=="down"?"top":"left",k=f=="up"||f=="left"?"pos":"neg",l={},m={},n={};l[j]=(k=="pos"?"-=":"+=")+g,m[j]=(k=="pos"?"+=":"-=")+g*2,n[j]=(k=="pos"?"-=":"+=")+g*2,c.animate(l,i,b.options.easing);for(var p=1;p<h;p++)c.animate(m,i,b.options.easing).animate(n,i,b.options.easing);c.animate(m,i,b.options.easing).animate(l,i/2,b.options.easing,function(){a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)}),c.queue("fx",function(){c.dequeue()}),c.dequeue()})}}(jQuery),function(a,b){a.effects.slide=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"show"),f=b.options.direction||"left";a.effects.save(c,d),c.show(),a.effects.createWrapper(c).css({overflow:"hidden"});var g=f=="up"||f=="down"?"top":"left",h=f=="up"||f=="left"?"pos":"neg",i=b.options.distance||(g=="top"?c.outerHeight({margin:!0}):c.outerWidth({margin:!0}));e=="show"&&c.css(g,h=="pos"?isNaN(i)?"-"+i:-i:i);var j={};j[g]=(e=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i,c.animate(j,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}}(jQuery),function(a,b){a.effects.transfer=function(b){return this.queue(function(){var c=a(this),d=a(b.options.to),e=d.offset(),f={top:e.top,left:e.left,height:d.innerHeight(),width:d.innerWidth()},g=c.offset(),h=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(b.options.className).css({top:g.top,left:g.left,height:c.innerHeight(),width:c.innerWidth(),position:"absolute"}).animate(f,b.duration,b.options.easing,function(){h.remove(),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}}(jQuery),function(a,b){a.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:!0,clearStyle:!1,collapsible:!1,event:"click",fillSpace:!1,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var b=this,c=b.options;b.running=0,b.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix"),b.headers=b.element.find(c.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-focus")}),b.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(c.navigation){var d=b.element.find("a").filter(c.navigationFilter).eq(0);if(d.length){var e=d.closest(".ui-accordion-header");e.length?b.active=e:b.active=d.closest(".ui-accordion-content").prev()}}b.active=b._findActive(b.active||c.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"),b.active.next().addClass("ui-accordion-content-active"),b._createIcons(),b.resize(),b.element.attr("role","tablist"),b.headers.attr("role","tab").bind("keydown.accordion",function(a){return b._keydown(a)}).next().attr("role","tabpanel"),b.headers.not(b.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide(),b.active.length?b.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):b.headers.eq(0).attr("tabIndex",0),a.browser.safari||b.headers.find("a").attr("tabIndex",-1),c.event&&b.headers.bind(c.event.split(" ").join(".accordion ")+".accordion",function(a){b._clickHandler.call(b,a,this),a.preventDefault()})},_createIcons:function(){var b=this.options;b.icons&&(a("<span></span>").addClass("ui-icon "+b.icons.header).prependTo(this.headers),this.active.children(".ui-icon").toggleClass(b.icons.header).toggleClass(b.icons.headerSelected),this.element.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.children(".ui-icon").remove(),this.element.removeClass("ui-accordion-icons")},destroy:function(){var b=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex"),this.headers.find("a").removeAttr("tabIndex"),this._destroyIcons();var c=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");return(b.autoHeight||b.fillHeight)&&c.css("height",""),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b=="active"&&this.activate(c),b=="icons"&&(this._destroyIcons(),c&&this._createIcons()),b=="disabled"&&this.headers.add(this.headers.next())[c?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")},_keydown:function(b){if(this.options.disabled||b.altKey||b.ctrlKey)return;var c=a.ui.keyCode,d=this.headers.length,e=this.headers.index(b.target),f=!1;switch(b.keyCode){case c.RIGHT:case c.DOWN:f=this.headers[(e+1)%d];break;case c.LEFT:case c.UP:f=this.headers[(e-1+d)%d];break;case c.SPACE:case c.ENTER:this._clickHandler({target:b.target},b.target),b.preventDefault()}return f?(a(b.target).attr("tabIndex",-1),a(f).attr("tabIndex",0),f.focus(),!1):!0},resize:function(){var b=this.options,c;if(b.fillSpace){if(a.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}c=this.element.parent().height(),a.browser.msie&&this.element.parent().css("overflow",d),this.headers.each(function(){c-=a(this).outerHeight(!0)}),this.headers.next().each(function(){a(this).height(Math.max(0,c-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")}else b.autoHeight&&(c=0,this.headers.next().each(function(){c=Math.max(c,a(this).height("").height())}).height(c));return this},activate:function(a){this.options.active=a;var b=this._findActive(a)[0];return this._clickHandler({target:b},b),this},_findActive:function(b){return b?typeof b=="number"?this.headers.filter(":eq("+b+")"):this.headers.not(this.headers.not(b)):b===!1?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(b,c){var d=this.options;if(d.disabled)return;if(!b.target){if(!d.collapsible)return;this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),this.active.next().addClass("ui-accordion-content-active");var e=this.active.next(),f={options:d,newHeader:a([]),oldHeader:d.active,newContent:a([]),oldContent:e},g=this.active=a([]);this._toggle(g,e,f);return}var h=a(b.currentTarget||c),i=h[0]===this.active[0];d.active=d.collapsible&&i?!1:this.headers.index(h);if(this.running||!d.collapsible&&i)return;var j=this.active,g=h.next(),e=this.active.next(),f={options:d,newHeader:i&&d.collapsible?a([]):h,oldHeader:this.active,newContent:i&&d.collapsible?a([]):g,oldContent:e},k=this.headers.index(this.active[0])>this.headers.index(h[0]);this.active=i?a([]):h,this._toggle(g,e,f,i,k),j.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),i||(h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected),h.next().addClass("ui-accordion-content-active"));return},_toggle:function(b,c,d,e,f){var g=this,h=g.options;g.toShow=b,g.toHide=c,g.data=d;var i=function(){if(!g)return;return g._completed.apply(g,arguments)};g._trigger("changestart",null,g.data),g.running=c.size()===0?b.size():c.size();if(h.animated){var j={};h.collapsible&&e?j={toShow:a([]),toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace}:j={toShow:b,toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace},h.proxied||(h.proxied=h.animated),h.proxiedDuration||(h.proxiedDuration=h.duration),h.animated=a.isFunction(h.proxied)?h.proxied(j):h.proxied,h.duration=a.isFunction(h.proxiedDuration)?h.proxiedDuration(j):h.proxiedDuration;var k=a.ui.accordion.animations,l=h.duration,m=h.animated;m&&!k[m]&&!a.easing[m]&&(m="slide"),k[m]||(k[m]=function(a){this.slide(a,{easing:m,duration:l||700})}),k[m](j)}else h.collapsible&&e?b.toggle():(c.hide(),b.show()),i(!0);c.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur(),b.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(a){this.running=a?0:--this.running;if(this.running)return;this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""}),this.toHide.removeClass("ui-accordion-content-active"),this.toHide.length&&(this.toHide.parent()[0].className=this.toHide.parent()[0].className),this._trigger("change",null,this.data)}}),a.extend(a.ui.accordion,{version:"1.8.20",animations:{slide:function(b,c){b=a.extend({easing:"swing",duration:300},b,c);if(!b.toHide.size()){b.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},b);return}if(!b.toShow.size()){b.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},b);return}var d=b.toShow.css("overflow"),e=0,f={},g={},h=["height","paddingTop","paddingBottom"],i,j=b.toShow;i=j[0].style.width,j.width(j.parent().width()-parseFloat(j.css("paddingLeft"))-parseFloat(j.css("paddingRight"))-(parseFloat(j.css("borderLeftWidth"))||0)-(parseFloat(j.css("borderRightWidth"))||0)),a.each(h,function(c,d){g[d]="hide";var e=(""+a.css(b.toShow[0],d)).match(/^([\d+-.]+)(.*)$/);f[d]={value:e[1],unit:e[2]||"px"}}),b.toShow.css({height:0,overflow:"hidden"}).show(),b.toHide.filter(":hidden").each(b.complete).end().filter(":visible").animate(g,{step:function(a,c){c.prop=="height"&&(e=c.end-c.start===0?0:(c.now-c.start)/(c.end-c.start)),b.toShow[0].style[c.prop]=e*f[c.prop].value+f[c.prop].unit},duration:b.duration,easing:b.easing,complete:function(){b.autoHeight||b.toShow.css("height",""),b.toShow.css({width:i,overflow:d}),b.complete()}})},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1e3:200})}}})}(jQuery),function(a,b){var c=0;a.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function(){var b=this,c=this.element[0].ownerDocument,d;this.isMultiLine=this.element.is("textarea"),this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){if(b.options.disabled||b.element.propAttr("readOnly"))return;d=!1;var e=a.ui.keyCode;switch(c.keyCode){case e.PAGE_UP:b._move("previousPage",c);break;case e.PAGE_DOWN:b._move("nextPage",c);break;case e.UP:b._keyEvent("previous",c);break;case e.DOWN:b._keyEvent("next",c);break;case e.ENTER:case e.NUMPAD_ENTER:b.menu.active&&(d=!0,c.preventDefault());case e.TAB:if(!b.menu.active)return;b.menu.select(c);break;case e.ESCAPE:b.element.val(b.term),b.close(c);break;default:clearTimeout(b.searching),b.searching=setTimeout(function(){b.term!=b.element.val()&&(b.selectedItem=null,b.search(null,c))},b.options.delay)}}).bind("keypress.autocomplete",function(a){d&&(d=!1,a.preventDefault())}).bind("focus.autocomplete",function(){if(b.options.disabled)return;b.selectedItem=null,b.previous=b.element.val()}).bind("blur.autocomplete",function(a){if(b.options.disabled)return;clearTimeout(b.searching),b.closing=setTimeout(function(){b.close(a),b._change(a)},150)}),this._initSource(),this.menu=a("<ul></ul>").addClass("ui-autocomplete").appendTo(a(this.options.appendTo||"body",c)[0]).mousedown(function(c){var d=b.menu.element[0];a(c.target).closest(".ui-menu-item").length||setTimeout(function(){a(document).one("mousedown",function(c){c.target!==b.element[0]&&c.target!==d&&!a.ui.contains(d,c.target)&&b.close()})},1),setTimeout(function(){clearTimeout(b.closing)},13)}).menu({focus:function(a,c){var d=c.item.data("item.autocomplete");!1!==b._trigger("focus",a,{item:d})&&/^key/.test(a.originalEvent.type)&&b.element.val(d.value)},selected:function(a,d){var e=d.item.data("item.autocomplete"),f=b.previous;b.element[0]!==c.activeElement&&(b.element.focus(),b.previous=f,setTimeout(function(){b.previous=f,b.selectedItem=e},1)),!1!==b._trigger("select",a,{item:e})&&b.element.val(e.value),b.term=b.element.val(),b.close(a),b.selectedItem=e},blur:function(a,c){b.menu.element.is(":visible")&&b.element.val()!==b.term&&b.element.val(b.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu"),a.fn.bgiframe&&this.menu.element.bgiframe(),b.beforeunloadHandler=function(){b.element.removeAttr("autocomplete")},a(window).bind("beforeunload",b.beforeunloadHandler)},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup"),this.menu.element.remove(),a(window).unbind("beforeunload",this.beforeunloadHandler),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b==="source"&&this._initSource(),b==="appendTo"&&this.menu.element.appendTo(a(c||"body",this.element[0].ownerDocument)[0]),b==="disabled"&&c&&this.xhr&&this.xhr.abort()},_initSource:function(){var b=this,c,d;a.isArray(this.options.source)?(c=this.options.source,this.source=function(b,d){d(a.ui.autocomplete.filter(c,b.term))}):typeof this.options.source=="string"?(d=this.options.source,this.source=function(c,e){b.xhr&&b.xhr.abort(),b.xhr=a.ajax({url:d,data:c,dataType:"json",success:function(a,b){e(a)},error:function(){e([])}})}):this.source=this.options.source},search:function(a,b){a=a!=null?a:this.element.val(),this.term=this.element.val();if(a.length<this.options.minLength)return this.close(b);clearTimeout(this.closing);if(this._trigger("search",b)===!1)return;return this._search(a)},_search:function(a){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.source({term:a},this._response())},_response:function(){var a=this,b=++c;return function(d){b===c&&a.__response(d),a.pending--,a.pending||a.element.removeClass("ui-autocomplete-loading")}},__response:function(a){!this.options.disabled&&a&&a.length?(a=this._normalize(a),this._suggest(a),this._trigger("open")):this.close()},close:function(a){clearTimeout(this.closing),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.deactivate(),this._trigger("close",a))},_change:function(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem})},_normalize:function(b){return b.length&&b[0].label&&b[0].value?b:a.map(b,function(b){return typeof b=="string"?{label:b,value:b}:a.extend({label:b.label||b.value,value:b.value||b.label},b)})},_suggest:function(b){var c=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(c,b),this.menu.deactivate(),this.menu.refresh(),c.show(),this._resizeMenu(),c.position(a.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(new a.Event("mouseover"))},_resizeMenu:function(){var a=this.menu.element;a.outerWidth(Math.max(a.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(b,c){var d=this;a.each(c,function(a,c){d._renderItem(b,c)})},_renderItem:function(b,c){return a("<li></li>").data("item.autocomplete",c).append(a("<a></a>").text(c.label)).appendTo(b)},_move:function(a,b){if(!this.menu.element.is(":visible")){this.search(null,b);return}if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term),this.menu.deactivate();return}this.menu[a](b)},widget:function(){return this.menu.element},_keyEvent:function(a,b){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(a,b),b.preventDefault()}}),a.extend(a.ui.autocomplete,{escapeRegex:function(a){return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},filter:function(b,c){var d=new RegExp(a.ui.autocomplete.escapeRegex(c),"i");return a.grep(b,function(a){return d.test(a.label||a.value||a)})}})}(jQuery),function(a){a.widget("ui.menu",{_create:function(){var b=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(c){if(!a(c.target).closest(".ui-menu-item a").length)return;c.preventDefault(),b.select(c)}),this.refresh()},refresh:function(){var b=this,c=this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem");c.children("a").addClass("ui-corner-all").attr("tabindex",-1).mouseenter(function(c){b.activate(c,a(this).parent())}).mouseleave(function(){b.deactivate()})},activate:function(a,b){this.deactivate();if(this.hasScroll()){var c=b.offset().top-this.element.offset().top,d=this.element.scrollTop(),e=this.element.height();c<0?this.element.scrollTop(d+c):c>=e&&this.element.scrollTop(d+c-e+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end(),this._trigger("focus",a,{item:b})},deactivate:function(){if(!this.active)return;this.active.children("a").removeClass("ui-state-hover").removeAttr("id"),this._trigger("blur"),this.active=null},next:function(a){this.move("next",".ui-menu-item:first",a)},previous:function(a){this.move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(a,b,c){if(!this.active){this.activate(c,this.element.children(b));return}var d=this.active[a+"All"](".ui-menu-item").eq(0);d.length?this.activate(c,d):this.activate(c,this.element.children(b))},nextPage:function(b){if(this.hasScroll()){if(!this.active||this.last()){this.activate(b,this.element.children(".ui-menu-item:first"));return}var c=this.active.offset().top,d=this.element.height(),e=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c-d+a(this).height();return b<10&&b>-10});e.length||(e=this.element.children(".ui-menu-item:last")),this.activate(b,e)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))},previousPage:function(b){if(this.hasScroll()){if(!this.active||this.first()){this.activate(b,this.element.children(".ui-menu-item:last"));return}var c=this.active.offset().top,d=this.element.height(),e=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c+d-a(this).height();return b<10&&b>-10});e.length||(e=this.element.children(".ui-menu-item:first")),this.activate(b,e)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"))},hasScroll:function(){return this.element.height()<this.element[a.fn.prop?"prop":"attr"]("scrollHeight")},select:function(a){this._trigger("selected",a,{item:this.active})}})}(jQuery),function(a,b){var c,d,e,f,g="ui-button ui-widget ui-state-default ui-corner-all",h="ui-state-hover ui-state-active ",i="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",j=function(){var b=a(this).find(":ui-button");setTimeout(function(){b.button("refresh")},1)},k=function(b){var c=b.name,d=b.form,e=a([]);return c&&(d?e=a(d).find("[name='"+c+"']"):e=a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form})),e};a.widget("ui.button",{options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",j),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.propAttr("disabled"):this.element.propAttr("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var b=this,h=this.options,i=this.type==="checkbox"||this.type==="radio",l="ui-state-hover"+(i?"":" ui-state-active"),m="ui-state-focus";h.label===null&&(h.label=this.buttonElement.html()),this.buttonElement.addClass(g).attr("role","button").bind("mouseenter.button",function(){if(h.disabled)return;a(this).addClass("ui-state-hover"),this===c&&a(this).addClass("ui-state-active")}).bind("mouseleave.button",function(){if(h.disabled)return;a(this).removeClass(l)}).bind("click.button",function(a){h.disabled&&(a.preventDefault(),a.stopImmediatePropagation())}),this.element.bind("focus.button",function(){b.buttonElement.addClass(m)}).bind("blur.button",function(){b.buttonElement.removeClass(m)}),i&&(this.element.bind("change.button",function(){if(f)return;b.refresh()}),this.buttonElement.bind("mousedown.button",function(a){if(h.disabled)return;f=!1,d=a.pageX,e=a.pageY}).bind("mouseup.button",function(a){if(h.disabled)return;if(d!==a.pageX||e!==a.pageY)f=!0})),this.type==="checkbox"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).toggleClass("ui-state-active"),b.buttonElement.attr("aria-pressed",b.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).addClass("ui-state-active"),b.buttonElement.attr("aria-pressed","true");var c=b.element[0];k(c).not(c).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown.button",function(){if(h.disabled)return!1;a(this).addClass("ui-state-active"),c=this,a(document).one("mouseup",function(){c=null})}).bind("mouseup.button",function(){if(h.disabled)return!1;a(this).removeClass("ui-state-active")}).bind("keydown.button",function(b){if(h.disabled)return!1;(b.keyCode==a.ui.keyCode.SPACE||b.keyCode==a.ui.keyCode.ENTER)&&a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(b){b.keyCode===a.ui.keyCode.SPACE&&a(this).click()})),this._setOption("disabled",h.disabled),this._resetButton()},_determineButtonType:function(){this.element.is(":checkbox")?this.type="checkbox":this.element.is(":radio")?this.type="radio":this.element.is("input")?this.type="input":this.type="button";if(this.type==="checkbox"||this.type==="radio"){var a=this.element.parents().filter(":last"),b="label[for='"+this.element.attr("id")+"']";this.buttonElement=a.find(b),this.buttonElement.length||(a=a.length?a.siblings():this.element.siblings(),this.buttonElement=a.filter(b),this.buttonElement.length||(this.buttonElement=a.find(b))),this.element.addClass("ui-helper-hidden-accessible");var c=this.element.is(":checked");c&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.attr("aria-pressed",c)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(g+" "+h+" "+i).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title"),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments);if(b==="disabled"){c?this.element.propAttr("disabled",!0):this.element.propAttr("disabled",!1);return}this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b),this.type==="radio"?k(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var b=this.buttonElement.removeClass(i),c=a("<span></span>",this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary,f=[];d.primary||d.secondary?(this.options.text&&f.push("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary")),d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>"),d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>"),this.options.text||(f.push(e?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||b.attr("title",c))):f.push("ui-button-text-only"),b.addClass(f.join(" "))}}),a.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c),a.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var b=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(b?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(b?"ui-corner-left":"ui-corner-right").end().end()},destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy"),a.Widget.prototype.destroy.call(this)}})}(jQuery),function($,undefined){function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}function bindHover(a){var b="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return a.bind("mouseout",function(a){var c=$(a.target).closest(b);if(!c.length)return;c.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(c){var d=$(c.target).closest(b);if($.datepicker._isDisabledDatepicker(instActive.inline?a.parent()[0]:instActive.input[0])||!d.length)return;d.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),d.addClass("ui-state-hover"),d.hasClass("ui-datepicker-prev")&&d.addClass("ui-datepicker-prev-hover"),d.hasClass("ui-datepicker-next")&&d.addClass("ui-datepicker-next-hover")})}function extendRemove(a,b){$.extend(a,b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}function isArray(a){return a&&($.browser.safari&&typeof a=="object"&&a.length||a.constructor&&a.constructor.toString().match(/\Array\(\)/))}$.extend($.ui,{datepicker:{version:"1.8.20"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){return extendRemove(this._defaults,a||{}),this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(a,b){var c=a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:c,input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:b?bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')):this.dpDiv}},_connectDatepicker:function(a,b){var c=$(a);b.append=$([]),b.trigger=$([]);if(c.hasClass(this.markerClassName))return;this._attachments(c,b),c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),this._autoSize(b),$.data(a,PROP_NAME,b),b.settings.disabled&&this._disableDatepicker(a)},_attachments:function(a,b){var c=this._get(b,"appendText"),d=this._get(b,"isRTL");b.append&&b.append.remove(),c&&(b.append=$('<span class="'+this._appendClass+'">'+c+"</span>"),a[d?"before":"after"](b.append)),a.unbind("focus",this._showDatepicker),b.trigger&&b.trigger.remove();var e=this._get(b,"showOn");(e=="focus"||e=="both")&&a.focus(this._showDatepicker);if(e=="button"||e=="both"){var f=this._get(b,"buttonText"),g=this._get(b,"buttonImage");b.trigger=$(this._get(b,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:g,alt:f,title:f}):$('<button type="button"></button>').addClass(this._triggerClass).html(g==""?f:$("<img/>").attr({src:g,alt:f,title:f}))),a[d?"before":"after"](b.trigger),b.trigger.click(function(){return $.datepicker._datepickerShowing&&$.datepicker._lastInput==a[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=a[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(a[0])):$.datepicker._showDatepicker(a[0]),!1})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var d=function(a){var b=0,c=0;for(var d=0;d<a.length;d++)a[d].length>b&&(b=a[d].length,c=d);return c};b.setMonth(d(this._get(a,c.match(/MM/)?"monthNames":"monthNamesShort"))),b.setDate(d(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=$(a);if(c.hasClass(this.markerClassName))return;c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),$.data(a,PROP_NAME,b),this._setDate(b,this._getDefaultDate(b),!0),this._updateDatepicker(b),this._updateAlternate(b),b.settings.disabled&&this._disableDatepicker(a),b.dpDiv.css("display","block")},_dialogDatepicker:function(a,b,c,d,e){var f=this._dialogInst;if(!f){this.uuid+=1;var g="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+g+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),f=this._dialogInst=this._newInst(this._dialogInput,!1),f.settings={},$.data(this._dialogInput[0],PROP_NAME,f)}extendRemove(f.settings,d||{}),b=b&&b.constructor==Date?this._formatDate(f,b):b,this._dialogInput.val(b),this._pos=e?e.length?e:[e.pageX,e.pageY]:null;if(!this._pos){var h=document.documentElement.clientWidth,i=document.documentElement.clientHeight,j=document.documentElement.scrollLeft||document.body.scrollLeft,k=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[h/2-100+j,i/2-150+k]}return this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),f.settings.onSelect=c,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,f),this},_destroyDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();$.removeData(a,PROP_NAME),d=="input"?(c.append.remove(),c.trigger.remove(),b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(d=="div"||d=="span")&&b.removeClass(this.markerClassName).empty()},_enableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!1,c.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().removeClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b})},_disableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!0,c.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().addClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b}),this._disabledInputs[this._disabledInputs.length]=a},_isDisabledDatepicker:function(a){if(!a)return!1;for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return!0;return!1},_getInst:function(a){try{return $.data(a,PROP_NAME)}catch(b){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(a,b,c){var d=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?$.extend({},$.datepicker._defaults):d?b=="all"?$.extend({},d.settings):this._get(d,b):null;var e=b||{};typeof b=="string"&&(e={},e[b]=c);if(d){this._curInst==d&&this._hideDatepicker();var f=this._getDateDatepicker(a,!0),g=this._getMinMaxDate(d,"min"),h=this._getMinMaxDate(d,"max");extendRemove(d.settings,e),g!==null&&e.dateFormat!==undefined&&e.minDate===undefined&&(d.settings.minDate=this._formatDate(d,g)),h!==null&&e.dateFormat!==undefined&&e.maxDate===undefined&&(d.settings.maxDate=this._formatDate(d,h)),this._attachments($(a),d),this._autoSize(d),this._setDate(d,f),this._updateAlternate(d),this._updateDatepicker(d)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){var b=this._getInst(a);b&&this._updateDatepicker(b)},_setDateDatepicker:function(a,b){var c=this._getInst(a);c&&(this._setDate(c,b),this._updateDatepicker(c),this._updateAlternate(c))},_getDateDatepicker:function(a,b){var c=this._getInst(a);return c&&!c.inline&&this._setDateFromField(c,b),c?this._getDate(c):null},_doKeyDown:function(a){var b=$.datepicker._getInst(a.target),c=!0,d=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=!0;if($.datepicker._datepickerShowing)switch(a.keyCode){case 9:$.datepicker._hideDatepicker(),c=!1;break;case 13:var e=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",b.dpDiv);e[0]&&$.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,e[0]);var f=$.datepicker._get(b,"onSelect");if(f){var g=$.datepicker._formatDate(b);f.apply(b.input?b.input[0]:null,[g,b])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 35:(a.ctrlKey||a.metaKey)&&$.datepicker._clearDate(a.target),c=a.ctrlKey||a.metaKey;break;case 36:(a.ctrlKey||a.metaKey)&&$.datepicker._gotoToday(a.target),c=a.ctrlKey||a.metaKey;break;case 37:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?1:-1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 38:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,-7,"D"),c=a.ctrlKey||a.metaKey;break;case 39:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?-1:1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 40:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,7,"D"),c=a.ctrlKey||a.metaKey;break;default:c=!1}else a.keyCode==36&&a.ctrlKey?$.datepicker._showDatepicker(this):c=!1;c&&(a.preventDefault(),a.stopPropagation())},_doKeyPress:function(a){var b=$.datepicker._getInst(a.target);if($.datepicker._get(b,"constrainInput")){var c=$.datepicker._possibleChars($.datepicker._get(b,"dateFormat")),d=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||a.metaKey||d<" "||!c||c.indexOf(d)>-1}},_doKeyUp:function(a){var b=$.datepicker._getInst(a.target);if(b.input.val()!=b.lastVal)try{var c=$.datepicker.parseDate($.datepicker._get(b,"dateFormat"),b.input?b.input.val():null,$.datepicker._getFormatConfig(b));c&&($.datepicker._setDateFromField(b),$.datepicker._updateAlternate(b),$.datepicker._updateDatepicker(b))}catch(d){$.datepicker.log(d)}return!0},_showDatepicker:function(a){a=a.target||a,a.nodeName.toLowerCase()!="input"&&(a=$("input",a.parentNode)[0]);if($.datepicker._isDisabledDatepicker(a)||$.datepicker._lastInput==a)return;var b=$.datepicker._getInst(a);$.datepicker._curInst&&$.datepicker._curInst!=b&&($.datepicker._curInst.dpDiv.stop(!0,!0),b&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var c=$.datepicker._get(b,"beforeShow"),d=c?c.apply(a,[a,b]):{};if(d===!1)return;extendRemove(b.settings,d),b.lastVal=null,$.datepicker._lastInput=a,$.datepicker._setDateFromField(b),$.datepicker._inDialog&&(a.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(a),$.datepicker._pos[1]+=a.offsetHeight);var e=!1;$(a).parents().each(function(){return e|=$(this).css("position")=="fixed",!e}),e&&$.browser.opera&&($.datepicker._pos[0]-=document.documentElement.scrollLeft,$.datepicker._pos[1]-=document.documentElement.scrollTop);var f={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,b.dpDiv.empty(),b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(b),f=$.datepicker._checkOffset(b,f,e),b.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":e?"fixed":"absolute",display:"none",left:f.left+"px",top:f.top+"px"});if(!b.inline){var g=$.datepicker._get(b,"showAnim"),h=$.datepicker._get(b,"duration"),i=function(){var a=b.dpDiv.find("iframe.ui-datepicker-cover");if(!!a.length){var c=$.datepicker._getBorders(b.dpDiv);a.css({left:-c[0],top:-c[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})}};b.dpDiv.zIndex($(a).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&$.effects[g]?b.dpDiv.show(g,$.datepicker._get(b,"showOptions"),h,i):b.dpDiv[g||"show"](g?h:null,i),(!g||!h)&&i(),b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus(),$.datepicker._curInst=b}},_updateDatepicker:function(a){var b=this;b.maxRows=4;var c=$.datepicker._getBorders(a.dpDiv);instActive=a,a.dpDiv.empty().append(this._generateHTML(a));var d=a.dpDiv.find("iframe.ui-datepicker-cover");!d.length||d.css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}),a.dpDiv.find("."+this._dayOverClass+" a").mouseover();var e=this._getNumberOfMonths(a),f=e[1],g=17;a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),f>1&&a.dpDiv.addClass("ui-datepicker-multi-"+f).css("width",g*f+"em"),a.dpDiv[(e[0]!=1||e[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),a==$.datepicker._curInst&&$.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var h=a.yearshtml;setTimeout(function(){h===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml),h=a.yearshtml=null},0)}},_getBorders:function(a){var b=function(a){return{thin:1,medium:2,thick:3}[a]||a};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var d=a.dpDiv.outerWidth(),e=a.dpDiv.outerHeight(),f=a.input?a.input.outerWidth():0,g=a.input?a.input.outerHeight():0,h=document.documentElement.clientWidth+$(document).scrollLeft(),i=document.documentElement.clientHeight+$(document).scrollTop();return b.left-=this._get(a,"isRTL")?d-f:0,b.left-=c&&b.left==a.input.offset().left?$(document).scrollLeft():0,b.top-=c&&b.top==a.input.offset().top+g?$(document).scrollTop():0,b.left-=Math.min(b.left,b.left+d>h&&h>d?Math.abs(b.left+d-h):0),b.top-=Math.min(b.top,b.top+e>i&&i>e?Math.abs(e+g):0),b},_findPos:function(a){var b=this._getInst(a),c=this._get(b,"isRTL");while(a&&(a.type=="hidden"||a.nodeType!=1||$.expr.filters.hidden(a)))a=a[c?"previousSibling":"nextSibling"];var d=$(a).offset();return[d.left,d.top]},_hideDatepicker:function(a){var b=this._curInst;if(!b||a&&b!=$.data(a,PROP_NAME))return;if(this._datepickerShowing){var c=this._get(b,"showAnim"),d=this._get(b,"duration"),e=function(){$.datepicker._tidyDialog(b)};$.effects&&$.effects[c]?b.dpDiv.hide(c,$.datepicker._get(b,"showOptions"),d,e):b.dpDiv[c=="slideDown"?"slideUp":c=="fadeIn"?"fadeOut":"hide"](c?d:null,e),c||e(),this._datepickerShowing=!1;var f=this._get(b,"onClose");f&&f.apply(b.input?b.input[0]:null,[b.input?b.input.val():"",b]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(!$.datepicker._curInst)return;var b=$(a.target),c=$.datepicker._getInst(b[0]);(b[0].id!=$.datepicker._mainDivId&&b.parents("#"+$.datepicker._mainDivId).length==0&&!b.hasClass($.datepicker.markerClassName)&&!b.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||b.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=c)&&$.datepicker._hideDatepicker()},_adjustDate:function(a,b,c){var d=$(a),e=this._getInst(d[0]);if(this._isDisabledDatepicker(d[0]))return;this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c),this._updateDatepicker(e)},_gotoToday:function(a){var b=$(a),c=this._getInst(b[0]);if(this._get(c,"gotoCurrent")&&c.currentDay)c.selectedDay=c.currentDay,c.drawMonth=c.selectedMonth=c.currentMonth,c.drawYear=c.selectedYear=c.currentYear;else{var d=new Date;c.selectedDay=d.getDate(),c.drawMonth=c.selectedMonth=d.getMonth(),c.drawYear=c.selectedYear=d.getFullYear()}this._notifyChange(c),this._adjustDate(b)},_selectMonthYear:function(a,b,c){var d=$(a),e=this._getInst(d[0]);e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10),this._notifyChange(e),this._adjustDate(d)},_selectDay:function(a,b,c,d){var e=$(a);if($(d).hasClass(this._unselectableClass)||this._isDisabledDatepicker(e[0]))return;var f=this._getInst(e[0]);f.selectedDay=f.currentDay=$("a",d).html(),f.selectedMonth=f.currentMonth=b,f.selectedYear=f.currentYear=c,this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))},_clearDate:function(a){var b=$(a),c=this._getInst(b[0]);this._selectDate(b,"")},_selectDate:function(a,b){var c=$(a),d=this._getInst(c[0]);b=b!=null?b:this._formatDate(d),d.input&&d.input.val(b),this._updateAlternate(d);var e=this._get(d,"onSelect");e?e.apply(d.input?d.input[0]:null,[b,d]):d.input&&d.input.trigger("change"),d.inline?this._updateDatepicker(d):(this._hideDatepicker(),this._lastInput=d.input[0],typeof d.input[0]!="object"&&d.input.focus(),this._lastInput=null)},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||this._get(a,"dateFormat"),d=this._getDate(a),e=this.formatDate(c,d,this._getFormatConfig(a));$(b).each(function(){$(this).val(e)})}},noWeekends:function(a){var b=a.getDay();return[b>0&&b<6,""]},iso8601Week:function(a){var b=new Date(a.getTime());b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;var d=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff;d=typeof d!="string"?d:(new Date).getFullYear()%100+parseInt(d,10);var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?c.dayNames:null)||this._defaults.dayNames,g=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,h=(c?c.monthNames:null)||this._defaults.monthNames,i=-1,j=-1,k=-1,l=-1,m=!1,n=function(b){var c=s+1<a.length&&a.charAt(s+1)==b;return c&&s++,c},o=function(a){var c=n(a),d=a=="@"?14:a=="!"?20:a=="y"&&c?4:a=="o"?3:2,e=new RegExp("^\\d{1,"+d+"}"),f=b.substring(r).match(e);if(!f)throw"Missing number at position "+r;return r+=f[0].length,parseInt(f[0],10)},p=function(a,c,d){var e=$.map(n(a)?d:c,function(a,b){return[[b,a]]}).sort(function(a,b){return-(a[1].length-b[1].length)}),f=-1;$.each(e,function(a,c){var d=c[1];if(b.substr(r,d.length).toLowerCase()==d.toLowerCase())return f=c[0],r+=d.length,!1});if(f!=-1)return f+1;throw"Unknown name at position "+r},q=function(){if(b.charAt(r)!=a.charAt(s))throw"Unexpected literal at position "+r;r++},r=0;for(var s=0;s<a.length;s++)if(m)a.charAt(s)=="'"&&!n("'")?m=!1:q();else switch(a.charAt(s)){case"d":k=o("d");break;case"D":p("D",e,f);break;case"o":l=o("o");break;case"m":j=o("m");break;case"M":j=p("M",g,h);break;case"y":i=o("y");break;case"@":var t=new Date(o("@"));i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"!":var t=new Date((o("!")-this._ticksTo1970)/1e4);i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"'":n("'")?q():m=!0;break;default:q()}if(r<b.length)throw"Extra/unparsed characters found in date: "+b.substring(r);i==-1?i=(new Date).getFullYear():i<100&&(i+=(new Date).getFullYear()-(new Date).getFullYear()%100+(i<=d?0:-100));if(l>-1){j=1,k=l;do{var u=this._getDaysInMonth(i,j-1);if(k<=u)break;j++,k-=u}while(!0)}var t=this._daylightSavingAdjust(new Date(i,j-1,k));if(t.getFullYear()!=i||t.getMonth()+1!=j||t.getDate()!=k)throw"Invalid date";return t},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(a,b,c){if(!b)return"";var d=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,e=(c?c.dayNames:null)||this._defaults.dayNames,f=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,h=function(b){var c=m+1<a.length&&a.charAt(m+1)==b;return c&&m++,c},i=function(a,b,c){var d=""+b;if(h(a))while(d.length<c)d="0"+d;return d},j=function(a,b,c,d){return h(a)?d[b]:c[b]},k="",l=!1;if(b)for(var m=0;m<a.length;m++)if(l)a.charAt(m)=="'"&&!h("'")?l=!1:k+=a.charAt(m);else switch(a.charAt(m)){case"d":k+=i("d",b.getDate(),2);break;case"D":k+=j("D",b.getDay(),d,e);break;case"o":k+=i("o",Math.round(((new Date(b.getFullYear(),b.getMonth(),b.getDate())).getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":k+=i("m",b.getMonth()+1,2);break;case"M":k+=j("M",b.getMonth(),f,g);break;case"y":k+=h("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case"@":k+=b.getTime();break;case"!":k+=b.getTime()*1e4+this._ticksTo1970;break;case"'":h("'")?k+="'":l=!0;break;default:k+=a.charAt(m)}return k},_possibleChars:function(a){var b="",c=!1,d=function(b){var c=e+1<a.length&&a.charAt(e+1)==b;return c&&e++,c};for(var e=0;e<a.length;e++)if(c)a.charAt(e)=="'"&&!d("'")?c=!1:b+=a.charAt(e);else switch(a.charAt(e)){case"d":case"m":case"y":case"@":b+="0123456789";break;case"D":case"M":return null;case"'":d("'")?b+="'":c=!0;break;default:b+=a.charAt(e)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()==a.lastVal)return;var c=this._get(a,"dateFormat"),d=a.lastVal=a.input?a.input.val():null,e,f;e=f=this._getDefaultDate(a);var g=this._getFormatConfig(a);try{e=this.parseDate(c,d,g)||f}catch(h){this.log(h),d=b?"":d}a.selectedDay=e.getDate(),a.drawMonth=a.selectedMonth=e.getMonth(),a.drawYear=a.selectedYear=e.getFullYear(),a.currentDay=d?e.getDate():0,a.currentMonth=d?e.getMonth():0,a.currentYear=d?e.getFullYear():0,this._adjustInstDate(a)},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))},_determineDate:function(a,b,c){var d=function(a){var b=new Date;return b.setDate(b.getDate()+a),b},e=function(b){try{return $.datepicker.parseDate($.datepicker._get(a,"dateFormat"),b,$.datepicker._getFormatConfig(a))}catch(c){}var d=(b.toLowerCase().match(/^c/)?$.datepicker._getDate(a):null)||new Date,e=d.getFullYear(),f=d.getMonth(),g=d.getDate(),h=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,i=h.exec(b);while(i){switch(i[2]||"d"){case"d":case"D":g+=parseInt(i[1],10);break;case"w":case"W":g+=parseInt(i[1],10)*7;break;case"m":case"M":f+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f));break;case"y":case"Y":e+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f))}i=h.exec(b)}return new Date(e,f,g)},f=b==null||b===""?c:typeof b=="string"?e(b):typeof b=="number"?isNaN(b)?c:d(b):new Date(b.getTime());return f=f&&f.toString()=="Invalid Date"?c:f,f&&(f.setHours(0),f.setMinutes(0),f.setSeconds(0),f.setMilliseconds(0)),this._daylightSavingAdjust(f)},_daylightSavingAdjust:function(a){return a?(a.setHours(a.getHours()>12?a.getHours()+2:0),a):null},_setDate:function(a,b,c){var d=!b,e=a.selectedMonth,f=a.selectedYear,g=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=g.getDate(),a.drawMonth=a.selectedMonth=a.currentMonth=g.getMonth(),a.drawYear=a.selectedYear=a.currentYear=g.getFullYear(),(e!=a.selectedMonth||f!=a.selectedYear)&&!c&&this._notifyChange(a),this._adjustInstDate(a),a.input&&a.input.val(d?"":this._formatDate(a))},_getDate:function(a){var b=!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return b},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),d=this._get(a,"showButtonPanel"),e=this._get(a,"hideIfNoPrevNext"),f=this._get(a,"navigationAsDateFormat"),g=this._getNumberOfMonths(a),h=this._get(a,"showCurrentAtPos"),i=this._get(a,"stepMonths"),j=g[0]!=1||g[1]!=1,k=this._daylightSavingAdjust(a.currentDay?new Date(a.currentYear,a.currentMonth,a.currentDay):new Date(9999,9,9)),l=this._getMinMaxDate(a,"min"),m=this._getMinMaxDate(a,"max"),n=a.drawMonth-h,o=a.drawYear;n<0&&(n+=12,o--);if(m){var p=this._daylightSavingAdjust(new Date(m.getFullYear(),m.getMonth()-g[0]*g[1]+1,m.getDate()));p=l&&p<l?l:p;while(this._daylightSavingAdjust(new Date(o,n,1))>p)n--,n<0&&(n=11,o--)}a.drawMonth=n,a.drawYear=o;var q=this._get(a,"prevText");q=f?this.formatDate(q,this._daylightSavingAdjust(new Date(o,n-i,1)),this._getFormatConfig(a)):q;var r=this._canAdjustMonth(a,-1,o,n)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', -"+i+", 'M');\""+' title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>":e?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>",s=this._get(a,"nextText");s=f?this.formatDate(s,this._daylightSavingAdjust(new Date(o,n+i,1)),this._getFormatConfig(a)):s;var t=this._canAdjustMonth(a,1,o,n)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', +"+i+", 'M');\""+' title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>":e?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>",u=this._get(a,"currentText"),v=this._get(a,"gotoCurrent")&&a.currentDay?k:b;u=f?this.formatDate(u,v,this._getFormatConfig(a)):u;var w=a.inline?"":'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+dpuuid+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>",x=d?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?w:"")+(this._isInRange(a,v)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._gotoToday('#"+a.id+"');\""+">"+u+"</button>":"")+(c?"":w)+"</div>":"",y=parseInt(this._get(a,"firstDay"),10);y=isNaN(y)?0:y;var z=this._get(a,"showWeek"),A=this._get(a,"dayNames"),B=this._get(a,"dayNamesShort"),C=this._get(a,"dayNamesMin"),D=this._get(a,"monthNames"),E=this._get(a,"monthNamesShort"),F=this._get(a,"beforeShowDay"),G=this._get(a,"showOtherMonths"),H=this._get(a,"selectOtherMonths"),I=this._get(a,"calculateWeek")||this.iso8601Week,J=this._getDefaultDate(a),K="";for(var L=0;L<g[0];L++){var M="";this.maxRows=4;for(var N=0;N<g[1];N++){var O=this._daylightSavingAdjust(new Date(o,n,a.selectedDay)),P=" ui-corner-all",Q="";if(j){Q+='<div class="ui-datepicker-group';if(g[1]>1)switch(N){case 0:Q+=" ui-datepicker-group-first",P=" ui-corner-"+(c?"right":"left");break;case g[1]-1:Q+=" ui-datepicker-group-last",P=" ui-corner-"+(c?"left":"right");break;default:Q+=" ui-datepicker-group-middle",P=""}Q+='">'}Q+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+P+'">'+(/all|left/.test(P)&&L==0?c?t:r:"")+(/all|right/.test(P)&&L==0?c?r:t:"")+this._generateMonthYearHeader(a,n,o,l,m,L>0||N>0,D,E)+'</div><table class="ui-datepicker-calendar"><thead>'+"<tr>";var R=z?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(var S=0;S<7;S++){var T=(S+y)%7;R+="<th"+((S+y+6)%7>=5?' class="ui-datepicker-week-end"':"")+">"+'<span title="'+A[T]+'">'+C[T]+"</span></th>"}Q+=R+"</tr></thead><tbody>";var U=this._getDaysInMonth(o,n);o==a.selectedYear&&n==a.selectedMonth&&(a.selectedDay=Math.min(a.selectedDay,U));var V=(this._getFirstDayOfMonth(o,n)-y+7)%7,W=Math.ceil((V+U)/7),X=j?this.maxRows>W?this.maxRows:W:W;this.maxRows=X;var Y=this._daylightSavingAdjust(new Date(o,n,1-V));for(var Z=0;Z<X;Z++){Q+="<tr>";var _=z?'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(Y)+"</td>":"";for(var S=0;S<7;S++){var ba=F?F.apply(a.input?a.input[0]:null,[Y]):[!0,""],bb=Y.getMonth()!=n,bc=bb&&!H||!ba[0]||l&&Y<l||m&&Y>m;_+='<td class="'+((S+y+6)%7>=5?" ui-datepicker-week-end":"")+(bb?" ui-datepicker-other-month":"")+(Y.getTime()==O.getTime()&&n==a.selectedMonth&&a._keyEvent||J.getTime()==Y.getTime()&&J.getTime()==O.getTime()?" "+this._dayOverClass:"")+(bc?" "+this._unselectableClass+" ui-state-disabled":"")+(bb&&!G?"":" "+ba[1]+(Y.getTime()==k.getTime()?" "+this._currentClass:"")+(Y.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!bb||G)&&ba[2]?' title="'+ba[2]+'"':"")+(bc?"":' onclick="DP_jQuery_'+dpuuid+".datepicker._selectDay('#"+a.id+"',"+Y.getMonth()+","+Y.getFullYear()+', this);return false;"')+">"+(bb&&!G?" ":bc?'<span class="ui-state-default">'+Y.getDate()+"</span>":'<a class="ui-state-default'+(Y.getTime()==b.getTime()?" ui-state-highlight":"")+(Y.getTime()==k.getTime()?" ui-state-active":"")+(bb?" ui-priority-secondary":"")+'" href="#">'+Y.getDate()+"</a>")+"</td>",Y.setDate(Y.getDate()+1),Y=this._daylightSavingAdjust(Y)}Q+=_+"</tr>"}n++,n>11&&(n=0,o++),Q+="</tbody></table>"+(j?"</div>"+(g[0]>0&&N==g[1]-1?'<div class="ui-datepicker-row-break"></div>':""):""),M+=Q}K+=M}return K+=x+($.browser.msie&&parseInt($.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':""),a._keyEvent=!1,K},_generateMonthYearHeader:function(a,b,c,d,e,f,g,h){var i=this._get(a,"changeMonth"),j=this._get(a,"changeYear"),k=this._get(a,"showMonthAfterYear"),l='<div class="ui-datepicker-title">',m="";if(f||!i)m+='<span class="ui-datepicker-month">'+g[b]+"</span>";else{var n=d&&d.getFullYear()==c,o=e&&e.getFullYear()==c;m+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" "+">";for(var p=0;p<12;p++)(!n||p>=d.getMonth())&&(!o||p<=e.getMonth())&&(m+='<option value="'+p+'"'+(p==b?' selected="selected"':"")+">"+h[p]+"</option>");m+="</select>"}k||(l+=m+(f||!i||!j?" ":""));if(!a.yearshtml){a.yearshtml="";if(f||!j)l+='<span class="ui-datepicker-year">'+c+"</span>";else{var q=this._get(a,"yearRange").split(":"),r=(new Date).getFullYear(),s=function(a){var b=a.match(/c[+-].*/)?c+parseInt(a.substring(1),10):a.match(/[+-].*/)?r+parseInt(a,10):parseInt(a,10);return isNaN(b)?r:b},t=s(q[0]),u=Math.max(t,s(q[1]||""));t=d?Math.max(t,d.getFullYear()):t,u=e?Math.min(u,e.getFullYear()):u,a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" "+">";for(;t<=u;t++)a.yearshtml+='<option value="'+t+'"'+(t==c?' selected="selected"':"")+">"+t+"</option>";a.yearshtml+="</select>",l+=a.yearshtml,a.yearshtml=null}}return l+=this._get(a,"yearSuffix"),k&&(l+=(f||!i||!j?" ":"")+m),l+="</div>",l},_adjustInstDate:function(a,b,c){var d=a.drawYear+(c=="Y"?b:0),e=a.drawMonth+(c=="M"?b:0),f=Math.min(a.selectedDay,this._getDaysInMonth(d,e))+(c=="D"?b:0),g=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(d,e,f)));a.selectedDay=g.getDate(),a.drawMonth=a.selectedMonth=g.getMonth(),a.drawYear=a.selectedYear=g.getFullYear(),(c=="M"||c=="Y")&&this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max"),e=c&&b<c?c:b;return e=d&&e>d?d:e,e},_notifyChange:function(a){var b=this._get(a,"onChangeMonthYear");b&&b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){var b=this._get(a,"numberOfMonths");return b==null?[1,1]:typeof b=="number"?[1,b]:b},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-this._daylightSavingAdjust(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,d){var e=this._getNumberOfMonths(a),f=this._daylightSavingAdjust(new Date(c,d+(b<0?b:e[0]*e[1]),1));return b<0&&f.setDate(this._getDaysInMonth(f.getFullYear(),f.getMonth())),this._isInRange(a,f)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!d||b.getTime()<=d.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");return b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10),{shortYearCutoff:b,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,d){b||(a.currentDay=a.selectedDay,a.currentMonth=a.selectedMonth,a.currentYear=a.selectedYear);var e=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(d,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),e,this._getFormatConfig(a))}}),$.fn.datepicker=function(a){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv),$.datepicker.initialized=!0);var b=Array.prototype.slice.call(arguments,1);return typeof a!="string"||a!="isDisabled"&&a!="getDate"&&a!="widget"?a=="option"&&arguments.length==2&&typeof arguments[1]=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b)):this.each(function(){typeof a=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this].concat(b)):$.datepicker._attachDatepicker(this,a)}):$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b))},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.8.20",window["DP_jQuery_"+dpuuid]=$}(jQuery),function(a,b){var c="ui-dialog ui-widget ui-widget-content ui-corner-all ",d={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},e={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},f=a.attrFn||{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0,click:!0};a.widget("ui.dialog",{options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",collision:"fit",using:function(b){var c=a(this).css(b).offset().top;c<0&&a(this).css("top",b.top-c)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&&(this.originalTitle=""),this.options.title=this.options.title||this.originalTitle;var b=this,d=b.options,e=d.title||" ",f=a.ui.dialog.getTitleId(b.element),g=(b.uiDialog=a("<div></div>")).appendTo(document.body).hide().addClass(c+d.dialogClass).css({zIndex:d.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(c){d.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}).attr({role:"dialog","aria-labelledby":f}).mousedown(function(a){b.moveToTop(!1,a)}),h=b.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g),i=(b.uiDialogTitlebar=a("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),j=a('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){j.addClass("ui-state-hover")},function(){j.removeClass("ui-state-hover")}).focus(function(){j.addClass("ui-state-focus")}).blur(function(){j.removeClass("ui-state-focus")}).click(function(a){return b.close(a),!1}).appendTo(i),k=(b.uiDialogTitlebarCloseText=a("<span></span>")).addClass("ui-icon ui-icon-closethick").text(d.closeText).appendTo(j),l=a("<span></span>").addClass("ui-dialog-title").attr("id",f).html(e).prependTo(i);a.isFunction(d.beforeclose)&&!a.isFunction(d.beforeClose)&&(d.beforeClose=d.beforeclose),i.find("*").add(i).disableSelection(),d.draggable&&a.fn.draggable&&b._makeDraggable(),d.resizable&&a.fn.resizable&&b._makeResizable(),b._createButtons(d.buttons),b._isOpen=!1,a.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;return a.overlay&&a.overlay.destroy(),a.uiDialog.hide(),a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),a.uiDialog.remove(),a.originalTitle&&a.element.attr("title",a.originalTitle),a},widget:function(){return this.uiDialog},close:function(b){var c=this,d,e;if(!1===c._trigger("beforeClose",b))return;return c.overlay&&c.overlay.destroy(),c.uiDialog.unbind("keypress.ui-dialog"),c._isOpen=!1,c.options.hide?c.uiDialog.hide(c.options.hide,function(){c._trigger("close",b)}):(c.uiDialog.hide(),c._trigger("close",b)),a.ui.dialog.overlay.resize(),c.options.modal&&(d=0,a(".ui-dialog").each(function(){this!==c.uiDialog[0]&&(e=a(this).css("z-index"),isNaN(e)||(d=Math.max(d,e)))}),a.ui.dialog.maxZ=d),c},isOpen:function(){return this._isOpen},moveToTop:function(b,c){var d=this,e=d.options,f;return e.modal&&!b||!e.stack&&!e.modal?d._trigger("focus",c):(e.zIndex>a.ui.dialog.maxZ&&(a.ui.dialog.maxZ=e.zIndex),d.overlay&&(a.ui.dialog.maxZ+=1,d.overlay.$el.css("z-index",a.ui.dialog.overlay.maxZ=a.ui.dialog.maxZ)),f={scrollTop:d.element.scrollTop(),scrollLeft:d.element.scrollLeft()},a.ui.dialog.maxZ+=1,d.uiDialog.css("z-index",a.ui.dialog.maxZ),d.element.attr(f),d._trigger("focus",c),d)},open:function(){if(this._isOpen)return;var b=this,c=b.options,d=b.uiDialog;return b.overlay=c.modal?new a.ui.dialog.overlay(b):null,b._size(),b._position(c.position),d.show(c.show),b.moveToTop(!0),c.modal&&d.bind("keydown.ui-dialog",function(b){if(b.keyCode!==a.ui.keyCode.TAB)return;var c=a(":tabbable",this),d=c.filter(":first"),e=c.filter(":last");if(b.target===e[0]&&!b.shiftKey)return d.focus(1),!1;if(b.target===d[0]&&b.shiftKey)return e.focus(1),!1}),a(b.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus(),b._isOpen=!0,b._trigger("open"),b},_createButtons:function(b){var c=this,d=!1,e=a("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),g=a("<div></div>").addClass("ui-dialog-buttonset").appendTo(e);c.uiDialog.find(".ui-dialog-buttonpane").remove(),typeof b=="object"&&b!==null&&a.each(b,function(){return!(d=!0)}),d&&(a.each(b,function(b,d){d=a.isFunction(d)?{click:d,text:b}:d;var e=a('<button type="button"></button>').click(function(){d.click.apply(c.element[0],arguments)}).appendTo(g);a.each(d,function(a,b){if(a==="click")return;a in f?e[a](b):e.attr(a,b)}),a.fn.button&&e.button()}),e.appendTo(c.uiDialog))},_makeDraggable:function(){function f(a){return{position:a.position,offset:a.offset}}var b=this,c=b.options,d=a(document),e;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(d,g){e=c.height==="auto"?"auto":a(this).height(),a(this).height(a(this).height()).addClass("ui-dialog-dragging"),b._trigger("dragStart",d,f(g))},drag:function(a,c){b._trigger("drag",a,f(c))},stop:function(g,h){c.position=[h.position.left-d.scrollLeft(),h.position.top-d.scrollTop()],a(this).removeClass("ui-dialog-dragging").height(e),b._trigger("dragStop",g,f(h)),a.ui.dialog.overlay.resize()}})},_makeResizable:function(c){function h(a){return{originalPosition:a.originalPosition,originalSize:a.originalSize,position:a.position,size:a.size}}c=c===b?this.options.resizable:c;var d=this,e=d.options,f=d.uiDialog.css("position"),g=typeof c=="string"?c:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:g,start:function(b,c){a(this).addClass("ui-dialog-resizing"),d._trigger("resizeStart",b,h(c))},resize:function(a,b){d._trigger("resize",a,h(b))},stop:function(b,c){a(this).removeClass("ui-dialog-resizing"),e.height=a(this).height(),e.width=a(this).width(),d._trigger("resizeStop",b,h(c)),a.ui.dialog.overlay.resize()}}).css("position",f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(b){var c=[],d=[0,0],e;if(b){if(typeof b=="string"||typeof b=="object"&&"0"in b)c=b.split?b.split(" "):[b[0],b[1]],c.length===1&&(c[1]=c[0]),a.each(["left","top"],function(a,b){+c[a]===c[a]&&(d[a]=c[a],c[a]=b)}),b={my:c.join(" "),at:c.join(" "),offset:d.join(" ")};b=a.extend({},a.ui.dialog.prototype.options.position,b)}else b=a.ui.dialog.prototype.options.position;e=this.uiDialog.is(":visible"),e||this.uiDialog.show(),this.uiDialog.css({top:0,left:0}).position(a.extend({of:window},b)),e||this.uiDialog.hide()},_setOptions:function(b){var c=this,f={},g=!1;a.each(b,function(a,b){c._setOption(a,b),a in d&&(g=!0),a in e&&(f[a]=b)}),g&&this._size(),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",f)},_setOption:function(b,d){var e=this,f=e.uiDialog;switch(b){case"beforeclose":b="beforeClose";break;case"buttons":e._createButtons(d);break;case"closeText":e.uiDialogTitlebarCloseText.text(""+d);break;case"dialogClass":f.removeClass(e.options.dialogClass).addClass(c+d);break;case"disabled":d?f.addClass("ui-dialog-disabled"):f.removeClass("ui-dialog-disabled");break;case"draggable":var g=f.is(":data(draggable)");g&&!d&&f.draggable("destroy"),!g&&d&&e._makeDraggable();break;case"position":e._position(d);break;case"resizable":var h=f.is(":data(resizable)");h&&!d&&f.resizable("destroy"),h&&typeof d=="string"&&f.resizable("option","handles",d),!h&&d!==!1&&e._makeResizable(d);break;case"title":a(".ui-dialog-title",e.uiDialogTitlebar).html(""+(d||" "))}a.Widget.prototype._setOption.apply(e,arguments)},_size:function(){var b=this.options,c,d,e=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),b.minWidth>b.width&&(b.width=b.minWidth),c=this.uiDialog.css({height:"auto",width:b.width}).height(),d=Math.max(0,b.minHeight-c);if(b.height==="auto")if(a.support.minHeight)this.element.css({minHeight:d,height:"auto"});else{this.uiDialog.show();var f=this.element.css("height","auto").height();e||this.uiDialog.hide(),this.element.height(Math.max(f,d))}else this.element.height(Math.max(b.height-c,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}}),a.extend(a.ui.dialog,{version:"1.8.20",uuid:0,maxZ:0,getTitleId:function(a){var b=a.attr("id");return b||(this.uuid+=1,b=this.uuid),"ui-dialog-title-"+b},overlay:function(b){this.$el=a.ui.dialog.overlay.create(b)}}),a.extend(a.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:a.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(b){this.instances.length===0&&(setTimeout(function(){a.ui.dialog.overlay.instances.length&&a(document).bind(a.ui.dialog.overlay.events,function(b){if(a(b.target).zIndex()<a.ui.dialog.overlay.maxZ)return!1})},1),a(document).bind("keydown.dialog-overlay",function(c){b.options.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}),a(window).bind("resize.dialog-overlay",a.ui.dialog.overlay.resize));var c=(this.oldInstances.pop()||a("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});return a.fn.bgiframe&&c.bgiframe(),this.instances.push(c),c},destroy:function(b){var c=a.inArray(b,this.instances);c!=-1&&this.oldInstances.push(this.instances.splice(c,1)[0]),this.instances.length===0&&a([document,window]).unbind(".dialog-overlay"),b.remove();var d=0;a.each(this.instances,function(){d=Math.max(d,this.css("z-index"))}),this.maxZ=d},height:function(){var b,c;return a.browser.msie&&a.browser.version<7?(b=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),c=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),b<c?a(window).height()+"px":b+"px"):a(document).height()+"px"},width:function(){var b,c;return a.browser.msie?(b=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),c=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth),b<c?a(window).width()+"px":b+"px"):a(document).width()+"px"},resize:function(){var b=a([]);a.each(a.ui.dialog.overlay.instances,function(){b=b.add(this)}),b.css({width:0,height:0}).css({width:a.ui.dialog.overlay.width(),height:a.ui.dialog.overlay.height()})}}),a.extend(a.ui.dialog.overlay.prototype,{destroy:function(){a.ui.dialog.overlay.destroy(this.$el)}})}(jQuery),function(a,b){a.ui=a.ui||{};var c=/left|center|right/,d=/top|center|bottom/,e="center",f={},g=a.fn.position,h=a.fn.offset;a.fn.position=function(b){if(!b||!b.of)return g.apply(this,arguments);b=a.extend({},b);var h=a(b.of),i=h[0],j=(b.collision||"flip").split(" "),k=b.offset?b.offset.split(" "):[0,0],l,m,n;return i.nodeType===9?(l=h.width(),m=h.height(),n={top:0,left:0}):i.setTimeout?(l=h.width(),m=h.height(),n={top:h.scrollTop(),left:h.scrollLeft()}):i.preventDefault?(b.at="left top",l=m=0,n={top:b.of.pageY,left:b.of.pageX}):(l=h.outerWidth(),m=h.outerHeight(),n=h.offset()),a.each(["my","at"],function(){var a=(b[this]||"").split(" ");a.length===1&&(a=c.test(a[0])?a.concat([e]):d.test(a[0])?[e].concat(a):[e,e]),a[0]=c.test(a[0])?a[0]:e,a[1]=d.test(a[1])?a[1]:e,b[this]=a}),j.length===1&&(j[1]=j[0]),k[0]=parseInt(k[0],10)||0,k.length===1&&(k[1]=k[0]),k[1]=parseInt(k[1],10)||0,b.at[0]==="right"?n.left+=l:b.at[0]===e&&(n.left+=l/2),b.at[1]==="bottom"?n.top+=m:b.at[1]===e&&(n.top+=m/2),n.left+=k[0],n.top+=k[1],this.each(function(){var c=a(this),d=c.outerWidth(),g=c.outerHeight(),h=parseInt(a.curCSS(this,"marginLeft",!0))||0,i=parseInt(a.curCSS(this,"marginTop",!0))||0,o=d+h+(parseInt(a.curCSS(this,"marginRight",!0))||0),p=g+i+(parseInt(a.curCSS(this,"marginBottom",!0))||0),q=a.extend({},n),r;b.my[0]==="right"?q.left-=d:b.my[0]===e&&(q.left-=d/2),b.my[1]==="bottom"?q.top-=g:b.my[1]===e&&(q.top-=g/2),f.fractions||(q.left=Math.round(q.left),q.top=Math.round(q.top)),r={left:q.left-h,top:q.top-i},a.each(["left","top"],function(c,e){a.ui.position[j[c]]&&a.ui.position[j[c]][e](q,{targetWidth:l,targetHeight:m,elemWidth:d,elemHeight:g,collisionPosition:r,collisionWidth:o,collisionHeight:p,offset:k,my:b.my,at:b.at})}),a.fn.bgiframe&&c.bgiframe(),c.offset(a.extend(q,{using:b.using}))})},a.ui.position={fit:{left:function(b,c){var d=a(window),e=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft();b.left=e>0?b.left-e:Math.max(b.left-c.collisionPosition.left,b.left)},top:function(b,c){var d=a(window),e=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop();b.top=e>0?b.top-e:Math.max(b.top-c.collisionPosition.top,b.top)}},flip:{left:function(b,c){if(c.at[0]===e)return;var d=a(window),f=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft(),g=c.my[0]==="left"?-c.elemWidth:c.my[0]==="right"?c.elemWidth:0,h=c.at[0]==="left"?c.targetWidth:-c.targetWidth,i=-2*c.offset[0];b.left+=c.collisionPosition.left<0?g+h+i:f>0?g+h+i:0},top:function(b,c){if(c.at[1]===e)return;var d=a(window),f=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop(),g=c.my[1]==="top"?-c.elemHeight:c.my[1]==="bottom"?c.elemHeight:0,h=c.at[1]==="top"?c.targetHeight:-c.targetHeight,i=-2*c.offset[1];b.top+=c.collisionPosition.top<0?g+h+i:f>0?g+h+i:0}}},a.offset.setOffset||(a.offset.setOffset=function(b,c){/static/.test(a.curCSS(b,"position"))&&(b.style.position="relative");var d=a(b),e=d.offset(),f=parseInt(a.curCSS(b,"top",!0),10)||0,g=parseInt(a.curCSS(b,"left",!0),10)||0,h={top:c.top-e.top+f,left:c.left-e.left+g};"using"in c?c.using.call(b,h):d.css(h)},a.fn.offset=function(b){var c=this[0];return!c||!c.ownerDocument?null:b?this.each(function(){a.offset.setOffset(this,b)}):h.call(this)}),function(){var b=document.getElementsByTagName("body")[0],c=document.createElement("div"),d,e,g,h,i;d=document.createElement(b?"div":"body"),g={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},b&&a.extend(g,{position:"absolute",left:"-1000px",top:"-1000px"});for(var j in g)d.style[j]=g[j];d.appendChild(c),e=b||document.documentElement,e.insertBefore(d,e.firstChild),c.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;",h=a(c).offset(function(a,b){return b}).offset(),d.innerHTML="",e.removeChild(d),i=h.top+h.left+(b?2e3:0),f.fractions=i>21&&i<22}()}(jQuery),function(a,b){a.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()}),this.valueDiv=a("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this.oldValue=this._value(),this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove(),a.Widget.prototype.destroy.apply(this,arguments)},value:function(a){return a===b?this._value():(this._setOption("value",a),this)},_setOption:function(b,c){b==="value"&&(this.options.value=c,this._refreshValue(),this._value()===this.options.max&&this._trigger("complete")),a.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var a=this.options.value;return typeof a!="number"&&(a=0),Math.min(this.options.max,Math.max(this.min,a))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var a=this.value(),b=this._percentage();this.oldValue!==a&&(this.oldValue=a,this._trigger("change")),this.valueDiv.toggle(a>this.min).toggleClass("ui-corner-right",a===this.options.max).width(b.toFixed(0)+"%"),this.element.attr("aria-valuenow",a)}}),a.extend(a.ui.progressbar,{version:"1.8.20"})}(jQuery),function(a,b){var c=5;a.widget("ui.slider",a.ui.mouse,{widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null},_create:function(){var b=this,d=this.options,e=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),f="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",g=d.values&&d.values.length||1,h=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"+(d.disabled?" ui-slider-disabled ui-disabled":"")),this.range=a([]),d.range&&(d.range===!0&&(d.values||(d.values=[this._valueMin(),this._valueMin()]),d.values.length&&d.values.length!==2&&(d.values=[d.values[0],d.values[0]])),this.range=a("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(d.range==="min"||d.range==="max"?" ui-slider-range-"+d.range:"")));for(var i=e.length;i<g;i+=1)h.push(f);this.handles=e.add(a(h.join("")).appendTo(b.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(a){a.preventDefault()}).hover(function(){d.disabled||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}).focus(function(){d.disabled?a(this).blur():(a(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),a(this).addClass("ui-state-focus"))}).blur(function(){a(this).removeClass("ui-state-focus")}),this.handles.each(function(b){a(this).data("index.ui-slider-handle",b)}),this.handles.keydown(function(d){var e=a(this).data("index.ui-slider-handle"),f,g,h,i;if(b.options.disabled)return;switch(d.keyCode){case a.ui.keyCode.HOME:case a.ui.keyCode.END:case a.ui.keyCode.PAGE_UP:case a.ui.keyCode.PAGE_DOWN:case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:d.preventDefault();if(!b._keySliding){b._keySliding=!0,a(this).addClass("ui-state-active"),f=b._start(d,e);if(f===!1)return}}i=b.options.step,b.options.values&&b.options.values.length?g=h=b.values(e):g=h=b.value();switch(d.keyCode){case a.ui.keyCode.HOME:h=b._valueMin();break;case a.ui.keyCode.END:h=b._valueMax();break;case a.ui.keyCode.PAGE_UP:h=b._trimAlignValue(g+(b._valueMax()-b._valueMin())/c);break;case a.ui.keyCode.PAGE_DOWN:h=b._trimAlignValue(g-(b._valueMax()-b._valueMin())/c);break;case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:if(g===b._valueMax())return;h=b._trimAlignValue(g+i);break;case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(g===b._valueMin())return;h=b._trimAlignValue(g-i)}b._slide(d,e,h)}).keyup(function(c){var d=a(this).data("index.ui-slider-handle");b._keySliding&&(b._keySliding=!1,b._stop(c,d),b._change(c,d),a(this).removeClass("ui-state-active"))}),this._refreshValue(),this._animateOff=!1},destroy:function(){return this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"),this._mouseDestroy(),this},_mouseCapture:function(b){var c=this.options,d,e,f,g,h,i,j,k,l;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),d={x:b.pageX,y:b.pageY},e=this._normValueFromMouse(d),f=this._valueMax()-this._valueMin()+1,h=this,this.handles.each(function(b){var c=Math.abs(e-h.values(b));f>c&&(f=c,g=a(this),i=b)}),c.range===!0&&this.values(1)===c.min&&(i+=1,g=a(this.handles[i])),j=this._start(b,i),j===!1?!1:(this._mouseSliding=!0,h._handleIndex=i,g.addClass("ui-state-active").focus(),k=g.offset(),l=!a(b.target).parents().andSelf().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:b.pageX-k.left-g.width()/2,top:b.pageY-k.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(b,i,e),this._animateOff=!0,!0))},_mouseStart:function(a){return!0},_mouseDrag:function(a){var b={x:a.pageX,y:a.pageY},c=this._normValueFromMouse(b);return this._slide(a,this._handleIndex,c),!1},_mouseStop:function(a){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(a,this._handleIndex),this._change(a,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b,c,d,e,f;return this.orientation==="horizontal"?(b=this.elementSize.width,c=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(b=this.elementSize.height,c=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),d=c/b,d>1&&(d=1),d<0&&(d=0),this.orientation==="vertical"&&(d=1-d),e=this._valueMax()-this._valueMin(),f=this._valueMin()+d*e,this._trimAlignValue(f)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};return this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("start",a,c)},_slide:function(a,b,c){var d,e,f;this.options.values&&this.options.values.length?(d=this.values(b?0:1),this.options.values.length===2&&this.options.range===!0&&(b===0&&c>d||b===1&&c<d)&&(c=d),c!==this.values(b)&&(e=this.values(),e[b]=c,f=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e}),d=this.values(b?0:1),f!==!1&&this.values(b,c,!0))):c!==this.value()&&(f=this._trigger("slide",a,{handle:this.handles[b],value:c}),f!==!1&&this.value(c))},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("change",a,c)}},value:function(a){if(arguments.length){this.options.value=this._trimAlignValue(a),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(b,c){var d,e,f;if(arguments.length>1){this.options.values[b]=this._trimAlignValue(c),this._refreshValue(),this._change(null,b);return}if(!arguments.length)return this._values();if(!a.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(b):this.value();d=this.options.values,e=arguments[0];for(f=0;f<d.length;f+=1)d[f]=this._trimAlignValue(e[f]),this._change(null,f);this._refreshValue()},_setOption:function(b,c){var d,e=0;a.isArray(this.options.values)&&(e=this.options.values.length),a.Widget.prototype._setOption.apply(this,arguments);switch(b){case"disabled":c?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.propAttr("disabled",!0),this.element.addClass("ui-disabled")):(this.handles.propAttr("disabled",!1),this.element.removeClass("ui-disabled"));break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(d=0;d<e;d+=1)this._change(null,d);this._animateOff=!1}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a),a},_values:function(a){var b,c,d;if(arguments.length)return b=this.options.values[a],b=this._trimAlignValue(b),b;c=this.options.values.slice();for(d=0;d<c.length;d+=1)c[d]=this._trimAlignValue(c[d]);return c},_trimAlignValue:function(a){if(a<=this._valueMin())return this._valueMin();if(a>=this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=(a-this._valueMin())%b,d=a-c;return Math.abs(c)*2>=b&&(d+=c>0?b:-b),parseFloat(d.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var b=this.options.range,c=this.options,d=this,e=this._animateOff?!1:c.animate,f,g={},h,i,j,k;this.options.values&&this.options.values.length?this.handles.each(function(b,i){f=(d.values(b)-d._valueMin())/(d._valueMax()-d._valueMin())*100,g[d.orientation==="horizontal"?"left":"bottom"]=f+"%",a(this).stop(1,1)[e?"animate":"css"](g,c.animate),d.options.range===!0&&(d.orientation==="horizontal"?(b===0&&d.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},c.animate),b===1&&d.range[e?"animate":"css"]({width:f-h+"%"},{queue:!1,duration:c.animate})):(b===0&&d.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},c.animate),b===1&&d.range[e?"animate":"css"]({height:f-h+"%"},{queue:!1,duration:c.animate}))),h=f}):(i=this.value(),j=this._valueMin(),k=this._valueMax(),f=k!==j?(i-j)/(k-j)*100:0,g[d.orientation==="horizontal"?"left":"bottom"]=f+"%",this.handle.stop(1,1)[e?"animate":"css"](g,c.animate),b==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},c.animate),b==="max"&&this.orientation==="horizontal"&&this.range[e?"animate":"css"]({width:100-f+"%"},{queue:!1,duration:c.animate}),b==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},c.animate),b==="max"&&this.orientation==="vertical"&&this.range[e?"animate":"css"]({height:100-f+"%"},{queue:!1,duration:c.animate}))}}),a.extend(a.ui.slider,{version:"1.8.20"})}(jQuery),function(a,b){function e(){return++c}function f(){return++d}var c=0,d=0;a.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:!1,cookie:null,collapsible:!1,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(!0)},_setOption:function(a,b){if(a=="selected"){if(this.options.collapsible&&b==this.options.selected)return;this.select(b)}else this.options[a]=b,this._tabify()},_tabId:function(a){return a.title&&a.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(a){return a.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+f());return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(a,b){return{tab:a,panel:b,index:this.anchors.index(a)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function m(b,c){b.css("display",""),!a.support.opacity&&c.opacity&&b[0].style.removeAttribute("filter")}var d=this,e=this.options,f=/^#.+/;this.list=this.element.find("ol,ul").eq(0),this.lis=a(" > li:has(a[href])",this.list),this.anchors=this.lis.map(function(){return a("a",this)[0]}),this.panels=a([]),this.anchors.each(function(b,c){var g=a(c).attr("href"),h=g.split("#")[0],i;h&&(h===location.toString().split("#")[0]||(i=a("base")[0])&&h===i.href)&&(g=c.hash,c.href=g);if(f.test(g))d.panels=d.panels.add(d.element.find(d._sanitizeSelector(g)));else if(g&&g!=="#"){a.data(c,"href.tabs",g),a.data(c,"load.tabs",g.replace(/#.*$/,""));var j=d._tabId(c);c.href="#"+j;var k=d.element.find("#"+j);k.length||(k=a(e.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(d.panels[b-1]||d.list),k.data("destroy.tabs",!0)),d.panels=d.panels.add(k)}else e.disabled.push(b)}),c?(this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"),this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.lis.addClass("ui-state-default ui-corner-top"),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom"),e.selected===b?(location.hash&&this.anchors.each(function(a,b){if(b.hash==location.hash)return e.selected=a,!1}),typeof e.selected!="number"&&e.cookie&&(e.selected=parseInt(d._cookie(),10)),typeof e.selected!="number"&&this.lis.filter(".ui-tabs-selected").length&&(e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))),e.selected=e.selected||(this.lis.length?0:-1)):e.selected===null&&(e.selected=-1),e.selected=e.selected>=0&&this.anchors[e.selected]||e.selected<0?e.selected:0,e.disabled=a.unique(e.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(a,b){return d.lis.index(a)}))).sort(),a.inArray(e.selected,e.disabled)!=-1&&e.disabled.splice(a.inArray(e.selected,e.disabled),1),this.panels.addClass("ui-tabs-hide"),this.lis.removeClass("ui-tabs-selected ui-state-active"),e.selected>=0&&this.anchors.length&&(d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash)).removeClass("ui-tabs-hide"),this.lis.eq(e.selected).addClass("ui-tabs-selected ui-state-active"),d.element.queue("tabs",function(){d._trigger("show",null,d._ui(d.anchors[e.selected],d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash))[0]))}),this.load(e.selected)),a(window).bind("unload",function(){d.lis.add(d.anchors).unbind(".tabs"),d.lis=d.anchors=d.panels=null})):e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected")),this.element[e.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible"),e.cookie&&this._cookie(e.selected,e.cookie);for(var g=0,h;h=this.lis[g];g++)a(h)[a.inArray(g,e.disabled)!=-1&&!a(h).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");e.cache===!1&&this.anchors.removeData("cache.tabs"),this.lis.add(this.anchors).unbind(".tabs");if(e.event!=="mouseover"){var i=function(a,b){b.is(":not(.ui-state-disabled)")&&b.addClass("ui-state-"+a)},j=function(a,b){b.removeClass("ui-state-"+a)};this.lis.bind("mouseover.tabs",function(){i("hover",a(this))}),this.lis.bind("mouseout.tabs",function(){j("hover",a(this))}),this.anchors.bind("focus.tabs",function(){i("focus",a(this).closest("li"))}),this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var k,l;e.fx&&(a.isArray(e.fx)?(k=e.fx[0],l=e.fx[1]):k=l=e.fx);var n=l?function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.hide().removeClass("ui-tabs-hide").animate(l,l.duration||"normal",function(){m(c,l),d._trigger("show",null,d._ui(b,c[0]))})}:function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.removeClass("ui-tabs-hide"),d._trigger("show",null,d._ui(b,c[0]))},o=k?function(a,b){b.animate(k,k.duration||"normal",function(){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),m(b,k),d.element.dequeue("tabs")})}:function(a,b,c){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),d.element.dequeue("tabs")};this.anchors.bind(e.event+".tabs",function(){var b=this,c=a(b).closest("li"),f=d.panels.filter(":not(.ui-tabs-hide)"),g=d.element.find(d._sanitizeSelector(b.hash));if(c.hasClass("ui-tabs-selected")&&!e.collapsible||c.hasClass("ui-state-disabled")||c.hasClass("ui-state-processing")||d.panels.filter(":animated").length||d._trigger("select",null,d._ui(this,g[0]))===!1)return this.blur(),!1;e.selected=d.anchors.index(this),d.abort();if(e.collapsible){if(c.hasClass("ui-tabs-selected"))return e.selected=-1,e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){o(b,f)}).dequeue("tabs"),this.blur(),!1;if(!f.length)return e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this)),this.blur(),!1}e.cookie&&d._cookie(e.selected,e.cookie);if(g.length)f.length&&d.element.queue("tabs",function(){o(b,f)}),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this));else throw"jQuery UI Tabs: Mismatching fragment identifier.";a.browser.msie&&this.blur()}),this.anchors.bind("click.tabs",function(){return!1})},_getIndex:function(a){return typeof a=="string"&&(a=this.anchors.index(this.anchors.filter("[href$='"+a+"']"))),a},destroy:function(){var b=this.options;return this.abort(),this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs"),this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.anchors.each(function(){var b=a.data(this,"href.tabs");b&&(this.href=b);var c=a(this).unbind(".tabs");a.each(["href","load","cache"],function(a,b){c.removeData(b+".tabs")})}),this.lis.unbind(".tabs").add(this.panels).each(function(){a.data(this,"destroy.tabs")?a(this).remove():a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}),b.cookie&&this._cookie(null,b.cookie),this},add:function(c,d,e){e===b&&(e=this.anchors.length);var f=this,g=this.options,h=a(g.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,d)),i=c.indexOf("#")?this._tabId(a("a",h)[0]):c.replace("#","");h.addClass("ui-state-default ui-corner-top").data("destroy.tabs",!0);var j=f.element.find("#"+i);return j.length||(j=a(g.panelTemplate).attr("id",i).data("destroy.tabs",!0)),j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"),e>=this.lis.length?(h.appendTo(this.list),j.appendTo(this.list[0].parentNode)):(h.insertBefore(this.lis[e]),j.insertBefore(this.panels[e])),g.disabled=a.map(g.disabled,function(a,b){return a>=e?++a:a}),this._tabify(),this.anchors.length==1&&(g.selected=0,h.addClass("ui-tabs-selected ui-state-active"),j.removeClass("ui-tabs-hide"),this.element.queue("tabs",function(){f._trigger("show",null,f._ui(f.anchors[0],f.panels[0]))}),this.load(0)),this._trigger("add",null,this._ui(this.anchors[e],this.panels[e])),this},remove:function(b){b=this._getIndex(b);var c=this.options,d=this.lis.eq(b).remove(),e=this.panels.eq(b).remove();return d.hasClass("ui-tabs-selected")&&this.anchors.length>1&&this.select(b+(b+1<this.anchors.length?1:-1)),c.disabled=a.map(a.grep(c.disabled,function(a,c){return a!=b}),function(a,c){return a>=b?--a:a}),this._tabify(),this._trigger("remove",null,this._ui(d.find("a")[0],e[0])),this},enable:function(b){b=this._getIndex(b);var c=this.options;if(a.inArray(b,c.disabled)==-1)return;return this.lis.eq(b).removeClass("ui-state-disabled"),c.disabled=a.grep(c.disabled,function(a,c){return a!=b}),this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b])),this},disable:function(a){a=this._getIndex(a);var b=this,c=this.options;return a!=c.selected&&(this.lis.eq(a).addClass("ui-state-disabled"),c.disabled.push(a),c.disabled.sort(),this._trigger("disable",null,this._ui(this.anchors[a],this.panels[a]))),this},select:function(a){a=this._getIndex(a);if(a==-1)if(this.options.collapsible&&this.options.selected!=-1)a=this.options.selected;else return this;return this.anchors.eq(a).trigger(this.options.event+".tabs"),this},load:function(b){b=this._getIndex(b);var c=this,d=this.options,e=this.anchors.eq(b)[0],f=a.data(e,"load.tabs");this.abort();if(!f||this.element.queue("tabs").length!==0&&a.data(e,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(b).addClass("ui-state-processing");if(d.spinner){var g=a("span",e);g.data("label.tabs",g.html()).html(d.spinner)}return this.xhr=a.ajax(a.extend({},d.ajaxOptions,{url:f,success:function(f,g){c.element.find(c._sanitizeSelector(e.hash)).html(f),c._cleanup(),d.cache&&a.data(e,"cache.tabs",!0),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.success(f,g)}catch(h){}},error:function(a,f,g){c._cleanup(),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.error(a,f,b,e)}catch(g){}}})),c.element.dequeue("tabs"),this},abort:function(){return this.element.queue([]),this.panels.stop(!1,!0),this.element.queue("tabs",this.element.queue("tabs").splice(-2,2)),this.xhr&&(this.xhr.abort(),delete this.xhr),this._cleanup(),this},url:function(a,b){return this.anchors.eq(a).removeData("cache.tabs").data("load.tabs",b),this},length:function(){return this.anchors.length}}),a.extend(a.ui.tabs,{version:"1.8.20"}),a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(a,b){var c=this,d=this.options,e=c._rotate||(c._rotate=function(b){clearTimeout(c.rotation),c.rotation=setTimeout(function(){var a=d.selected;c.select(++a<c.anchors.length?a:0)},a),b&&b.stopPropagation()}),f=c._unrotate||(c._unrotate=b?function(a){e()}:function(a){a.clientX&&c.rotate(null)});return a?(this.element.bind("tabsshow",e),this.anchors.bind(d.event+".tabs",f),e()):(clearTimeout(c.rotation),this.element.unbind("tabsshow",e),this.anchors.unbind(d.event+".tabs",f),delete this._rotate,delete this._unrotate),this}})}(jQuery);
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery.unobtrusive-ajax.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery.unobtrusive-ajax.js new file mode 100644 index 0000000..eecd7c9 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery.unobtrusive-ajax.js @@ -0,0 +1,163 @@ +/*! +** Unobtrusive Ajax support library for jQuery +** Copyright (C) Microsoft Corporation. All rights reserved. +*/ + +/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */ +/*global window: false, jQuery: false */ + +(function ($) { + var data_click = "unobtrusiveAjaxClick", + data_validation = "unobtrusiveValidation"; + + function getFunction(code, argNames) { + var fn = window, parts = (code || "").split("."); + while (fn && parts.length) { + fn = fn[parts.shift()]; + } + if (typeof (fn) === "function") { + return fn; + } + argNames.push(code); + return Function.constructor.apply(null, argNames); + } + + function isMethodProxySafe(method) { + return method === "GET" || method === "POST"; + } + + function asyncOnBeforeSend(xhr, method) { + if (!isMethodProxySafe(method)) { + xhr.setRequestHeader("X-HTTP-Method-Override", method); + } + } + + function asyncOnSuccess(element, data, contentType) { + var mode; + + if (contentType.indexOf("application/x-javascript") !== -1) { // jQuery already executes JavaScript for us + return; + } + + mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase(); + $(element.getAttribute("data-ajax-update")).each(function (i, update) { + var top; + + switch (mode) { + case "BEFORE": + top = update.firstChild; + $("<div />").html(data).contents().each(function () { + update.insertBefore(this, top); + }); + break; + case "AFTER": + $("<div />").html(data).contents().each(function () { + update.appendChild(this); + }); + break; + default: + $(update).html(data); + break; + } + }); + } + + function asyncRequest(element, options) { + var confirm, loading, method, duration; + + confirm = element.getAttribute("data-ajax-confirm"); + if (confirm && !window.confirm(confirm)) { + return; + } + + loading = $(element.getAttribute("data-ajax-loading")); + duration = element.getAttribute("data-ajax-loading-duration") || 0; + + $.extend(options, { + type: element.getAttribute("data-ajax-method") || undefined, + url: element.getAttribute("data-ajax-url") || undefined, + beforeSend: function (xhr) { + var result; + asyncOnBeforeSend(xhr, method); + result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments); + if (result !== false) { + loading.show(duration); + } + return result; + }, + complete: function () { + loading.hide(duration); + getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(this, arguments); + }, + success: function (data, status, xhr) { + asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html"); + getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments); + }, + error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"]) + }); + + options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" }); + + method = options.type.toUpperCase(); + if (!isMethodProxySafe(method)) { + options.type = "POST"; + options.data.push({ name: "X-HTTP-Method-Override", value: method }); + } + + $.ajax(options); + } + + function validate(form) { + var validationInfo = $(form).data(data_validation); + return !validationInfo || !validationInfo.validate || validationInfo.validate(); + } + + $("a[data-ajax=true]").live("click", function (evt) { + evt.preventDefault(); + asyncRequest(this, { + url: this.href, + type: "GET", + data: [] + }); + }); + + $("form[data-ajax=true] input[type=image]").live("click", function (evt) { + var name = evt.target.name, + $target = $(evt.target), + form = $target.parents("form")[0], + offset = $target.offset(); + + $(form).data(data_click, [ + { name: name + ".x", value: Math.round(evt.pageX - offset.left) }, + { name: name + ".y", value: Math.round(evt.pageY - offset.top) } + ]); + + setTimeout(function () { + $(form).removeData(data_click); + }, 0); + }); + + $("form[data-ajax=true] :submit").live("click", function (evt) { + var name = evt.target.name, + form = $(evt.target).parents("form")[0]; + + $(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []); + + setTimeout(function () { + $(form).removeData(data_click); + }, 0); + }); + + $("form[data-ajax=true]").live("submit", function (evt) { + var clickInfo = $(this).data(data_click) || []; + evt.preventDefault(); + if (!validate(this)) { + return; + } + asyncRequest(this, { + url: this.action, + type: this.method || "GET", + data: clickInfo.concat($(this).serializeArray()) + }); + }); +}(jQuery));
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery.unobtrusive-ajax.min.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery.unobtrusive-ajax.min.js new file mode 100644 index 0000000..3542991 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery.unobtrusive-ajax.min.js @@ -0,0 +1,5 @@ +/* +** Unobtrusive Ajax support library for jQuery +** Copyright (C) Microsoft Corporation. All rights reserved. +*/ +(function(a){var b="unobtrusiveAjaxClick",g="unobtrusiveValidation";function c(d,b){var a=window,c=(d||"").split(".");while(a&&c.length)a=a[c.shift()];if(typeof a==="function")return a;b.push(d);return Function.constructor.apply(null,b)}function d(a){return a==="GET"||a==="POST"}function f(b,a){!d(a)&&b.setRequestHeader("X-HTTP-Method-Override",a)}function h(c,b,e){var d;if(e.indexOf("application/x-javascript")!==-1)return;d=(c.getAttribute("data-ajax-mode")||"").toUpperCase();a(c.getAttribute("data-ajax-update")).each(function(f,c){var e;switch(d){case"BEFORE":e=c.firstChild;a("<div />").html(b).contents().each(function(){c.insertBefore(this,e)});break;case"AFTER":a("<div />").html(b).contents().each(function(){c.appendChild(this)});break;default:a(c).html(b)}})}function e(b,e){var j,k,g,i;j=b.getAttribute("data-ajax-confirm");if(j&&!window.confirm(j))return;k=a(b.getAttribute("data-ajax-loading"));i=b.getAttribute("data-ajax-loading-duration")||0;a.extend(e,{type:b.getAttribute("data-ajax-method")||undefined,url:b.getAttribute("data-ajax-url")||undefined,beforeSend:function(d){var a;f(d,g);a=c(b.getAttribute("data-ajax-begin"),["xhr"]).apply(this,arguments);a!==false&&k.show(i);return a},complete:function(){k.hide(i);c(b.getAttribute("data-ajax-complete"),["xhr","status"]).apply(this,arguments)},success:function(a,e,d){h(b,a,d.getResponseHeader("Content-Type")||"text/html");c(b.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(this,arguments)},error:c(b.getAttribute("data-ajax-failure"),["xhr","status","error"])});e.data.push({name:"X-Requested-With",value:"XMLHttpRequest"});g=e.type.toUpperCase();if(!d(g)){e.type="POST";e.data.push({name:"X-HTTP-Method-Override",value:g})}a.ajax(e)}function i(c){var b=a(c).data(g);return!b||!b.validate||b.validate()}a("a[data-ajax=true]").live("click",function(a){a.preventDefault();e(this,{url:this.href,type:"GET",data:[]})});a("form[data-ajax=true] input[type=image]").live("click",function(c){var g=c.target.name,d=a(c.target),f=d.parents("form")[0],e=d.offset();a(f).data(b,[{name:g+".x",value:Math.round(c.pageX-e.left)},{name:g+".y",value:Math.round(c.pageY-e.top)}]);setTimeout(function(){a(f).removeData(b)},0)});a("form[data-ajax=true] :submit").live("click",function(c){var e=c.target.name,d=a(c.target).parents("form")[0];a(d).data(b,e?[{name:e,value:c.target.value}]:[]);setTimeout(function(){a(d).removeData(b)},0)});a("form[data-ajax=true]").live("submit",function(d){var c=a(this).data(b)||[];d.preventDefault();if(!i(this))return;e(this,{url:this.action,type:this.method||"GET",data:c.concat(a(this).serializeArray())})})})(jQuery);
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate-vsdoc.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate-vsdoc.js new file mode 100644 index 0000000..22a5460 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate-vsdoc.js @@ -0,0 +1,1291 @@ +/* +* This file has been commented to support Visual Studio Intellisense. +* You should not use this file at runtime inside the browser--it is only +* intended to be used only for design-time IntelliSense. Please use the +* standard jQuery library for all production use. +* +* Comment version: 1.8 +*/ + +/* +* Note: While Microsoft is not the author of this file, Microsoft is +* offering you a license subject to the terms of the Microsoft Software +* License Terms for Microsoft ASP.NET Model View Controller 3. +* Microsoft reserves all other rights. The notices below are provided +* for informational purposes only and are not the license terms under +* which Microsoft distributed this file. +* +* jQuery validation plugin 1.8.0 +* +* http://bassistance.de/jquery-plugins/jquery-plugin-validation/ +* http://docs.jquery.com/Plugins/Validation +* +* Copyright (c) 2006 - 2011 Jörn Zaefferer +* +*/ + +(function($) { + +$.extend($.fn, { + // http://docs.jquery.com/Plugins/Validation/validate + validate: function( options ) { + /// <summary> + /// Validates the selected form. This method sets up event handlers for submit, focus, + /// keyup, blur and click to trigger validation of the entire form or individual + /// elements. Each one can be disabled, see the onxxx options (onsubmit, onfocusout, + /// onkeyup, onclick). focusInvalid focuses elements when submitting a invalid form. + /// </summary> + /// <param name="options" type="Object"> + /// A set of key/value pairs that configure the validate. All options are optional. + /// </param> + + // if nothing is selected, return nothing; can't chain anyway + if (!this.length) { + options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" ); + return; + } + + // check if a validator for this form was already created + var validator = $.data(this[0], 'validator'); + if ( validator ) { + return validator; + } + + validator = new $.validator( options, this[0] ); + $.data(this[0], 'validator', validator); + + if ( validator.settings.onsubmit ) { + + // allow suppresing validation by adding a cancel class to the submit button + this.find("input, button").filter(".cancel").click(function() { + validator.cancelSubmit = true; + }); + + // when a submitHandler is used, capture the submitting button + if (validator.settings.submitHandler) { + this.find("input, button").filter(":submit").click(function() { + validator.submitButton = this; + }); + } + + // validate the form on submit + this.submit( function( event ) { + if ( validator.settings.debug ) + // prevent form submit to be able to see console output + event.preventDefault(); + + function handle() { + if ( validator.settings.submitHandler ) { + if (validator.submitButton) { + // insert a hidden input as a replacement for the missing submit button + var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm); + } + validator.settings.submitHandler.call( validator, validator.currentForm ); + if (validator.submitButton) { + // and clean up afterwards; thanks to no-block-scope, hidden can be referenced + hidden.remove(); + } + return false; + } + return true; + } + + // prevent submit for invalid forms or custom submit handlers + if ( validator.cancelSubmit ) { + validator.cancelSubmit = false; + return handle(); + } + if ( validator.form() ) { + if ( validator.pendingRequest ) { + validator.formSubmitted = true; + return false; + } + return handle(); + } else { + validator.focusInvalid(); + return false; + } + }); + } + + return validator; + }, + // http://docs.jquery.com/Plugins/Validation/valid + valid: function() { + /// <summary> + /// Checks if the selected form is valid or if all selected elements are valid. + /// validate() needs to be called on the form before checking it using this method. + /// </summary> + /// <returns type="Boolean" /> + + if ( $(this[0]).is('form')) { + return this.validate().form(); + } else { + var valid = true; + var validator = $(this[0].form).validate(); + this.each(function() { + valid &= validator.element(this); + }); + return valid; + } + }, + // attributes: space seperated list of attributes to retrieve and remove + removeAttrs: function(attributes) { + /// <summary> + /// Remove the specified attributes from the first matched element and return them. + /// </summary> + /// <param name="attributes" type="String"> + /// A space-seperated list of attribute names to remove. + /// </param> + + var result = {}, + $element = this; + $.each(attributes.split(/\s/), function(index, value) { + result[value] = $element.attr(value); + $element.removeAttr(value); + }); + return result; + }, + // http://docs.jquery.com/Plugins/Validation/rules + rules: function(command, argument) { + /// <summary> + /// Return the validations rules for the first selected element. + /// </summary> + /// <param name="command" type="String"> + /// Can be either "add" or "remove". + /// </param> + /// <param name="argument" type=""> + /// A list of rules to add or remove. + /// </param> + + var element = this[0]; + + if (command) { + var settings = $.data(element.form, 'validator').settings; + var staticRules = settings.rules; + var existingRules = $.validator.staticRules(element); + switch(command) { + case "add": + $.extend(existingRules, $.validator.normalizeRule(argument)); + staticRules[element.name] = existingRules; + if (argument.messages) + settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages ); + break; + case "remove": + if (!argument) { + delete staticRules[element.name]; + return existingRules; + } + var filtered = {}; + $.each(argument.split(/\s/), function(index, method) { + filtered[method] = existingRules[method]; + delete existingRules[method]; + }); + return filtered; + } + } + + var data = $.validator.normalizeRules( + $.extend( + {}, + $.validator.metadataRules(element), + $.validator.classRules(element), + $.validator.attributeRules(element), + $.validator.staticRules(element) + ), element); + + // make sure required is at front + if (data.required) { + var param = data.required; + delete data.required; + data = $.extend({required: param}, data); + } + + return data; + } +}); + +// Custom selectors +$.extend($.expr[":"], { + // http://docs.jquery.com/Plugins/Validation/blank + blank: function(a) {return !$.trim("" + a.value);}, + // http://docs.jquery.com/Plugins/Validation/filled + filled: function(a) {return !!$.trim("" + a.value);}, + // http://docs.jquery.com/Plugins/Validation/unchecked + unchecked: function(a) {return !a.checked;} +}); + +// constructor for validator +$.validator = function( options, form ) { + this.settings = $.extend( true, {}, $.validator.defaults, options ); + this.currentForm = form; + this.init(); +}; + +$.validator.format = function(source, params) { + /// <summary> + /// Replaces {n} placeholders with arguments. + /// One or more arguments can be passed, in addition to the string template itself, to insert + /// into the string. + /// </summary> + /// <param name="source" type="String"> + /// The string to format. + /// </param> + /// <param name="params" type="String"> + /// The first argument to insert, or an array of Strings to insert + /// </param> + /// <returns type="String" /> + + if ( arguments.length == 1 ) + return function() { + var args = $.makeArray(arguments); + args.unshift(source); + return $.validator.format.apply( this, args ); + }; + if ( arguments.length > 2 && params.constructor != Array ) { + params = $.makeArray(arguments).slice(1); + } + if ( params.constructor != Array ) { + params = [ params ]; + } + $.each(params, function(i, n) { + source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n); + }); + return source; +}; + +$.extend($.validator, { + + defaults: { + messages: {}, + groups: {}, + rules: {}, + errorClass: "error", + validClass: "valid", + errorElement: "label", + focusInvalid: true, + errorContainer: $( [] ), + errorLabelContainer: $( [] ), + onsubmit: true, + ignore: [], + ignoreTitle: false, + onfocusin: function(element) { + this.lastActive = element; + + // hide error label and remove error class on focus if enabled + if ( this.settings.focusCleanup && !this.blockFocusCleanup ) { + this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass ); + this.addWrapper(this.errorsFor(element)).hide(); + } + }, + onfocusout: function(element) { + if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) { + this.element(element); + } + }, + onkeyup: function(element) { + if ( element.name in this.submitted || element == this.lastElement ) { + this.element(element); + } + }, + onclick: function(element) { + // click on selects, radiobuttons and checkboxes + if ( element.name in this.submitted ) + this.element(element); + // or option elements, check parent select in that case + else if (element.parentNode.name in this.submitted) + this.element(element.parentNode); + }, + highlight: function( element, errorClass, validClass ) { + $(element).addClass(errorClass).removeClass(validClass); + }, + unhighlight: function( element, errorClass, validClass ) { + $(element).removeClass(errorClass).addClass(validClass); + } + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults + setDefaults: function(settings) { + /// <summary> + /// Modify default settings for validation. + /// Accepts everything that Plugins/Validation/validate accepts. + /// </summary> + /// <param name="settings" type="Options"> + /// Options to set as default. + /// </param> + + $.extend( $.validator.defaults, settings ); + }, + + messages: { + required: "This field is required.", + remote: "Please fix this field.", + email: "Please enter a valid email address.", + url: "Please enter a valid URL.", + date: "Please enter a valid date.", + dateISO: "Please enter a valid date (ISO).", + number: "Please enter a valid number.", + digits: "Please enter only digits.", + creditcard: "Please enter a valid credit card number.", + equalTo: "Please enter the same value again.", + accept: "Please enter a value with a valid extension.", + maxlength: $.validator.format("Please enter no more than {0} characters."), + minlength: $.validator.format("Please enter at least {0} characters."), + rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."), + range: $.validator.format("Please enter a value between {0} and {1}."), + max: $.validator.format("Please enter a value less than or equal to {0}."), + min: $.validator.format("Please enter a value greater than or equal to {0}.") + }, + + autoCreateRanges: false, + + prototype: { + + init: function() { + this.labelContainer = $(this.settings.errorLabelContainer); + this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm); + this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer ); + this.submitted = {}; + this.valueCache = {}; + this.pendingRequest = 0; + this.pending = {}; + this.invalid = {}; + this.reset(); + + var groups = (this.groups = {}); + $.each(this.settings.groups, function(key, value) { + $.each(value.split(/\s/), function(index, name) { + groups[name] = key; + }); + }); + var rules = this.settings.rules; + $.each(rules, function(key, value) { + rules[key] = $.validator.normalizeRule(value); + }); + + function delegate(event) { + var validator = $.data(this[0].form, "validator"), + eventType = "on" + event.type.replace(/^validate/, ""); + validator.settings[eventType] && validator.settings[eventType].call(validator, this[0] ); + } + $(this.currentForm) + .validateDelegate(":text, :password, :file, select, textarea", "focusin focusout keyup", delegate) + .validateDelegate(":radio, :checkbox, select, option", "click", delegate); + + if (this.settings.invalidHandler) + $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler); + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/form + form: function() { + /// <summary> + /// Validates the form, returns true if it is valid, false otherwise. + /// This behaves as a normal submit event, but returns the result. + /// </summary> + /// <returns type="Boolean" /> + + this.checkForm(); + $.extend(this.submitted, this.errorMap); + this.invalid = $.extend({}, this.errorMap); + if (!this.valid()) + $(this.currentForm).triggerHandler("invalid-form", [this]); + this.showErrors(); + return this.valid(); + }, + + checkForm: function() { + this.prepareForm(); + for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) { + this.check( elements[i] ); + } + return this.valid(); + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/element + element: function( element ) { + /// <summary> + /// Validates a single element, returns true if it is valid, false otherwise. + /// This behaves as validation on blur or keyup, but returns the result. + /// </summary> + /// <param name="element" type="Selector"> + /// An element to validate, must be inside the validated form. + /// </param> + /// <returns type="Boolean" /> + + element = this.clean( element ); + this.lastElement = element; + this.prepareElement( element ); + this.currentElements = $(element); + var result = this.check( element ); + if ( result ) { + delete this.invalid[element.name]; + } else { + this.invalid[element.name] = true; + } + if ( !this.numberOfInvalids() ) { + // Hide error containers on last error + this.toHide = this.toHide.add( this.containers ); + } + this.showErrors(); + return result; + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/showErrors + showErrors: function(errors) { + /// <summary> + /// Show the specified messages. + /// Keys have to refer to the names of elements, values are displayed for those elements, using the configured error placement. + /// </summary> + /// <param name="errors" type="Object"> + /// One or more key/value pairs of input names and messages. + /// </param> + + if(errors) { + // add items to error list and map + $.extend( this.errorMap, errors ); + this.errorList = []; + for ( var name in errors ) { + this.errorList.push({ + message: errors[name], + element: this.findByName(name)[0] + }); + } + // remove items from success list + this.successList = $.grep( this.successList, function(element) { + return !(element.name in errors); + }); + } + this.settings.showErrors + ? this.settings.showErrors.call( this, this.errorMap, this.errorList ) + : this.defaultShowErrors(); + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/resetForm + resetForm: function() { + /// <summary> + /// Resets the controlled form. + /// Resets input fields to their original value (requires form plugin), removes classes + /// indicating invalid elements and hides error messages. + /// </summary> + + if ( $.fn.resetForm ) + $( this.currentForm ).resetForm(); + this.submitted = {}; + this.prepareForm(); + this.hideErrors(); + this.elements().removeClass( this.settings.errorClass ); + }, + + numberOfInvalids: function() { + /// <summary> + /// Returns the number of invalid fields. + /// This depends on the internal validator state. It covers all fields only after + /// validating the complete form (on submit or via $("form").valid()). After validating + /// a single element, only that element is counted. Most useful in combination with the + /// invalidHandler-option. + /// </summary> + /// <returns type="Number" /> + + return this.objectLength(this.invalid); + }, + + objectLength: function( obj ) { + var count = 0; + for ( var i in obj ) + count++; + return count; + }, + + hideErrors: function() { + this.addWrapper( this.toHide ).hide(); + }, + + valid: function() { + return this.size() == 0; + }, + + size: function() { + return this.errorList.length; + }, + + focusInvalid: function() { + if( this.settings.focusInvalid ) { + try { + $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []) + .filter(":visible") + .focus() + // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find + .trigger("focusin"); + } catch(e) { + // ignore IE throwing errors when focusing hidden elements + } + } + }, + + findLastActive: function() { + var lastActive = this.lastActive; + return lastActive && $.grep(this.errorList, function(n) { + return n.element.name == lastActive.name; + }).length == 1 && lastActive; + }, + + elements: function() { + var validator = this, + rulesCache = {}; + + // select all valid inputs inside the form (no submit or reset buttons) + // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved + return $([]).add(this.currentForm.elements) + .filter(":input") + .not(":submit, :reset, :image, [disabled]") + .not( this.settings.ignore ) + .filter(function() { + !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this); + + // select only the first element for each name, and only those with rules specified + if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) + return false; + + rulesCache[this.name] = true; + return true; + }); + }, + + clean: function( selector ) { + return $( selector )[0]; + }, + + errors: function() { + return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext ); + }, + + reset: function() { + this.successList = []; + this.errorList = []; + this.errorMap = {}; + this.toShow = $([]); + this.toHide = $([]); + this.currentElements = $([]); + }, + + prepareForm: function() { + this.reset(); + this.toHide = this.errors().add( this.containers ); + }, + + prepareElement: function( element ) { + this.reset(); + this.toHide = this.errorsFor(element); + }, + + check: function( element ) { + element = this.clean( element ); + + // if radio/checkbox, validate first element in group instead + if (this.checkable(element)) { + element = this.findByName(element.name).not(this.settings.ignore)[0]; + } + + var rules = $(element).rules(); + var dependencyMismatch = false; + for (var method in rules) { + var rule = { method: method, parameters: rules[method] }; + try { + var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters ); + + // if a method indicates that the field is optional and therefore valid, + // don't mark it as valid when there are no other rules + if ( result == "dependency-mismatch" ) { + dependencyMismatch = true; + continue; + } + dependencyMismatch = false; + + if ( result == "pending" ) { + this.toHide = this.toHide.not( this.errorsFor(element) ); + return; + } + + if( !result ) { + this.formatAndAdd( element, rule ); + return false; + } + } catch(e) { + this.settings.debug && window.console && console.log("exception occured when checking element " + element.id + + ", check the '" + rule.method + "' method", e); + throw e; + } + } + if (dependencyMismatch) + return; + if ( this.objectLength(rules) ) + this.successList.push(element); + return true; + }, + + // return the custom message for the given element and validation method + // specified in the element's "messages" metadata + customMetaMessage: function(element, method) { + if (!$.metadata) + return; + + var meta = this.settings.meta + ? $(element).metadata()[this.settings.meta] + : $(element).metadata(); + + return meta && meta.messages && meta.messages[method]; + }, + + // return the custom message for the given element name and validation method + customMessage: function( name, method ) { + var m = this.settings.messages[name]; + return m && (m.constructor == String + ? m + : m[method]); + }, + + // return the first defined argument, allowing empty strings + findDefined: function() { + for(var i = 0; i < arguments.length; i++) { + if (arguments[i] !== undefined) + return arguments[i]; + } + return undefined; + }, + + defaultMessage: function( element, method) { + return this.findDefined( + this.customMessage( element.name, method ), + this.customMetaMessage( element, method ), + // title is never undefined, so handle empty string as undefined + !this.settings.ignoreTitle && element.title || undefined, + $.validator.messages[method], + "<strong>Warning: No message defined for " + element.name + "</strong>" + ); + }, + + formatAndAdd: function( element, rule ) { + var message = this.defaultMessage( element, rule.method ), + theregex = /\$?\{(\d+)\}/g; + if ( typeof message == "function" ) { + message = message.call(this, rule.parameters, element); + } else if (theregex.test(message)) { + message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters); + } + this.errorList.push({ + message: message, + element: element + }); + + this.errorMap[element.name] = message; + this.submitted[element.name] = message; + }, + + addWrapper: function(toToggle) { + if ( this.settings.wrapper ) + toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) ); + return toToggle; + }, + + defaultShowErrors: function() { + for ( var i = 0; this.errorList[i]; i++ ) { + var error = this.errorList[i]; + this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass ); + this.showLabel( error.element, error.message ); + } + if( this.errorList.length ) { + this.toShow = this.toShow.add( this.containers ); + } + if (this.settings.success) { + for ( var i = 0; this.successList[i]; i++ ) { + this.showLabel( this.successList[i] ); + } + } + if (this.settings.unhighlight) { + for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) { + this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass ); + } + } + this.toHide = this.toHide.not( this.toShow ); + this.hideErrors(); + this.addWrapper( this.toShow ).show(); + }, + + validElements: function() { + return this.currentElements.not(this.invalidElements()); + }, + + invalidElements: function() { + return $(this.errorList).map(function() { + return this.element; + }); + }, + + showLabel: function(element, message) { + var label = this.errorsFor( element ); + if ( label.length ) { + // refresh error/success class + label.removeClass().addClass( this.settings.errorClass ); + + // check if we have a generated label, replace the message then + label.attr("generated") && label.html(message); + } else { + // create label + label = $("<" + this.settings.errorElement + "/>") + .attr({"for": this.idOrName(element), generated: true}) + .addClass(this.settings.errorClass) + .html(message || ""); + if ( this.settings.wrapper ) { + // make sure the element is visible, even in IE + // actually showing the wrapped element is handled elsewhere + label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent(); + } + if ( !this.labelContainer.append(label).length ) + this.settings.errorPlacement + ? this.settings.errorPlacement(label, $(element) ) + : label.insertAfter(element); + } + if ( !message && this.settings.success ) { + label.text(""); + typeof this.settings.success == "string" + ? label.addClass( this.settings.success ) + : this.settings.success( label ); + } + this.toShow = this.toShow.add(label); + }, + + errorsFor: function(element) { + var name = this.idOrName(element); + return this.errors().filter(function() { + return $(this).attr('for') == name; + }); + }, + + idOrName: function(element) { + return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name); + }, + + checkable: function( element ) { + return /radio|checkbox/i.test(element.type); + }, + + findByName: function( name ) { + // select by name and filter by form for performance over form.find("[name=...]") + var form = this.currentForm; + return $(document.getElementsByName(name)).map(function(index, element) { + return element.form == form && element.name == name && element || null; + }); + }, + + getLength: function(value, element) { + switch( element.nodeName.toLowerCase() ) { + case 'select': + return $("option:selected", element).length; + case 'input': + if( this.checkable( element) ) + return this.findByName(element.name).filter(':checked').length; + } + return value.length; + }, + + depend: function(param, element) { + return this.dependTypes[typeof param] + ? this.dependTypes[typeof param](param, element) + : true; + }, + + dependTypes: { + "boolean": function(param, element) { + return param; + }, + "string": function(param, element) { + return !!$(param, element.form).length; + }, + "function": function(param, element) { + return param(element); + } + }, + + optional: function(element) { + return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch"; + }, + + startRequest: function(element) { + if (!this.pending[element.name]) { + this.pendingRequest++; + this.pending[element.name] = true; + } + }, + + stopRequest: function(element, valid) { + this.pendingRequest--; + // sometimes synchronization fails, make sure pendingRequest is never < 0 + if (this.pendingRequest < 0) + this.pendingRequest = 0; + delete this.pending[element.name]; + if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) { + $(this.currentForm).submit(); + this.formSubmitted = false; + } else if (!valid && this.pendingRequest == 0 && this.formSubmitted) { + $(this.currentForm).triggerHandler("invalid-form", [this]); + this.formSubmitted = false; + } + }, + + previousValue: function(element) { + return $.data(element, "previousValue") || $.data(element, "previousValue", { + old: null, + valid: true, + message: this.defaultMessage( element, "remote" ) + }); + } + + }, + + classRuleSettings: { + required: {required: true}, + email: {email: true}, + url: {url: true}, + date: {date: true}, + dateISO: {dateISO: true}, + dateDE: {dateDE: true}, + number: {number: true}, + numberDE: {numberDE: true}, + digits: {digits: true}, + creditcard: {creditcard: true} + }, + + addClassRules: function(className, rules) { + /// <summary> + /// Add a compound class method - useful to refactor common combinations of rules into a single + /// class. + /// </summary> + /// <param name="name" type="String"> + /// The name of the class rule to add + /// </param> + /// <param name="rules" type="Options"> + /// The compound rules + /// </param> + + className.constructor == String ? + this.classRuleSettings[className] = rules : + $.extend(this.classRuleSettings, className); + }, + + classRules: function(element) { + var rules = {}; + var classes = $(element).attr('class'); + classes && $.each(classes.split(' '), function() { + if (this in $.validator.classRuleSettings) { + $.extend(rules, $.validator.classRuleSettings[this]); + } + }); + return rules; + }, + + attributeRules: function(element) { + var rules = {}; + var $element = $(element); + + for (var method in $.validator.methods) { + var value = $element.attr(method); + if (value) { + rules[method] = value; + } + } + + // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs + if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) { + delete rules.maxlength; + } + + return rules; + }, + + metadataRules: function(element) { + if (!$.metadata) return {}; + + var meta = $.data(element.form, 'validator').settings.meta; + return meta ? + $(element).metadata()[meta] : + $(element).metadata(); + }, + + staticRules: function(element) { + var rules = {}; + var validator = $.data(element.form, 'validator'); + if (validator.settings.rules) { + rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {}; + } + return rules; + }, + + normalizeRules: function(rules, element) { + // handle dependency check + $.each(rules, function(prop, val) { + // ignore rule when param is explicitly false, eg. required:false + if (val === false) { + delete rules[prop]; + return; + } + if (val.param || val.depends) { + var keepRule = true; + switch (typeof val.depends) { + case "string": + keepRule = !!$(val.depends, element.form).length; + break; + case "function": + keepRule = val.depends.call(element, element); + break; + } + if (keepRule) { + rules[prop] = val.param !== undefined ? val.param : true; + } else { + delete rules[prop]; + } + } + }); + + // evaluate parameters + $.each(rules, function(rule, parameter) { + rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter; + }); + + // clean number parameters + $.each(['minlength', 'maxlength', 'min', 'max'], function() { + if (rules[this]) { + rules[this] = Number(rules[this]); + } + }); + $.each(['rangelength', 'range'], function() { + if (rules[this]) { + rules[this] = [Number(rules[this][0]), Number(rules[this][1])]; + } + }); + + if ($.validator.autoCreateRanges) { + // auto-create ranges + if (rules.min && rules.max) { + rules.range = [rules.min, rules.max]; + delete rules.min; + delete rules.max; + } + if (rules.minlength && rules.maxlength) { + rules.rangelength = [rules.minlength, rules.maxlength]; + delete rules.minlength; + delete rules.maxlength; + } + } + + // To support custom messages in metadata ignore rule methods titled "messages" + if (rules.messages) { + delete rules.messages; + } + + return rules; + }, + + // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} + normalizeRule: function(data) { + if( typeof data == "string" ) { + var transformed = {}; + $.each(data.split(/\s/), function() { + transformed[this] = true; + }); + data = transformed; + } + return data; + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/addMethod + addMethod: function(name, method, message) { + /// <summary> + /// Add a custom validation method. It must consist of a name (must be a legal javascript + /// identifier), a javascript based function and a default string message. + /// </summary> + /// <param name="name" type="String"> + /// The name of the method, used to identify and referencing it, must be a valid javascript + /// identifier + /// </param> + /// <param name="method" type="Function"> + /// The actual method implementation, returning true if an element is valid + /// </param> + /// <param name="message" type="String" optional="true"> + /// (Optional) The default message to display for this method. Can be a function created by + /// jQuery.validator.format(value). When undefined, an already existing message is used + /// (handy for localization), otherwise the field-specific messages have to be defined. + /// </param> + + $.validator.methods[name] = method; + $.validator.messages[name] = message != undefined ? message : $.validator.messages[name]; + if (method.length < 3) { + $.validator.addClassRules(name, $.validator.normalizeRule(name)); + } + }, + + methods: { + + // http://docs.jquery.com/Plugins/Validation/Methods/required + required: function(value, element, param) { + // check if dependency is met + if ( !this.depend(param, element) ) + return "dependency-mismatch"; + switch( element.nodeName.toLowerCase() ) { + case 'select': + // could be an array for select-multiple or a string, both are fine this way + var val = $(element).val(); + return val && val.length > 0; + case 'input': + if ( this.checkable(element) ) + return this.getLength(value, element) > 0; + default: + return $.trim(value).length > 0; + } + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/remote + remote: function(value, element, param) { + if ( this.optional(element) ) + return "dependency-mismatch"; + + var previous = this.previousValue(element); + if (!this.settings.messages[element.name] ) + this.settings.messages[element.name] = {}; + previous.originalMessage = this.settings.messages[element.name].remote; + this.settings.messages[element.name].remote = previous.message; + + param = typeof param == "string" && {url:param} || param; + + if ( this.pending[element.name] ) { + return "pending"; + } + if ( previous.old === value ) { + return previous.valid; + } + + previous.old = value; + var validator = this; + this.startRequest(element); + var data = {}; + data[element.name] = value; + $.ajax($.extend(true, { + url: param, + mode: "abort", + port: "validate" + element.name, + dataType: "json", + data: data, + success: function(response) { + validator.settings.messages[element.name].remote = previous.originalMessage; + var valid = response === true; + if ( valid ) { + var submitted = validator.formSubmitted; + validator.prepareElement(element); + validator.formSubmitted = submitted; + validator.successList.push(element); + validator.showErrors(); + } else { + var errors = {}; + var message = response || validator.defaultMessage(element, "remote"); + errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message; + validator.showErrors(errors); + } + previous.valid = valid; + validator.stopRequest(element, valid); + } + }, param)); + return "pending"; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/minlength + minlength: function(value, element, param) { + return this.optional(element) || this.getLength($.trim(value), element) >= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/maxlength + maxlength: function(value, element, param) { + return this.optional(element) || this.getLength($.trim(value), element) <= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/rangelength + rangelength: function(value, element, param) { + var length = this.getLength($.trim(value), element); + return this.optional(element) || ( length >= param[0] && length <= param[1] ); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/min + min: function( value, element, param ) { + return this.optional(element) || value >= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/max + max: function( value, element, param ) { + return this.optional(element) || value <= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/range + range: function( value, element, param ) { + return this.optional(element) || ( value >= param[0] && value <= param[1] ); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/email + email: function(value, element) { + // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ + return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/url + url: function(value, element) { + // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ + return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/date + date: function(value, element) { + return this.optional(element) || !/Invalid|NaN/.test(new Date(value)); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/dateISO + dateISO: function(value, element) { + return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/number + number: function(value, element) { + return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/digits + digits: function(value, element) { + return this.optional(element) || /^\d+$/.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/creditcard + // based on http://en.wikipedia.org/wiki/Luhn + creditcard: function(value, element) { + if ( this.optional(element) ) + return "dependency-mismatch"; + // accept only digits and dashes + if (/[^0-9-]+/.test(value)) + return false; + var nCheck = 0, + nDigit = 0, + bEven = false; + + value = value.replace(/\D/g, ""); + + for (var n = value.length - 1; n >= 0; n--) { + var cDigit = value.charAt(n); + var nDigit = parseInt(cDigit, 10); + if (bEven) { + if ((nDigit *= 2) > 9) + nDigit -= 9; + } + nCheck += nDigit; + bEven = !bEven; + } + + return (nCheck % 10) == 0; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/accept + accept: function(value, element, param) { + param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif"; + return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/equalTo + equalTo: function(value, element, param) { + // bind to the blur event of the target in order to revalidate whenever the target field is updated + // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead + var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() { + $(element).valid(); + }); + return value == target.val(); + } + + } + +}); + +// deprecated, use $.validator.format instead +$.format = $.validator.format; + +})(jQuery); + +// ajax mode: abort +// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]}); +// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() +;(function($) { + var pendingRequests = {}; + // Use a prefilter if available (1.5+) + if ( $.ajaxPrefilter ) { + $.ajaxPrefilter(function(settings, _, xhr) { + var port = settings.port; + if (settings.mode == "abort") { + if ( pendingRequests[port] ) { + pendingRequests[port].abort(); + } pendingRequests[port] = xhr; + } + }); + } else { + // Proxy ajax + var ajax = $.ajax; + $.ajax = function(settings) { + var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode, + port = ( "port" in settings ? settings : $.ajaxSettings ).port; + if (mode == "abort") { + if ( pendingRequests[port] ) { + pendingRequests[port].abort(); + } + + return (pendingRequests[port] = ajax.apply(this, arguments)); + } + return ajax.apply(this, arguments); + }; + } +})(jQuery); + +// provides cross-browser focusin and focusout events +// IE has native support, in other browsers, use event caputuring (neither bubbles) + +// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation +// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target +;(function($) { + // only implement if not provided by jQuery core (since 1.4) + // TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs + if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) { + $.each({ + focus: 'focusin', + blur: 'focusout' + }, function( original, fix ){ + $.event.special[fix] = { + setup:function() { + this.addEventListener( original, handler, true ); + }, + teardown:function() { + this.removeEventListener( original, handler, true ); + }, + handler: function(e) { + arguments[0] = $.event.fix(e); + arguments[0].type = fix; + return $.event.handle.apply(this, arguments); + } + }; + function handler(e) { + e = $.event.fix(e); + e.type = fix; + return $.event.handle.call(this, e); + } + }); + }; + $.extend($.fn, { + validateDelegate: function(delegate, type, handler) { + return this.bind(type, function(event) { + var target = $(event.target); + if (target.is(delegate)) { + return handler.apply(target, arguments); + } + }); + } + }); +})(jQuery); diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.js new file mode 100644 index 0000000..c71dbb2 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.js @@ -0,0 +1,1186 @@ +/** + * jQuery Validation Plugin 1.9.0 + * + * http://bassistance.de/jquery-plugins/jquery-plugin-validation/ + * http://docs.jquery.com/Plugins/Validation + * + * Copyright (c) 2006 - 2011 Jörn Zaefferer + * + * Licensed under MIT: http://www.opensource.org/licenses/mit-license.php + */ + +(function($) { + +$.extend($.fn, { + // http://docs.jquery.com/Plugins/Validation/validate + validate: function( options ) { + + // if nothing is selected, return nothing; can't chain anyway + if (!this.length) { + options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" ); + return; + } + + // check if a validator for this form was already created + var validator = $.data(this[0], 'validator'); + if ( validator ) { + return validator; + } + + // Add novalidate tag if HTML5. + this.attr('novalidate', 'novalidate'); + + validator = new $.validator( options, this[0] ); + $.data(this[0], 'validator', validator); + + if ( validator.settings.onsubmit ) { + + var inputsAndButtons = this.find("input, button"); + + // allow suppresing validation by adding a cancel class to the submit button + inputsAndButtons.filter(".cancel").click(function () { + validator.cancelSubmit = true; + }); + + // when a submitHandler is used, capture the submitting button + if (validator.settings.submitHandler) { + inputsAndButtons.filter(":submit").click(function () { + validator.submitButton = this; + }); + } + + // validate the form on submit + this.submit( function( event ) { + if ( validator.settings.debug ) + // prevent form submit to be able to see console output + event.preventDefault(); + + function handle() { + if ( validator.settings.submitHandler ) { + if (validator.submitButton) { + // insert a hidden input as a replacement for the missing submit button + var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm); + } + validator.settings.submitHandler.call( validator, validator.currentForm ); + if (validator.submitButton) { + // and clean up afterwards; thanks to no-block-scope, hidden can be referenced + hidden.remove(); + } + return false; + } + return true; + } + + // prevent submit for invalid forms or custom submit handlers + if ( validator.cancelSubmit ) { + validator.cancelSubmit = false; + return handle(); + } + if ( validator.form() ) { + if ( validator.pendingRequest ) { + validator.formSubmitted = true; + return false; + } + return handle(); + } else { + validator.focusInvalid(); + return false; + } + }); + } + + return validator; + }, + // http://docs.jquery.com/Plugins/Validation/valid + valid: function() { + if ( $(this[0]).is('form')) { + return this.validate().form(); + } else { + var valid = true; + var validator = $(this[0].form).validate(); + this.each(function() { + valid &= validator.element(this); + }); + return valid; + } + }, + // attributes: space seperated list of attributes to retrieve and remove + removeAttrs: function(attributes) { + var result = {}, + $element = this; + $.each(attributes.split(/\s/), function(index, value) { + result[value] = $element.attr(value); + $element.removeAttr(value); + }); + return result; + }, + // http://docs.jquery.com/Plugins/Validation/rules + rules: function(command, argument) { + var element = this[0]; + + if (command) { + var settings = $.data(element.form, 'validator').settings; + var staticRules = settings.rules; + var existingRules = $.validator.staticRules(element); + switch(command) { + case "add": + $.extend(existingRules, $.validator.normalizeRule(argument)); + staticRules[element.name] = existingRules; + if (argument.messages) + settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages ); + break; + case "remove": + if (!argument) { + delete staticRules[element.name]; + return existingRules; + } + var filtered = {}; + $.each(argument.split(/\s/), function(index, method) { + filtered[method] = existingRules[method]; + delete existingRules[method]; + }); + return filtered; + } + } + + var data = $.validator.normalizeRules( + $.extend( + {}, + $.validator.metadataRules(element), + $.validator.classRules(element), + $.validator.attributeRules(element), + $.validator.staticRules(element) + ), element); + + // make sure required is at front + if (data.required) { + var param = data.required; + delete data.required; + data = $.extend({required: param}, data); + } + + return data; + } +}); + +// Custom selectors +$.extend($.expr[":"], { + // http://docs.jquery.com/Plugins/Validation/blank + blank: function(a) {return !$.trim("" + a.value);}, + // http://docs.jquery.com/Plugins/Validation/filled + filled: function(a) {return !!$.trim("" + a.value);}, + // http://docs.jquery.com/Plugins/Validation/unchecked + unchecked: function(a) {return !a.checked;} +}); + +// constructor for validator +$.validator = function( options, form ) { + this.settings = $.extend( true, {}, $.validator.defaults, options ); + this.currentForm = form; + this.init(); +}; + +$.validator.format = function(source, params) { + if ( arguments.length == 1 ) + return function() { + var args = $.makeArray(arguments); + args.unshift(source); + return $.validator.format.apply( this, args ); + }; + if ( arguments.length > 2 && params.constructor != Array ) { + params = $.makeArray(arguments).slice(1); + } + if ( params.constructor != Array ) { + params = [ params ]; + } + $.each(params, function(i, n) { + source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n); + }); + return source; +}; + +$.extend($.validator, { + + defaults: { + messages: {}, + groups: {}, + rules: {}, + errorClass: "error", + validClass: "valid", + errorElement: "label", + focusInvalid: true, + errorContainer: $( [] ), + errorLabelContainer: $( [] ), + onsubmit: true, + ignore: ":hidden", + ignoreTitle: false, + onfocusin: function(element, event) { + this.lastActive = element; + + // hide error label and remove error class on focus if enabled + if ( this.settings.focusCleanup && !this.blockFocusCleanup ) { + this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass ); + this.addWrapper(this.errorsFor(element)).hide(); + } + }, + onfocusout: function(element, event) { + if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) { + this.element(element); + } + }, + onkeyup: function(element, event) { + if ( element.name in this.submitted || element == this.lastElement ) { + this.element(element); + } + }, + onclick: function(element, event) { + // click on selects, radiobuttons and checkboxes + if ( element.name in this.submitted ) + this.element(element); + // or option elements, check parent select in that case + else if (element.parentNode.name in this.submitted) + this.element(element.parentNode); + }, + highlight: function(element, errorClass, validClass) { + if (element.type === 'radio') { + this.findByName(element.name).addClass(errorClass).removeClass(validClass); + } else { + $(element).addClass(errorClass).removeClass(validClass); + } + }, + unhighlight: function(element, errorClass, validClass) { + if (element.type === 'radio') { + this.findByName(element.name).removeClass(errorClass).addClass(validClass); + } else { + $(element).removeClass(errorClass).addClass(validClass); + } + } + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults + setDefaults: function(settings) { + $.extend( $.validator.defaults, settings ); + }, + + messages: { + required: "This field is required.", + remote: "Please fix this field.", + email: "Please enter a valid email address.", + url: "Please enter a valid URL.", + date: "Please enter a valid date.", + dateISO: "Please enter a valid date (ISO).", + number: "Please enter a valid number.", + digits: "Please enter only digits.", + creditcard: "Please enter a valid credit card number.", + equalTo: "Please enter the same value again.", + accept: "Please enter a value with a valid extension.", + maxlength: $.validator.format("Please enter no more than {0} characters."), + minlength: $.validator.format("Please enter at least {0} characters."), + rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."), + range: $.validator.format("Please enter a value between {0} and {1}."), + max: $.validator.format("Please enter a value less than or equal to {0}."), + min: $.validator.format("Please enter a value greater than or equal to {0}.") + }, + + autoCreateRanges: false, + + prototype: { + + init: function() { + this.labelContainer = $(this.settings.errorLabelContainer); + this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm); + this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer ); + this.submitted = {}; + this.valueCache = {}; + this.pendingRequest = 0; + this.pending = {}; + this.invalid = {}; + this.reset(); + + var groups = (this.groups = {}); + $.each(this.settings.groups, function(key, value) { + $.each(value.split(/\s/), function(index, name) { + groups[name] = key; + }); + }); + var rules = this.settings.rules; + $.each(rules, function(key, value) { + rules[key] = $.validator.normalizeRule(value); + }); + + function delegate(event) { + var validator = $.data(this[0].form, "validator"), + eventType = "on" + event.type.replace(/^validate/, ""); + validator.settings[eventType] && validator.settings[eventType].call(validator, this[0], event); + } + $(this.currentForm) + .validateDelegate("[type='text'], [type='password'], [type='file'], select, textarea, " + + "[type='number'], [type='search'] ,[type='tel'], [type='url'], " + + "[type='email'], [type='datetime'], [type='date'], [type='month'], " + + "[type='week'], [type='time'], [type='datetime-local'], " + + "[type='range'], [type='color'] ", + "focusin focusout keyup", delegate) + .validateDelegate("[type='radio'], [type='checkbox'], select, option", "click", delegate); + + if (this.settings.invalidHandler) + $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler); + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/form + form: function() { + this.checkForm(); + $.extend(this.submitted, this.errorMap); + this.invalid = $.extend({}, this.errorMap); + if (!this.valid()) + $(this.currentForm).triggerHandler("invalid-form", [this]); + this.showErrors(); + return this.valid(); + }, + + checkForm: function() { + this.prepareForm(); + for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) { + this.check( elements[i] ); + } + return this.valid(); + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/element + element: function( element ) { + element = this.validationTargetFor( this.clean( element ) ); + this.lastElement = element; + this.prepareElement( element ); + this.currentElements = $(element); + var result = this.check( element ); + if ( result ) { + delete this.invalid[element.name]; + } else { + this.invalid[element.name] = true; + } + if ( !this.numberOfInvalids() ) { + // Hide error containers on last error + this.toHide = this.toHide.add( this.containers ); + } + this.showErrors(); + return result; + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/showErrors + showErrors: function(errors) { + if(errors) { + // add items to error list and map + $.extend( this.errorMap, errors ); + this.errorList = []; + for ( var name in errors ) { + this.errorList.push({ + message: errors[name], + element: this.findByName(name)[0] + }); + } + // remove items from success list + this.successList = $.grep( this.successList, function(element) { + return !(element.name in errors); + }); + } + this.settings.showErrors + ? this.settings.showErrors.call( this, this.errorMap, this.errorList ) + : this.defaultShowErrors(); + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/resetForm + resetForm: function() { + if ( $.fn.resetForm ) + $( this.currentForm ).resetForm(); + this.submitted = {}; + this.lastElement = null; + this.prepareForm(); + this.hideErrors(); + this.elements().removeClass( this.settings.errorClass ); + }, + + numberOfInvalids: function() { + return this.objectLength(this.invalid); + }, + + objectLength: function( obj ) { + var count = 0; + for ( var i in obj ) + count++; + return count; + }, + + hideErrors: function() { + this.addWrapper( this.toHide ).hide(); + }, + + valid: function() { + return this.size() == 0; + }, + + size: function() { + return this.errorList.length; + }, + + focusInvalid: function() { + if( this.settings.focusInvalid ) { + try { + $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []) + .filter(":visible") + .focus() + // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find + .trigger("focusin"); + } catch(e) { + // ignore IE throwing errors when focusing hidden elements + } + } + }, + + findLastActive: function() { + var lastActive = this.lastActive; + return lastActive && $.grep(this.errorList, function(n) { + return n.element.name == lastActive.name; + }).length == 1 && lastActive; + }, + + elements: function() { + var validator = this, + rulesCache = {}; + + // select all valid inputs inside the form (no submit or reset buttons) + return $(this.currentForm) + .find("input, select, textarea") + .not(":submit, :reset, :image, [disabled]") + .not( this.settings.ignore ) + .filter(function() { + !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this); + + // select only the first element for each name, and only those with rules specified + if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) + return false; + + rulesCache[this.name] = true; + return true; + }); + }, + + clean: function( selector ) { + return $( selector )[0]; + }, + + errors: function() { + return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext ); + }, + + reset: function() { + this.successList = []; + this.errorList = []; + this.errorMap = {}; + this.toShow = $([]); + this.toHide = $([]); + this.currentElements = $([]); + }, + + prepareForm: function() { + this.reset(); + this.toHide = this.errors().add( this.containers ); + }, + + prepareElement: function( element ) { + this.reset(); + this.toHide = this.errorsFor(element); + }, + + check: function( element ) { + element = this.validationTargetFor( this.clean( element ) ); + + var rules = $(element).rules(); + var dependencyMismatch = false; + for (var method in rules ) { + var rule = { method: method, parameters: rules[method] }; + try { + var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters ); + + // if a method indicates that the field is optional and therefore valid, + // don't mark it as valid when there are no other rules + if ( result == "dependency-mismatch" ) { + dependencyMismatch = true; + continue; + } + dependencyMismatch = false; + + if ( result == "pending" ) { + this.toHide = this.toHide.not( this.errorsFor(element) ); + return; + } + + if( !result ) { + this.formatAndAdd( element, rule ); + return false; + } + } catch(e) { + this.settings.debug && window.console && console.log("exception occured when checking element " + element.id + + ", check the '" + rule.method + "' method", e); + throw e; + } + } + if (dependencyMismatch) + return; + if ( this.objectLength(rules) ) + this.successList.push(element); + return true; + }, + + // return the custom message for the given element and validation method + // specified in the element's "messages" metadata + customMetaMessage: function(element, method) { + if (!$.metadata) + return; + + var meta = this.settings.meta + ? $(element).metadata()[this.settings.meta] + : $(element).metadata(); + + return meta && meta.messages && meta.messages[method]; + }, + + // return the custom message for the given element name and validation method + customMessage: function( name, method ) { + var m = this.settings.messages[name]; + return m && (m.constructor == String + ? m + : m[method]); + }, + + // return the first defined argument, allowing empty strings + findDefined: function() { + for(var i = 0; i < arguments.length; i++) { + if (arguments[i] !== undefined) + return arguments[i]; + } + return undefined; + }, + + defaultMessage: function( element, method) { + return this.findDefined( + this.customMessage( element.name, method ), + this.customMetaMessage( element, method ), + // title is never undefined, so handle empty string as undefined + !this.settings.ignoreTitle && element.title || undefined, + $.validator.messages[method], + "<strong>Warning: No message defined for " + element.name + "</strong>" + ); + }, + + formatAndAdd: function( element, rule ) { + var message = this.defaultMessage( element, rule.method ), + theregex = /\$?\{(\d+)\}/g; + if ( typeof message == "function" ) { + message = message.call(this, rule.parameters, element); + } else if (theregex.test(message)) { + message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters); + } + this.errorList.push({ + message: message, + element: element + }); + + this.errorMap[element.name] = message; + this.submitted[element.name] = message; + }, + + addWrapper: function(toToggle) { + if ( this.settings.wrapper ) + toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) ); + return toToggle; + }, + + defaultShowErrors: function() { + for ( var i = 0; this.errorList[i]; i++ ) { + var error = this.errorList[i]; + this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass ); + this.showLabel( error.element, error.message ); + } + if( this.errorList.length ) { + this.toShow = this.toShow.add( this.containers ); + } + if (this.settings.success) { + for ( var i = 0; this.successList[i]; i++ ) { + this.showLabel( this.successList[i] ); + } + } + if (this.settings.unhighlight) { + for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) { + this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass ); + } + } + this.toHide = this.toHide.not( this.toShow ); + this.hideErrors(); + this.addWrapper( this.toShow ).show(); + }, + + validElements: function() { + return this.currentElements.not(this.invalidElements()); + }, + + invalidElements: function() { + return $(this.errorList).map(function() { + return this.element; + }); + }, + + showLabel: function(element, message) { + var label = this.errorsFor( element ); + if ( label.length ) { + // refresh error/success class + label.removeClass( this.settings.validClass ).addClass( this.settings.errorClass ); + + // check if we have a generated label, replace the message then + label.attr("generated") && label.html(message); + } else { + // create label + label = $("<" + this.settings.errorElement + "/>") + .attr({"for": this.idOrName(element), generated: true}) + .addClass(this.settings.errorClass) + .html(message || ""); + if ( this.settings.wrapper ) { + // make sure the element is visible, even in IE + // actually showing the wrapped element is handled elsewhere + label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent(); + } + if ( !this.labelContainer.append(label).length ) + this.settings.errorPlacement + ? this.settings.errorPlacement(label, $(element) ) + : label.insertAfter(element); + } + if ( !message && this.settings.success ) { + label.text(""); + typeof this.settings.success == "string" + ? label.addClass( this.settings.success ) + : this.settings.success( label ); + } + this.toShow = this.toShow.add(label); + }, + + errorsFor: function(element) { + var name = this.idOrName(element); + return this.errors().filter(function() { + return $(this).attr('for') == name; + }); + }, + + idOrName: function(element) { + return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name); + }, + + validationTargetFor: function(element) { + // if radio/checkbox, validate first element in group instead + if (this.checkable(element)) { + element = this.findByName( element.name ).not(this.settings.ignore)[0]; + } + return element; + }, + + checkable: function( element ) { + return /radio|checkbox/i.test(element.type); + }, + + findByName: function( name ) { + // select by name and filter by form for performance over form.find("[name=...]") + var form = this.currentForm; + return $(document.getElementsByName(name)).map(function(index, element) { + return element.form == form && element.name == name && element || null; + }); + }, + + getLength: function(value, element) { + switch( element.nodeName.toLowerCase() ) { + case 'select': + return $("option:selected", element).length; + case 'input': + if( this.checkable( element) ) + return this.findByName(element.name).filter(':checked').length; + } + return value.length; + }, + + depend: function(param, element) { + return this.dependTypes[typeof param] + ? this.dependTypes[typeof param](param, element) + : true; + }, + + dependTypes: { + "boolean": function(param, element) { + return param; + }, + "string": function(param, element) { + return !!$(param, element.form).length; + }, + "function": function(param, element) { + return param(element); + } + }, + + optional: function(element) { + return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch"; + }, + + startRequest: function(element) { + if (!this.pending[element.name]) { + this.pendingRequest++; + this.pending[element.name] = true; + } + }, + + stopRequest: function(element, valid) { + this.pendingRequest--; + // sometimes synchronization fails, make sure pendingRequest is never < 0 + if (this.pendingRequest < 0) + this.pendingRequest = 0; + delete this.pending[element.name]; + if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) { + $(this.currentForm).submit(); + this.formSubmitted = false; + } else if (!valid && this.pendingRequest == 0 && this.formSubmitted) { + $(this.currentForm).triggerHandler("invalid-form", [this]); + this.formSubmitted = false; + } + }, + + previousValue: function(element) { + return $.data(element, "previousValue") || $.data(element, "previousValue", { + old: null, + valid: true, + message: this.defaultMessage( element, "remote" ) + }); + } + + }, + + classRuleSettings: { + required: {required: true}, + email: {email: true}, + url: {url: true}, + date: {date: true}, + dateISO: {dateISO: true}, + dateDE: {dateDE: true}, + number: {number: true}, + numberDE: {numberDE: true}, + digits: {digits: true}, + creditcard: {creditcard: true} + }, + + addClassRules: function(className, rules) { + className.constructor == String ? + this.classRuleSettings[className] = rules : + $.extend(this.classRuleSettings, className); + }, + + classRules: function(element) { + var rules = {}; + var classes = $(element).attr('class'); + classes && $.each(classes.split(' '), function() { + if (this in $.validator.classRuleSettings) { + $.extend(rules, $.validator.classRuleSettings[this]); + } + }); + return rules; + }, + + attributeRules: function(element) { + var rules = {}; + var $element = $(element); + + for (var method in $.validator.methods) { + var value; + // If .prop exists (jQuery >= 1.6), use it to get true/false for required + if (method === 'required' && typeof $.fn.prop === 'function') { + value = $element.prop(method); + } else { + value = $element.attr(method); + } + if (value) { + rules[method] = value; + } else if ($element[0].getAttribute("type") === method) { + rules[method] = true; + } + } + + // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs + if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) { + delete rules.maxlength; + } + + return rules; + }, + + metadataRules: function(element) { + if (!$.metadata) return {}; + + var meta = $.data(element.form, 'validator').settings.meta; + return meta ? + $(element).metadata()[meta] : + $(element).metadata(); + }, + + staticRules: function(element) { + var rules = {}; + var validator = $.data(element.form, 'validator'); + if (validator.settings.rules) { + rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {}; + } + return rules; + }, + + normalizeRules: function(rules, element) { + // handle dependency check + $.each(rules, function(prop, val) { + // ignore rule when param is explicitly false, eg. required:false + if (val === false) { + delete rules[prop]; + return; + } + if (val.param || val.depends) { + var keepRule = true; + switch (typeof val.depends) { + case "string": + keepRule = !!$(val.depends, element.form).length; + break; + case "function": + keepRule = val.depends.call(element, element); + break; + } + if (keepRule) { + rules[prop] = val.param !== undefined ? val.param : true; + } else { + delete rules[prop]; + } + } + }); + + // evaluate parameters + $.each(rules, function(rule, parameter) { + rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter; + }); + + // clean number parameters + $.each(['minlength', 'maxlength', 'min', 'max'], function() { + if (rules[this]) { + rules[this] = Number(rules[this]); + } + }); + $.each(['rangelength', 'range'], function() { + if (rules[this]) { + rules[this] = [Number(rules[this][0]), Number(rules[this][1])]; + } + }); + + if ($.validator.autoCreateRanges) { + // auto-create ranges + if (rules.min && rules.max) { + rules.range = [rules.min, rules.max]; + delete rules.min; + delete rules.max; + } + if (rules.minlength && rules.maxlength) { + rules.rangelength = [rules.minlength, rules.maxlength]; + delete rules.minlength; + delete rules.maxlength; + } + } + + // To support custom messages in metadata ignore rule methods titled "messages" + if (rules.messages) { + delete rules.messages; + } + + return rules; + }, + + // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} + normalizeRule: function(data) { + if( typeof data == "string" ) { + var transformed = {}; + $.each(data.split(/\s/), function() { + transformed[this] = true; + }); + data = transformed; + } + return data; + }, + + // http://docs.jquery.com/Plugins/Validation/Validator/addMethod + addMethod: function(name, method, message) { + $.validator.methods[name] = method; + $.validator.messages[name] = message != undefined ? message : $.validator.messages[name]; + if (method.length < 3) { + $.validator.addClassRules(name, $.validator.normalizeRule(name)); + } + }, + + methods: { + + // http://docs.jquery.com/Plugins/Validation/Methods/required + required: function(value, element, param) { + // check if dependency is met + if ( !this.depend(param, element) ) + return "dependency-mismatch"; + switch( element.nodeName.toLowerCase() ) { + case 'select': + // could be an array for select-multiple or a string, both are fine this way + var val = $(element).val(); + return val && val.length > 0; + case 'input': + if ( this.checkable(element) ) + return this.getLength(value, element) > 0; + default: + return $.trim(value).length > 0; + } + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/remote + remote: function(value, element, param) { + if ( this.optional(element) ) + return "dependency-mismatch"; + + var previous = this.previousValue(element); + if (!this.settings.messages[element.name] ) + this.settings.messages[element.name] = {}; + previous.originalMessage = this.settings.messages[element.name].remote; + this.settings.messages[element.name].remote = previous.message; + + param = typeof param == "string" && {url:param} || param; + + if ( this.pending[element.name] ) { + return "pending"; + } + if ( previous.old === value ) { + return previous.valid; + } + + previous.old = value; + var validator = this; + this.startRequest(element); + var data = {}; + data[element.name] = value; + $.ajax($.extend(true, { + url: param, + mode: "abort", + port: "validate" + element.name, + dataType: "json", + data: data, + success: function(response) { + validator.settings.messages[element.name].remote = previous.originalMessage; + var valid = response === true; + if ( valid ) { + var submitted = validator.formSubmitted; + validator.prepareElement(element); + validator.formSubmitted = submitted; + validator.successList.push(element); + validator.showErrors(); + } else { + var errors = {}; + var message = response || validator.defaultMessage( element, "remote" ); + errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message; + validator.showErrors(errors); + } + previous.valid = valid; + validator.stopRequest(element, valid); + } + }, param)); + return "pending"; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/minlength + minlength: function(value, element, param) { + return this.optional(element) || this.getLength($.trim(value), element) >= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/maxlength + maxlength: function(value, element, param) { + return this.optional(element) || this.getLength($.trim(value), element) <= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/rangelength + rangelength: function(value, element, param) { + var length = this.getLength($.trim(value), element); + return this.optional(element) || ( length >= param[0] && length <= param[1] ); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/min + min: function( value, element, param ) { + return this.optional(element) || value >= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/max + max: function( value, element, param ) { + return this.optional(element) || value <= param; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/range + range: function( value, element, param ) { + return this.optional(element) || ( value >= param[0] && value <= param[1] ); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/email + email: function(value, element) { + // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ + return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/url + url: function(value, element) { + // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/ + return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/date + date: function(value, element) { + return this.optional(element) || !/Invalid|NaN/.test(new Date(value)); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/dateISO + dateISO: function(value, element) { + return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/number + number: function(value, element) { + return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/digits + digits: function(value, element) { + return this.optional(element) || /^\d+$/.test(value); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/creditcard + // based on http://en.wikipedia.org/wiki/Luhn + creditcard: function(value, element) { + if ( this.optional(element) ) + return "dependency-mismatch"; + // accept only spaces, digits and dashes + if (/[^0-9 -]+/.test(value)) + return false; + var nCheck = 0, + nDigit = 0, + bEven = false; + + value = value.replace(/\D/g, ""); + + for (var n = value.length - 1; n >= 0; n--) { + var cDigit = value.charAt(n); + var nDigit = parseInt(cDigit, 10); + if (bEven) { + if ((nDigit *= 2) > 9) + nDigit -= 9; + } + nCheck += nDigit; + bEven = !bEven; + } + + return (nCheck % 10) == 0; + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/accept + accept: function(value, element, param) { + param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif"; + return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i")); + }, + + // http://docs.jquery.com/Plugins/Validation/Methods/equalTo + equalTo: function(value, element, param) { + // bind to the blur event of the target in order to revalidate whenever the target field is updated + // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead + var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() { + $(element).valid(); + }); + return value == target.val(); + } + + } + +}); + +// deprecated, use $.validator.format instead +$.format = $.validator.format; + +})(jQuery); + +// ajax mode: abort +// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]}); +// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort() +;(function($) { + var pendingRequests = {}; + // Use a prefilter if available (1.5+) + if ( $.ajaxPrefilter ) { + $.ajaxPrefilter(function(settings, _, xhr) { + var port = settings.port; + if (settings.mode == "abort") { + if ( pendingRequests[port] ) { + pendingRequests[port].abort(); + } + pendingRequests[port] = xhr; + } + }); + } else { + // Proxy ajax + var ajax = $.ajax; + $.ajax = function(settings) { + var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode, + port = ( "port" in settings ? settings : $.ajaxSettings ).port; + if (mode == "abort") { + if ( pendingRequests[port] ) { + pendingRequests[port].abort(); + } + return (pendingRequests[port] = ajax.apply(this, arguments)); + } + return ajax.apply(this, arguments); + }; + } +})(jQuery); + +// provides cross-browser focusin and focusout events +// IE has native support, in other browsers, use event caputuring (neither bubbles) + +// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation +// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target +;(function($) { + // only implement if not provided by jQuery core (since 1.4) + // TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs + if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) { + $.each({ + focus: 'focusin', + blur: 'focusout' + }, function( original, fix ){ + $.event.special[fix] = { + setup:function() { + this.addEventListener( original, handler, true ); + }, + teardown:function() { + this.removeEventListener( original, handler, true ); + }, + handler: function(e) { + arguments[0] = $.event.fix(e); + arguments[0].type = fix; + return $.event.handle.apply(this, arguments); + } + }; + function handler(e) { + e = $.event.fix(e); + e.type = fix; + return $.event.handle.call(this, e); + } + }); + }; + $.extend($.fn, { + validateDelegate: function(delegate, type, handler) { + return this.bind(type, function(event) { + var target = $(event.target); + if (target.is(delegate)) { + return handler.apply(target, arguments); + } + }); + } + }); +})(jQuery); diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.min.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.min.js new file mode 100644 index 0000000..ebf8367 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.min.js @@ -0,0 +1,49 @@ +/** + * jQuery Validation Plugin 1.9.0 + * + * http://bassistance.de/jquery-plugins/jquery-plugin-validation/ + * http://docs.jquery.com/Plugins/Validation + * + * Copyright (c) 2006 - 2011 Jörn Zaefferer + * + * Licensed under MIT: http://www.opensource.org/licenses/mit-license.php + */ +(function(c){c.extend(c.fn,{validate:function(a){if(this.length){var b=c.data(this[0],"validator");if(b)return b;this.attr("novalidate","novalidate");b=new c.validator(a,this[0]);c.data(this[0],"validator",b);if(b.settings.onsubmit){a=this.find("input, button");a.filter(".cancel").click(function(){b.cancelSubmit=true});b.settings.submitHandler&&a.filter(":submit").click(function(){b.submitButton=this});this.submit(function(d){function e(){if(b.settings.submitHandler){if(b.submitButton)var f=c("<input type='hidden'/>").attr("name", +b.submitButton.name).val(b.submitButton.value).appendTo(b.currentForm);b.settings.submitHandler.call(b,b.currentForm);b.submitButton&&f.remove();return false}return true}b.settings.debug&&d.preventDefault();if(b.cancelSubmit){b.cancelSubmit=false;return e()}if(b.form()){if(b.pendingRequest){b.formSubmitted=true;return false}return e()}else{b.focusInvalid();return false}})}return b}else a&&a.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing")},valid:function(){if(c(this[0]).is("form"))return this.validate().form(); +else{var a=true,b=c(this[0].form).validate();this.each(function(){a&=b.element(this)});return a}},removeAttrs:function(a){var b={},d=this;c.each(a.split(/\s/),function(e,f){b[f]=d.attr(f);d.removeAttr(f)});return b},rules:function(a,b){var d=this[0];if(a){var e=c.data(d.form,"validator").settings,f=e.rules,g=c.validator.staticRules(d);switch(a){case "add":c.extend(g,c.validator.normalizeRule(b));f[d.name]=g;if(b.messages)e.messages[d.name]=c.extend(e.messages[d.name],b.messages);break;case "remove":if(!b){delete f[d.name]; +return g}var h={};c.each(b.split(/\s/),function(j,i){h[i]=g[i];delete g[i]});return h}}d=c.validator.normalizeRules(c.extend({},c.validator.metadataRules(d),c.validator.classRules(d),c.validator.attributeRules(d),c.validator.staticRules(d)),d);if(d.required){e=d.required;delete d.required;d=c.extend({required:e},d)}return d}});c.extend(c.expr[":"],{blank:function(a){return!c.trim(""+a.value)},filled:function(a){return!!c.trim(""+a.value)},unchecked:function(a){return!a.checked}});c.validator=function(a, +b){this.settings=c.extend(true,{},c.validator.defaults,a);this.currentForm=b;this.init()};c.validator.format=function(a,b){if(arguments.length==1)return function(){var d=c.makeArray(arguments);d.unshift(a);return c.validator.format.apply(this,d)};if(arguments.length>2&&b.constructor!=Array)b=c.makeArray(arguments).slice(1);if(b.constructor!=Array)b=[b];c.each(b,function(d,e){a=a.replace(RegExp("\\{"+d+"\\}","g"),e)});return a};c.extend(c.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error", +validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:c([]),errorLabelContainer:c([]),onsubmit:true,ignore:":hidden",ignoreTitle:false,onfocusin:function(a){this.lastActive=a;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(a)).hide()}},onfocusout:function(a){if(!this.checkable(a)&&(a.name in this.submitted||!this.optional(a)))this.element(a)}, +onkeyup:function(a){if(a.name in this.submitted||a==this.lastElement)this.element(a)},onclick:function(a){if(a.name in this.submitted)this.element(a);else a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).addClass(b).removeClass(d):c(a).addClass(b).removeClass(d)},unhighlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).removeClass(b).addClass(d):c(a).removeClass(b).addClass(d)}},setDefaults:function(a){c.extend(c.validator.defaults, +a)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:c.validator.format("Please enter no more than {0} characters."), +minlength:c.validator.format("Please enter at least {0} characters."),rangelength:c.validator.format("Please enter a value between {0} and {1} characters long."),range:c.validator.format("Please enter a value between {0} and {1}."),max:c.validator.format("Please enter a value less than or equal to {0}."),min:c.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){function a(e){var f=c.data(this[0].form,"validator"),g="on"+e.type.replace(/^validate/, +"");f.settings[g]&&f.settings[g].call(f,this[0],e)}this.labelContainer=c(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||c(this.currentForm);this.containers=c(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var b=this.groups={};c.each(this.settings.groups,function(e,f){c.each(f.split(/\s/),function(g,h){b[h]=e})});var d= +this.settings.rules;c.each(d,function(e,f){d[e]=c.validator.normalizeRule(f)});c(this.currentForm).validateDelegate("[type='text'], [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'] ","focusin focusout keyup",a).validateDelegate("[type='radio'], [type='checkbox'], select, option","click", +a);this.settings.invalidHandler&&c(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){this.checkForm();c.extend(this.submitted,this.errorMap);this.invalid=c.extend({},this.errorMap);this.valid()||c(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(a){this.lastElement= +a=this.validationTargetFor(this.clean(a));this.prepareElement(a);this.currentElements=c(a);var b=this.check(a);if(b)delete this.invalid[a.name];else this.invalid[a.name]=true;if(!this.numberOfInvalids())this.toHide=this.toHide.add(this.containers);this.showErrors();return b},showErrors:function(a){if(a){c.extend(this.errorMap,a);this.errorList=[];for(var b in a)this.errorList.push({message:a[b],element:this.findByName(b)[0]});this.successList=c.grep(this.successList,function(d){return!(d.name in a)})}this.settings.showErrors? +this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){c.fn.resetForm&&c(this.currentForm).resetForm();this.submitted={};this.lastElement=null;this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b=0,d;for(d in a)b++;return b},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()== +0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{c(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(a){}},findLastActive:function(){var a=this.lastActive;return a&&c.grep(this.errorList,function(b){return b.element.name==a.name}).length==1&&a},elements:function(){var a=this,b={};return c(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&& +a.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in b||!a.objectLength(c(this).rules()))return false;return b[this.name]=true})},clean:function(a){return c(a)[0]},errors:function(){return c(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=c([]);this.toHide=c([]);this.currentElements=c([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)}, +prepareElement:function(a){this.reset();this.toHide=this.errorsFor(a)},check:function(a){a=this.validationTargetFor(this.clean(a));var b=c(a).rules(),d=false,e;for(e in b){var f={method:e,parameters:b[e]};try{var g=c.validator.methods[e].call(this,a.value.replace(/\r/g,""),a,f.parameters);if(g=="dependency-mismatch")d=true;else{d=false;if(g=="pending"){this.toHide=this.toHide.not(this.errorsFor(a));return}if(!g){this.formatAndAdd(a,f);return false}}}catch(h){this.settings.debug&&window.console&&console.log("exception occured when checking element "+ +a.id+", check the '"+f.method+"' method",h);throw h;}}if(!d){this.objectLength(b)&&this.successList.push(a);return true}},customMetaMessage:function(a,b){if(c.metadata){var d=this.settings.meta?c(a).metadata()[this.settings.meta]:c(a).metadata();return d&&d.messages&&d.messages[b]}},customMessage:function(a,b){var d=this.settings.messages[a];return d&&(d.constructor==String?d:d[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==undefined)return arguments[a]},defaultMessage:function(a, +b){return this.findDefined(this.customMessage(a.name,b),this.customMetaMessage(a,b),!this.settings.ignoreTitle&&a.title||undefined,c.validator.messages[b],"<strong>Warning: No message defined for "+a.name+"</strong>")},formatAndAdd:function(a,b){var d=this.defaultMessage(a,b.method),e=/\$?\{(\d+)\}/g;if(typeof d=="function")d=d.call(this,b.parameters,a);else if(e.test(d))d=jQuery.format(d.replace(e,"{$1}"),b.parameters);this.errorList.push({message:d,element:a});this.errorMap[a.name]=d;this.submitted[a.name]= +d},addWrapper:function(a){if(this.settings.wrapper)a=a.add(a.parent(this.settings.wrapper));return a},defaultShowErrors:function(){for(var a=0;this.errorList[a];a++){var b=this.errorList[a];this.settings.highlight&&this.settings.highlight.call(this,b.element,this.settings.errorClass,this.settings.validClass);this.showLabel(b.element,b.message)}if(this.errorList.length)this.toShow=this.toShow.add(this.containers);if(this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]); +if(this.settings.unhighlight){a=0;for(b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass)}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return c(this.errorList).map(function(){return this.element})},showLabel:function(a,b){var d=this.errorsFor(a);if(d.length){d.removeClass(this.settings.validClass).addClass(this.settings.errorClass); +d.attr("generated")&&d.html(b)}else{d=c("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(a),generated:true}).addClass(this.settings.errorClass).html(b||"");if(this.settings.wrapper)d=d.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();this.labelContainer.append(d).length||(this.settings.errorPlacement?this.settings.errorPlacement(d,c(a)):d.insertAfter(a))}if(!b&&this.settings.success){d.text("");typeof this.settings.success=="string"?d.addClass(this.settings.success):this.settings.success(d)}this.toShow= +this.toShow.add(d)},errorsFor:function(a){var b=this.idOrName(a);return this.errors().filter(function(){return c(this).attr("for")==b})},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(a){if(this.checkable(a))a=this.findByName(a.name).not(this.settings.ignore)[0];return a},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(a){var b=this.currentForm;return c(document.getElementsByName(a)).map(function(d, +e){return e.form==b&&e.name==a&&e||null})},getLength:function(a,b){switch(b.nodeName.toLowerCase()){case "select":return c("option:selected",b).length;case "input":if(this.checkable(b))return this.findByName(b.name).filter(":checked").length}return a.length},depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):true},dependTypes:{"boolean":function(a){return a},string:function(a,b){return!!c(a,b.form).length},"function":function(a,b){return a(b)}},optional:function(a){return!c.validator.methods.required.call(this, +c.trim(a.value),a)&&"dependency-mismatch"},startRequest:function(a){if(!this.pending[a.name]){this.pendingRequest++;this.pending[a.name]=true}},stopRequest:function(a,b){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[a.name];if(b&&this.pendingRequest==0&&this.formSubmitted&&this.form()){c(this.currentForm).submit();this.formSubmitted=false}else if(!b&&this.pendingRequest==0&&this.formSubmitted){c(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted= +false}},previousValue:function(a){return c.data(a,"previousValue")||c.data(a,"previousValue",{old:null,valid:true,message:this.defaultMessage(a,"remote")})}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(a,b){a.constructor==String?this.classRuleSettings[a]=b:c.extend(this.classRuleSettings, +a)},classRules:function(a){var b={};(a=c(a).attr("class"))&&c.each(a.split(" "),function(){this in c.validator.classRuleSettings&&c.extend(b,c.validator.classRuleSettings[this])});return b},attributeRules:function(a){var b={};a=c(a);for(var d in c.validator.methods){var e;if(e=d==="required"&&typeof c.fn.prop==="function"?a.prop(d):a.attr(d))b[d]=e;else if(a[0].getAttribute("type")===d)b[d]=true}b.maxlength&&/-1|2147483647|524288/.test(b.maxlength)&&delete b.maxlength;return b},metadataRules:function(a){if(!c.metadata)return{}; +var b=c.data(a.form,"validator").settings.meta;return b?c(a).metadata()[b]:c(a).metadata()},staticRules:function(a){var b={},d=c.data(a.form,"validator");if(d.settings.rules)b=c.validator.normalizeRule(d.settings.rules[a.name])||{};return b},normalizeRules:function(a,b){c.each(a,function(d,e){if(e===false)delete a[d];else if(e.param||e.depends){var f=true;switch(typeof e.depends){case "string":f=!!c(e.depends,b.form).length;break;case "function":f=e.depends.call(b,b)}if(f)a[d]=e.param!==undefined? +e.param:true;else delete a[d]}});c.each(a,function(d,e){a[d]=c.isFunction(e)?e(b):e});c.each(["minlength","maxlength","min","max"],function(){if(a[this])a[this]=Number(a[this])});c.each(["rangelength","range"],function(){if(a[this])a[this]=[Number(a[this][0]),Number(a[this][1])]});if(c.validator.autoCreateRanges){if(a.min&&a.max){a.range=[a.min,a.max];delete a.min;delete a.max}if(a.minlength&&a.maxlength){a.rangelength=[a.minlength,a.maxlength];delete a.minlength;delete a.maxlength}}a.messages&&delete a.messages; +return a},normalizeRule:function(a){if(typeof a=="string"){var b={};c.each(a.split(/\s/),function(){b[this]=true});a=b}return a},addMethod:function(a,b,d){c.validator.methods[a]=b;c.validator.messages[a]=d!=undefined?d:c.validator.messages[a];b.length<3&&c.validator.addClassRules(a,c.validator.normalizeRule(a))},methods:{required:function(a,b,d){if(!this.depend(d,b))return"dependency-mismatch";switch(b.nodeName.toLowerCase()){case "select":return(a=c(b).val())&&a.length>0;case "input":if(this.checkable(b))return this.getLength(a, +b)>0;default:return c.trim(a).length>0}},remote:function(a,b,d){if(this.optional(b))return"dependency-mismatch";var e=this.previousValue(b);this.settings.messages[b.name]||(this.settings.messages[b.name]={});e.originalMessage=this.settings.messages[b.name].remote;this.settings.messages[b.name].remote=e.message;d=typeof d=="string"&&{url:d}||d;if(this.pending[b.name])return"pending";if(e.old===a)return e.valid;e.old=a;var f=this;this.startRequest(b);var g={};g[b.name]=a;c.ajax(c.extend(true,{url:d, +mode:"abort",port:"validate"+b.name,dataType:"json",data:g,success:function(h){f.settings.messages[b.name].remote=e.originalMessage;var j=h===true;if(j){var i=f.formSubmitted;f.prepareElement(b);f.formSubmitted=i;f.successList.push(b);f.showErrors()}else{i={};h=h||f.defaultMessage(b,"remote");i[b.name]=e.message=c.isFunction(h)?h(a):h;f.showErrors(i)}e.valid=j;f.stopRequest(b,j)}},d));return"pending"},minlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)>=d},maxlength:function(a, +b,d){return this.optional(b)||this.getLength(c.trim(a),b)<=d},rangelength:function(a,b,d){a=this.getLength(c.trim(a),b);return this.optional(b)||a>=d[0]&&a<=d[1]},min:function(a,b,d){return this.optional(b)||a>=d},max:function(a,b,d){return this.optional(b)||a<=d},range:function(a,b,d){return this.optional(b)||a>=d[0]&&a<=d[1]},email:function(a,b){return this.optional(b)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a)}, +url:function(a,b){return this.optional(b)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)}, +date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a))},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9 -]+/.test(a))return false;var d=0,e=0,f=false;a=a.replace(/\D/g,"");for(var g=a.length-1;g>= +0;g--){e=a.charAt(g);e=parseInt(e,10);if(f)if((e*=2)>9)e-=9;d+=e;f=!f}return d%10==0},accept:function(a,b,d){d=typeof d=="string"?d.replace(/,/g,"|"):"png|jpe?g|gif";return this.optional(b)||a.match(RegExp(".("+d+")$","i"))},equalTo:function(a,b,d){d=c(d).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){c(b).valid()});return a==d.val()}}});c.format=c.validator.format})(jQuery); +(function(c){var a={};if(c.ajaxPrefilter)c.ajaxPrefilter(function(d,e,f){e=d.port;if(d.mode=="abort"){a[e]&&a[e].abort();a[e]=f}});else{var b=c.ajax;c.ajax=function(d){var e=("port"in d?d:c.ajaxSettings).port;if(("mode"in d?d:c.ajaxSettings).mode=="abort"){a[e]&&a[e].abort();return a[e]=b.apply(this,arguments)}return b.apply(this,arguments)}}})(jQuery); +(function(c){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.handle.call(this,e)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)},handler:function(e){arguments[0]=c.event.fix(e);arguments[0].type=b;return c.event.handle.apply(this,arguments)}}});c.extend(c.fn,{validateDelegate:function(a, +b,d){return this.bind(b,function(e){var f=c(e.target);if(f.is(a))return d.apply(f,arguments)})}})})(jQuery); diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.unobtrusive.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.unobtrusive.js new file mode 100644 index 0000000..e2a410f --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.unobtrusive.js @@ -0,0 +1,365 @@ +/*! +** Unobtrusive validation support library for jQuery and jQuery Validate +** Copyright (C) Microsoft Corporation. All rights reserved. +*/ + +/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */ +/*global document: false, jQuery: false */ + +(function ($) { + var $jQval = $.validator, + adapters, + data_validation = "unobtrusiveValidation"; + + function setValidationValues(options, ruleName, value) { + options.rules[ruleName] = value; + if (options.message) { + options.messages[ruleName] = options.message; + } + } + + function splitAndTrim(value) { + return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g); + } + + function escapeAttributeValue(value) { + // As mentioned on http://api.jquery.com/category/selectors/ + return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1"); + } + + function getModelPrefix(fieldName) { + return fieldName.substr(0, fieldName.lastIndexOf(".") + 1); + } + + function appendModelPrefix(value, prefix) { + if (value.indexOf("*.") === 0) { + value = value.replace("*.", prefix); + } + return value; + } + + function onError(error, inputElement) { // 'this' is the form element + var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"), + replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false; + + container.removeClass("field-validation-valid").addClass("field-validation-error"); + error.data("unobtrusiveContainer", container); + + if (replace) { + container.empty(); + error.removeClass("input-validation-error").appendTo(container); + } + else { + error.hide(); + } + } + + function onErrors(event, validator) { // 'this' is the form element + var container = $(this).find("[data-valmsg-summary=true]"), + list = container.find("ul"); + + if (list && list.length && validator.errorList.length) { + list.empty(); + container.addClass("validation-summary-errors").removeClass("validation-summary-valid"); + + $.each(validator.errorList, function () { + $("<li />").html(this.message).appendTo(list); + }); + } + } + + function onSuccess(error) { // 'this' is the form element + var container = error.data("unobtrusiveContainer"), + replace = $.parseJSON(container.attr("data-valmsg-replace")); + + if (container) { + container.addClass("field-validation-valid").removeClass("field-validation-error"); + error.removeData("unobtrusiveContainer"); + + if (replace) { + container.empty(); + } + } + } + + function onReset(event) { // 'this' is the form element + var $form = $(this); + $form.data("validator").resetForm(); + $form.find(".validation-summary-errors") + .addClass("validation-summary-valid") + .removeClass("validation-summary-errors"); + $form.find(".field-validation-error") + .addClass("field-validation-valid") + .removeClass("field-validation-error") + .removeData("unobtrusiveContainer") + .find(">*") // If we were using valmsg-replace, get the underlying error + .removeData("unobtrusiveContainer"); + } + + function validationInfo(form) { + var $form = $(form), + result = $form.data(data_validation), + onResetProxy = $.proxy(onReset, form); + + if (!result) { + result = { + options: { // options structure passed to jQuery Validate's validate() method + errorClass: "input-validation-error", + errorElement: "span", + errorPlacement: $.proxy(onError, form), + invalidHandler: $.proxy(onErrors, form), + messages: {}, + rules: {}, + success: $.proxy(onSuccess, form) + }, + attachValidation: function () { + $form + .unbind("reset." + data_validation, onResetProxy) + .bind("reset." + data_validation, onResetProxy) + .validate(this.options); + }, + validate: function () { // a validation function that is called by unobtrusive Ajax + $form.validate(); + return $form.valid(); + } + }; + $form.data(data_validation, result); + } + + return result; + } + + $jQval.unobtrusive = { + adapters: [], + + parseElement: function (element, skipAttach) { + /// <summary> + /// Parses a single HTML element for unobtrusive validation attributes. + /// </summary> + /// <param name="element" domElement="true">The HTML element to be parsed.</param> + /// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the + /// validation to the form. If parsing just this single element, you should specify true. + /// If parsing several elements, you should specify false, and manually attach the validation + /// to the form when you are finished. The default is false.</param> + var $element = $(element), + form = $element.parents("form")[0], + valInfo, rules, messages; + + if (!form) { // Cannot do client-side validation without a form + return; + } + + valInfo = validationInfo(form); + valInfo.options.rules[element.name] = rules = {}; + valInfo.options.messages[element.name] = messages = {}; + + $.each(this.adapters, function () { + var prefix = "data-val-" + this.name, + message = $element.attr(prefix), + paramValues = {}; + + if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy) + prefix += "-"; + + $.each(this.params, function () { + paramValues[this] = $element.attr(prefix + this); + }); + + this.adapt({ + element: element, + form: form, + message: message, + params: paramValues, + rules: rules, + messages: messages + }); + } + }); + + $.extend(rules, { "__dummy__": true }); + + if (!skipAttach) { + valInfo.attachValidation(); + } + }, + + parse: function (selector) { + /// <summary> + /// Parses all the HTML elements in the specified selector. It looks for input elements decorated + /// with the [data-val=true] attribute value and enables validation according to the data-val-* + /// attribute values. + /// </summary> + /// <param name="selector" type="String">Any valid jQuery selector.</param> + var $forms = $(selector) + .parents("form") + .andSelf() + .add($(selector).find("form")) + .filter("form"); + + $(selector).find(":input[data-val=true]").each(function () { + $jQval.unobtrusive.parseElement(this, true); + }); + + $forms.each(function () { + var info = validationInfo(this); + if (info) { + info.attachValidation(); + } + }); + } + }; + + adapters = $jQval.unobtrusive.adapters; + + adapters.add = function (adapterName, params, fn) { + /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary> + /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used + /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param> + /// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will + /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and + /// mmmm is the parameter name).</param> + /// <param name="fn" type="Function">The function to call, which adapts the values from the HTML + /// attributes into jQuery Validate rules and/or messages.</param> + /// <returns type="jQuery.validator.unobtrusive.adapters" /> + if (!fn) { // Called with no params, just a function + fn = params; + params = []; + } + this.push({ name: adapterName, params: params, adapt: fn }); + return this; + }; + + adapters.addBool = function (adapterName, ruleName) { + /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where + /// the jQuery Validate validation rule has no parameter values.</summary> + /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used + /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param> + /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value + /// of adapterName will be used instead.</param> + /// <returns type="jQuery.validator.unobtrusive.adapters" /> + return this.add(adapterName, function (options) { + setValidationValues(options, ruleName || adapterName, true); + }); + }; + + adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) { + /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where + /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and + /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary> + /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used + /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param> + /// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only + /// have a minimum value.</param> + /// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only + /// have a maximum value.</param> + /// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you + /// have both a minimum and maximum value.</param> + /// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that + /// contains the minimum value. The default is "min".</param> + /// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that + /// contains the maximum value. The default is "max".</param> + /// <returns type="jQuery.validator.unobtrusive.adapters" /> + return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) { + var min = options.params.min, + max = options.params.max; + + if (min && max) { + setValidationValues(options, minMaxRuleName, [min, max]); + } + else if (min) { + setValidationValues(options, minRuleName, min); + } + else if (max) { + setValidationValues(options, maxRuleName, max); + } + }); + }; + + adapters.addSingleVal = function (adapterName, attribute, ruleName) { + /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where + /// the jQuery Validate validation rule has a single value.</summary> + /// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used + /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param> + /// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value. + /// The default is "val".</param> + /// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value + /// of adapterName will be used instead.</param> + /// <returns type="jQuery.validator.unobtrusive.adapters" /> + return this.add(adapterName, [attribute || "val"], function (options) { + setValidationValues(options, ruleName || adapterName, options.params[attribute]); + }); + }; + + $jQval.addMethod("__dummy__", function (value, element, params) { + return true; + }); + + $jQval.addMethod("regex", function (value, element, params) { + var match; + if (this.optional(element)) { + return true; + } + + match = new RegExp(params).exec(value); + return (match && (match.index === 0) && (match[0].length === value.length)); + }); + + $jQval.addMethod("nonalphamin", function (value, element, nonalphamin) { + var match; + if (nonalphamin) { + match = value.match(/\W/g); + match = match && match.length >= nonalphamin; + } + return match; + }); + + adapters.addSingleVal("accept", "exts").addSingleVal("regex", "pattern"); + adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url"); + adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range"); + adapters.add("equalto", ["other"], function (options) { + var prefix = getModelPrefix(options.element.name), + other = options.params.other, + fullOtherName = appendModelPrefix(other, prefix), + element = $(options.form).find(":input[name='" + escapeAttributeValue(fullOtherName) + "']")[0]; + + setValidationValues(options, "equalTo", element); + }); + adapters.add("required", function (options) { + // jQuery Validate equates "required" with "mandatory" for checkbox elements + if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") { + setValidationValues(options, "required", true); + } + }); + adapters.add("remote", ["url", "type", "additionalfields"], function (options) { + var value = { + url: options.params.url, + type: options.params.type || "GET", + data: {} + }, + prefix = getModelPrefix(options.element.name); + + $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) { + var paramName = appendModelPrefix(fieldName, prefix); + value.data[paramName] = function () { + return $(options.form).find(":input[name='" + escapeAttributeValue(paramName) + "']").val(); + }; + }); + + setValidationValues(options, "remote", value); + }); + adapters.add("password", ["min", "nonalphamin", "regex"], function (options) { + if (options.params.min) { + setValidationValues(options, "minlength", options.params.min); + } + if (options.params.nonalphamin) { + setValidationValues(options, "nonalphamin", options.params.nonalphamin); + } + if (options.params.regex) { + setValidationValues(options, "regex", options.params.regex); + } + }); + + $(function () { + $jQval.unobtrusive.parse(document); + }); +} (jQuery));
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.unobtrusive.min.js b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.unobtrusive.min.js new file mode 100644 index 0000000..e5e675b --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/jquery.validate.unobtrusive.min.js @@ -0,0 +1,5 @@ +/* +** Unobtrusive validation support library for jQuery and jQuery Validate +** Copyright (C) Microsoft Corporation. All rights reserved. +*/ +(function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,d){var b=a(this).find("[data-valmsg-for='"+f(d[0].name)+"']"),e=a.parseJSON(b.attr("data-valmsg-replace"))!==false;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(e){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("<li />").html(this.message).appendTo(b)})}}function k(c){var b=c.data("unobtrusiveContainer"),d=a.parseJSON(b.attr("data-valmsg-replace"));if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");c.removeData("unobtrusiveContainer");d&&b.empty()}}function n(){var b=a(this);b.data("validator").resetForm();b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(c){var b=a(c),d=b.data(e),f=a.proxy(n,c);if(!d){d={options:{errorClass:"input-validation-error",errorElement:"span",errorPlacement:a.proxy(m,c),invalidHandler:a.proxy(l,c),messages:{},rules:{},success:a.proxy(k,c)},attachValidation:function(){b.unbind("reset."+e,f).bind("reset."+e,f).validate(this.options)},validate:function(){b.validate();return b.valid()}};b.data(e,d)}return d}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(b){var c=a(b).parents("form").andSelf().add(a(b).find("form")).filter("form");a(b).find(":input[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});c.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});b.addSingleVal("accept","exts").addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){return a(b.form).find(":input[name='"+f(c)+"']").val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery);
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Scripts/knockout-2.1.0.debug.js b/samples/OAuth2ProtectedWebApi/Scripts/knockout-2.1.0.debug.js new file mode 100644 index 0000000..79882ce --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/knockout-2.1.0.debug.js @@ -0,0 +1,3443 @@ +// Knockout JavaScript library v2.1.0 +// (c) Steven Sanderson - http://knockoutjs.com/ +// License: MIT (http://www.opensource.org/licenses/mit-license.php) + +(function(window,document,navigator,undefined){ +var DEBUG=true; +!function(factory) { + // Support three module loading scenarios + if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') { + // [1] CommonJS/Node.js + var target = module['exports'] || exports; // module.exports is for Node.js + factory(target); + } else if (typeof define === 'function' && define['amd']) { + // [2] AMD anonymous module + define(['exports'], factory); + } else { + // [3] No module loader (plain <script> tag) - put directly in global namespace + factory(window['ko'] = {}); + } +}(function(koExports){ +// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler). +// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable. +var ko = typeof koExports !== 'undefined' ? koExports : {}; +// Google Closure Compiler helpers (used only to make the minified file smaller) +ko.exportSymbol = function(koPath, object) { + var tokens = koPath.split("."); + + // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable) + // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko) + var target = ko; + + for (var i = 0; i < tokens.length - 1; i++) + target = target[tokens[i]]; + target[tokens[tokens.length - 1]] = object; +}; +ko.exportProperty = function(owner, publicName, object) { + owner[publicName] = object; +}; +ko.version = "2.1.0"; + +ko.exportSymbol('version', ko.version); +ko.utils = new (function () { + var stringTrimRegex = /^(\s|\u00A0)+|(\s|\u00A0)+$/g; + + // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup) + var knownEvents = {}, knownEventTypesByEventName = {}; + var keyEventTypeName = /Firefox\/2/i.test(navigator.userAgent) ? 'KeyboardEvent' : 'UIEvents'; + knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress']; + knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave']; + for (var eventType in knownEvents) { + var knownEventsForType = knownEvents[eventType]; + if (knownEventsForType.length) { + for (var i = 0, j = knownEventsForType.length; i < j; i++) + knownEventTypesByEventName[knownEventsForType[i]] = eventType; + } + } + var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406 + + // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness) + var ieVersion = (function() { + var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i'); + + // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment + while ( + div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->', + iElems[0] + ); + return version > 4 ? version : undefined; + }()); + var isIe6 = ieVersion === 6, + isIe7 = ieVersion === 7; + + function isClickOnCheckableElement(element, eventType) { + if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false; + if (eventType.toLowerCase() != "click") return false; + var inputType = element.type; + return (inputType == "checkbox") || (inputType == "radio"); + } + + return { + fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/], + + arrayForEach: function (array, action) { + for (var i = 0, j = array.length; i < j; i++) + action(array[i]); + }, + + arrayIndexOf: function (array, item) { + if (typeof Array.prototype.indexOf == "function") + return Array.prototype.indexOf.call(array, item); + for (var i = 0, j = array.length; i < j; i++) + if (array[i] === item) + return i; + return -1; + }, + + arrayFirst: function (array, predicate, predicateOwner) { + for (var i = 0, j = array.length; i < j; i++) + if (predicate.call(predicateOwner, array[i])) + return array[i]; + return null; + }, + + arrayRemoveItem: function (array, itemToRemove) { + var index = ko.utils.arrayIndexOf(array, itemToRemove); + if (index >= 0) + array.splice(index, 1); + }, + + arrayGetDistinctValues: function (array) { + array = array || []; + var result = []; + for (var i = 0, j = array.length; i < j; i++) { + if (ko.utils.arrayIndexOf(result, array[i]) < 0) + result.push(array[i]); + } + return result; + }, + + arrayMap: function (array, mapping) { + array = array || []; + var result = []; + for (var i = 0, j = array.length; i < j; i++) + result.push(mapping(array[i])); + return result; + }, + + arrayFilter: function (array, predicate) { + array = array || []; + var result = []; + for (var i = 0, j = array.length; i < j; i++) + if (predicate(array[i])) + result.push(array[i]); + return result; + }, + + arrayPushAll: function (array, valuesToPush) { + if (valuesToPush instanceof Array) + array.push.apply(array, valuesToPush); + else + for (var i = 0, j = valuesToPush.length; i < j; i++) + array.push(valuesToPush[i]); + return array; + }, + + extend: function (target, source) { + if (source) { + for(var prop in source) { + if(source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + } + return target; + }, + + emptyDomNode: function (domNode) { + while (domNode.firstChild) { + ko.removeNode(domNode.firstChild); + } + }, + + moveCleanedNodesToContainerElement: function(nodes) { + // Ensure it's a real array, as we're about to reparent the nodes and + // we don't want the underlying collection to change while we're doing that. + var nodesArray = ko.utils.makeArray(nodes); + + var container = document.createElement('div'); + for (var i = 0, j = nodesArray.length; i < j; i++) { + ko.cleanNode(nodesArray[i]); + container.appendChild(nodesArray[i]); + } + return container; + }, + + setDomNodeChildren: function (domNode, childNodes) { + ko.utils.emptyDomNode(domNode); + if (childNodes) { + for (var i = 0, j = childNodes.length; i < j; i++) + domNode.appendChild(childNodes[i]); + } + }, + + replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) { + var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray; + if (nodesToReplaceArray.length > 0) { + var insertionPoint = nodesToReplaceArray[0]; + var parent = insertionPoint.parentNode; + for (var i = 0, j = newNodesArray.length; i < j; i++) + parent.insertBefore(newNodesArray[i], insertionPoint); + for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) { + ko.removeNode(nodesToReplaceArray[i]); + } + } + }, + + setOptionNodeSelectionState: function (optionNode, isSelected) { + // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser. + if (navigator.userAgent.indexOf("MSIE 6") >= 0) + optionNode.setAttribute("selected", isSelected); + else + optionNode.selected = isSelected; + }, + + stringTrim: function (string) { + return (string || "").replace(stringTrimRegex, ""); + }, + + stringTokenize: function (string, delimiter) { + var result = []; + var tokens = (string || "").split(delimiter); + for (var i = 0, j = tokens.length; i < j; i++) { + var trimmed = ko.utils.stringTrim(tokens[i]); + if (trimmed !== "") + result.push(trimmed); + } + return result; + }, + + stringStartsWith: function (string, startsWith) { + string = string || ""; + if (startsWith.length > string.length) + return false; + return string.substring(0, startsWith.length) === startsWith; + }, + + buildEvalWithinScopeFunction: function (expression, scopeLevels) { + // Build the source for a function that evaluates "expression" + // For each scope variable, add an extra level of "with" nesting + // Example result: with(sc[1]) { with(sc[0]) { return (expression) } } + var functionBody = "return (" + expression + ")"; + for (var i = 0; i < scopeLevels; i++) { + functionBody = "with(sc[" + i + "]) { " + functionBody + " } "; + } + return new Function("sc", functionBody); + }, + + domNodeIsContainedBy: function (node, containedByNode) { + if (containedByNode.compareDocumentPosition) + return (containedByNode.compareDocumentPosition(node) & 16) == 16; + while (node != null) { + if (node == containedByNode) + return true; + node = node.parentNode; + } + return false; + }, + + domNodeIsAttachedToDocument: function (node) { + return ko.utils.domNodeIsContainedBy(node, node.ownerDocument); + }, + + tagNameLower: function(element) { + // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case. + // Possible future optimization: If we know it's an element from an XHTML document (not HTML), + // we don't need to do the .toLowerCase() as it will always be lower case anyway. + return element && element.tagName && element.tagName.toLowerCase(); + }, + + registerEventHandler: function (element, eventType, handler) { + var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType]; + if (!mustUseAttachEvent && typeof jQuery != "undefined") { + if (isClickOnCheckableElement(element, eventType)) { + // For click events on checkboxes, jQuery interferes with the event handling in an awkward way: + // it toggles the element checked state *after* the click event handlers run, whereas native + // click events toggle the checked state *before* the event handler. + // Fix this by intecepting the handler and applying the correct checkedness before it runs. + var originalHandler = handler; + handler = function(event, eventData) { + var jQuerySuppliedCheckedState = this.checked; + if (eventData) + this.checked = eventData.checkedStateBeforeEvent !== true; + originalHandler.call(this, event); + this.checked = jQuerySuppliedCheckedState; // Restore the state jQuery applied + }; + } + jQuery(element)['bind'](eventType, handler); + } else if (!mustUseAttachEvent && typeof element.addEventListener == "function") + element.addEventListener(eventType, handler, false); + else if (typeof element.attachEvent != "undefined") + element.attachEvent("on" + eventType, function (event) { + handler.call(element, event); + }); + else + throw new Error("Browser doesn't support addEventListener or attachEvent"); + }, + + triggerEvent: function (element, eventType) { + if (!(element && element.nodeType)) + throw new Error("element must be a DOM node when calling triggerEvent"); + + if (typeof jQuery != "undefined") { + var eventData = []; + if (isClickOnCheckableElement(element, eventType)) { + // Work around the jQuery "click events on checkboxes" issue described above by storing the original checked state before triggering the handler + eventData.push({ checkedStateBeforeEvent: element.checked }); + } + jQuery(element)['trigger'](eventType, eventData); + } else if (typeof document.createEvent == "function") { + if (typeof element.dispatchEvent == "function") { + var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents"; + var event = document.createEvent(eventCategory); + event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element); + element.dispatchEvent(event); + } + else + throw new Error("The supplied element doesn't support dispatchEvent"); + } else if (typeof element.fireEvent != "undefined") { + // Unlike other browsers, IE doesn't change the checked state of checkboxes/radiobuttons when you trigger their "click" event + // so to make it consistent, we'll do it manually here + if (isClickOnCheckableElement(element, eventType)) + element.checked = element.checked !== true; + element.fireEvent("on" + eventType); + } + else + throw new Error("Browser doesn't support triggering events"); + }, + + unwrapObservable: function (value) { + return ko.isObservable(value) ? value() : value; + }, + + toggleDomNodeCssClass: function (node, className, shouldHaveClass) { + var currentClassNames = (node.className || "").split(/\s+/); + var hasClass = ko.utils.arrayIndexOf(currentClassNames, className) >= 0; + + if (shouldHaveClass && !hasClass) { + node.className += (currentClassNames[0] ? " " : "") + className; + } else if (hasClass && !shouldHaveClass) { + var newClassName = ""; + for (var i = 0; i < currentClassNames.length; i++) + if (currentClassNames[i] != className) + newClassName += currentClassNames[i] + " "; + node.className = ko.utils.stringTrim(newClassName); + } + }, + + setTextContent: function(element, textContent) { + var value = ko.utils.unwrapObservable(textContent); + if ((value === null) || (value === undefined)) + value = ""; + + 'innerText' in element ? element.innerText = value + : element.textContent = value; + + if (ieVersion >= 9) { + // Believe it or not, this actually fixes an IE9 rendering bug + // (See https://github.com/SteveSanderson/knockout/issues/209) + element.style.display = element.style.display; + } + }, + + ensureSelectElementIsRenderedCorrectly: function(selectElement) { + // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width. + // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option) + if (ieVersion >= 9) { + var originalWidth = selectElement.style.width; + selectElement.style.width = 0; + selectElement.style.width = originalWidth; + } + }, + + range: function (min, max) { + min = ko.utils.unwrapObservable(min); + max = ko.utils.unwrapObservable(max); + var result = []; + for (var i = min; i <= max; i++) + result.push(i); + return result; + }, + + makeArray: function(arrayLikeObject) { + var result = []; + for (var i = 0, j = arrayLikeObject.length; i < j; i++) { + result.push(arrayLikeObject[i]); + }; + return result; + }, + + isIe6 : isIe6, + isIe7 : isIe7, + ieVersion : ieVersion, + + getFormFields: function(form, fieldName) { + var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea"))); + var isMatchingField = (typeof fieldName == 'string') + ? function(field) { return field.name === fieldName } + : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate + var matches = []; + for (var i = fields.length - 1; i >= 0; i--) { + if (isMatchingField(fields[i])) + matches.push(fields[i]); + }; + return matches; + }, + + parseJson: function (jsonString) { + if (typeof jsonString == "string") { + jsonString = ko.utils.stringTrim(jsonString); + if (jsonString) { + if (window.JSON && window.JSON.parse) // Use native parsing where available + return window.JSON.parse(jsonString); + return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers + } + } + return null; + }, + + stringifyJson: function (data, replacer, space) { // replacer and space are optional + if ((typeof JSON == "undefined") || (typeof JSON.stringify == "undefined")) + throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js"); + return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space); + }, + + postJson: function (urlOrForm, data, options) { + options = options || {}; + var params = options['params'] || {}; + var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost; + var url = urlOrForm; + + // If we were given a form, use its 'action' URL and pick out any requested field values + if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) { + var originalForm = urlOrForm; + url = originalForm.action; + for (var i = includeFields.length - 1; i >= 0; i--) { + var fields = ko.utils.getFormFields(originalForm, includeFields[i]); + for (var j = fields.length - 1; j >= 0; j--) + params[fields[j].name] = fields[j].value; + } + } + + data = ko.utils.unwrapObservable(data); + var form = document.createElement("form"); + form.style.display = "none"; + form.action = url; + form.method = "post"; + for (var key in data) { + var input = document.createElement("input"); + input.name = key; + input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key])); + form.appendChild(input); + } + for (var key in params) { + var input = document.createElement("input"); + input.name = key; + input.value = params[key]; + form.appendChild(input); + } + document.body.appendChild(form); + options['submitter'] ? options['submitter'](form) : form.submit(); + setTimeout(function () { form.parentNode.removeChild(form); }, 0); + } + } +})(); + +ko.exportSymbol('utils', ko.utils); +ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach); +ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst); +ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter); +ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues); +ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf); +ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap); +ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll); +ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem); +ko.exportSymbol('utils.extend', ko.utils.extend); +ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost); +ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields); +ko.exportSymbol('utils.postJson', ko.utils.postJson); +ko.exportSymbol('utils.parseJson', ko.utils.parseJson); +ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler); +ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson); +ko.exportSymbol('utils.range', ko.utils.range); +ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass); +ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent); +ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable); + +if (!Function.prototype['bind']) { + // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf) + // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js + Function.prototype['bind'] = function (object) { + var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift(); + return function () { + return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments))); + }; + }; +} + +ko.utils.domData = new (function () { + var uniqueId = 0; + var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime(); + var dataStore = {}; + return { + get: function (node, key) { + var allDataForNode = ko.utils.domData.getAll(node, false); + return allDataForNode === undefined ? undefined : allDataForNode[key]; + }, + set: function (node, key, value) { + if (value === undefined) { + // Make sure we don't actually create a new domData key if we are actually deleting a value + if (ko.utils.domData.getAll(node, false) === undefined) + return; + } + var allDataForNode = ko.utils.domData.getAll(node, true); + allDataForNode[key] = value; + }, + getAll: function (node, createIfNotFound) { + var dataStoreKey = node[dataStoreKeyExpandoPropertyName]; + var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null"); + if (!hasExistingDataStore) { + if (!createIfNotFound) + return undefined; + dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++; + dataStore[dataStoreKey] = {}; + } + return dataStore[dataStoreKey]; + }, + clear: function (node) { + var dataStoreKey = node[dataStoreKeyExpandoPropertyName]; + if (dataStoreKey) { + delete dataStore[dataStoreKey]; + node[dataStoreKeyExpandoPropertyName] = null; + } + } + } +})(); + +ko.exportSymbol('utils.domData', ko.utils.domData); +ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully + +ko.utils.domNodeDisposal = new (function () { + var domDataKey = "__ko_domNodeDisposal__" + (new Date).getTime(); + var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document + var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document + + function getDisposeCallbacksCollection(node, createIfNotFound) { + var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey); + if ((allDisposeCallbacks === undefined) && createIfNotFound) { + allDisposeCallbacks = []; + ko.utils.domData.set(node, domDataKey, allDisposeCallbacks); + } + return allDisposeCallbacks; + } + function destroyCallbacksCollection(node) { + ko.utils.domData.set(node, domDataKey, undefined); + } + + function cleanSingleNode(node) { + // Run all the dispose callbacks + var callbacks = getDisposeCallbacksCollection(node, false); + if (callbacks) { + callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves) + for (var i = 0; i < callbacks.length; i++) + callbacks[i](node); + } + + // Also erase the DOM data + ko.utils.domData.clear(node); + + // Special support for jQuery here because it's so commonly used. + // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData + // so notify it to tear down any resources associated with the node & descendants here. + if ((typeof jQuery == "function") && (typeof jQuery['cleanData'] == "function")) + jQuery['cleanData']([node]); + + // Also clear any immediate-child comment nodes, as these wouldn't have been found by + // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements) + if (cleanableNodeTypesWithDescendants[node.nodeType]) + cleanImmediateCommentTypeChildren(node); + } + + function cleanImmediateCommentTypeChildren(nodeWithChildren) { + var child, nextChild = nodeWithChildren.firstChild; + while (child = nextChild) { + nextChild = child.nextSibling; + if (child.nodeType === 8) + cleanSingleNode(child); + } + } + + return { + addDisposeCallback : function(node, callback) { + if (typeof callback != "function") + throw new Error("Callback must be a function"); + getDisposeCallbacksCollection(node, true).push(callback); + }, + + removeDisposeCallback : function(node, callback) { + var callbacksCollection = getDisposeCallbacksCollection(node, false); + if (callbacksCollection) { + ko.utils.arrayRemoveItem(callbacksCollection, callback); + if (callbacksCollection.length == 0) + destroyCallbacksCollection(node); + } + }, + + cleanNode : function(node) { + // First clean this node, where applicable + if (cleanableNodeTypes[node.nodeType]) { + cleanSingleNode(node); + + // ... then its descendants, where applicable + if (cleanableNodeTypesWithDescendants[node.nodeType]) { + // Clone the descendants list in case it changes during iteration + var descendants = []; + ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*")); + for (var i = 0, j = descendants.length; i < j; i++) + cleanSingleNode(descendants[i]); + } + } + }, + + removeNode : function(node) { + ko.cleanNode(node); + if (node.parentNode) + node.parentNode.removeChild(node); + } + } +})(); +ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience +ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience +ko.exportSymbol('cleanNode', ko.cleanNode); +ko.exportSymbol('removeNode', ko.removeNode); +ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal); +ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback); +ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback); +(function () { + var leadingCommentRegex = /^(\s*)<!--(.*?)-->/; + + function simpleHtmlParse(html) { + // Based on jQuery's "clean" function, but only accounting for table-related elements. + // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly + + // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of + // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>" + // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node + // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present. + + // Trim whitespace, otherwise indexOf won't work as expected + var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div"); + + // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column + var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] || + !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] || + (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] || + /* anything else */ [0, "", ""]; + + // Go to html and back, then peel off extra wrappers + // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness. + var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>"; + if (typeof window['innerShiv'] == "function") { + div.appendChild(window['innerShiv'](markup)); + } else { + div.innerHTML = markup; + } + + // Move to the right depth + while (wrap[0]--) + div = div.lastChild; + + return ko.utils.makeArray(div.lastChild.childNodes); + } + + function jQueryHtmlParse(html) { + var elems = jQuery['clean']([html]); + + // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment. + // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time. + // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment. + if (elems && elems[0]) { + // Find the top-most parent element that's a direct child of a document fragment + var elem = elems[0]; + while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */) + elem = elem.parentNode; + // ... then detach it + if (elem.parentNode) + elem.parentNode.removeChild(elem); + } + + return elems; + } + + ko.utils.parseHtmlFragment = function(html) { + return typeof jQuery != 'undefined' ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible + : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases. + }; + + ko.utils.setHtml = function(node, html) { + ko.utils.emptyDomNode(node); + + if ((html !== null) && (html !== undefined)) { + if (typeof html != 'string') + html = html.toString(); + + // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments, + // for example <tr> elements which are not normally allowed to exist on their own. + // If you've referenced jQuery we'll use that rather than duplicating its code. + if (typeof jQuery != 'undefined') { + jQuery(node)['html'](html); + } else { + // ... otherwise, use KO's own parsing logic. + var parsedNodes = ko.utils.parseHtmlFragment(html); + for (var i = 0; i < parsedNodes.length; i++) + node.appendChild(parsedNodes[i]); + } + } + }; +})(); + +ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment); +ko.exportSymbol('utils.setHtml', ko.utils.setHtml); + +ko.memoization = (function () { + var memos = {}; + + function randomMax8HexChars() { + return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1); + } + function generateRandomId() { + return randomMax8HexChars() + randomMax8HexChars(); + } + function findMemoNodes(rootNode, appendToArray) { + if (!rootNode) + return; + if (rootNode.nodeType == 8) { + var memoId = ko.memoization.parseMemoText(rootNode.nodeValue); + if (memoId != null) + appendToArray.push({ domNode: rootNode, memoId: memoId }); + } else if (rootNode.nodeType == 1) { + for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++) + findMemoNodes(childNodes[i], appendToArray); + } + } + + return { + memoize: function (callback) { + if (typeof callback != "function") + throw new Error("You can only pass a function to ko.memoization.memoize()"); + var memoId = generateRandomId(); + memos[memoId] = callback; + return "<!--[ko_memo:" + memoId + "]-->"; + }, + + unmemoize: function (memoId, callbackParams) { + var callback = memos[memoId]; + if (callback === undefined) + throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized."); + try { + callback.apply(null, callbackParams || []); + return true; + } + finally { delete memos[memoId]; } + }, + + unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) { + var memos = []; + findMemoNodes(domNode, memos); + for (var i = 0, j = memos.length; i < j; i++) { + var node = memos[i].domNode; + var combinedParams = [node]; + if (extraCallbackParamsArray) + ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray); + ko.memoization.unmemoize(memos[i].memoId, combinedParams); + node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again + if (node.parentNode) + node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again) + } + }, + + parseMemoText: function (memoText) { + var match = memoText.match(/^\[ko_memo\:(.*?)\]$/); + return match ? match[1] : null; + } + }; +})(); + +ko.exportSymbol('memoization', ko.memoization); +ko.exportSymbol('memoization.memoize', ko.memoization.memoize); +ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize); +ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText); +ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants); +ko.extenders = { + 'throttle': function(target, timeout) { + // Throttling means two things: + + // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies + // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate + target['throttleEvaluation'] = timeout; + + // (2) For writable targets (observables, or writable dependent observables), we throttle *writes* + // so the target cannot change value synchronously or faster than a certain rate + var writeTimeoutInstance = null; + return ko.dependentObservable({ + 'read': target, + 'write': function(value) { + clearTimeout(writeTimeoutInstance); + writeTimeoutInstance = setTimeout(function() { + target(value); + }, timeout); + } + }); + }, + + 'notify': function(target, notifyWhen) { + target["equalityComparer"] = notifyWhen == "always" + ? function() { return false } // Treat all values as not equal + : ko.observable["fn"]["equalityComparer"]; + return target; + } +}; + +function applyExtenders(requestedExtenders) { + var target = this; + if (requestedExtenders) { + for (var key in requestedExtenders) { + var extenderHandler = ko.extenders[key]; + if (typeof extenderHandler == 'function') { + target = extenderHandler(target, requestedExtenders[key]); + } + } + } + return target; +} + +ko.exportSymbol('extenders', ko.extenders); + +ko.subscription = function (target, callback, disposeCallback) { + this.target = target; + this.callback = callback; + this.disposeCallback = disposeCallback; + ko.exportProperty(this, 'dispose', this.dispose); +}; +ko.subscription.prototype.dispose = function () { + this.isDisposed = true; + this.disposeCallback(); +}; + +ko.subscribable = function () { + this._subscriptions = {}; + + ko.utils.extend(this, ko.subscribable['fn']); + ko.exportProperty(this, 'subscribe', this.subscribe); + ko.exportProperty(this, 'extend', this.extend); + ko.exportProperty(this, 'getSubscriptionsCount', this.getSubscriptionsCount); +} + +var defaultEvent = "change"; + +ko.subscribable['fn'] = { + subscribe: function (callback, callbackTarget, event) { + event = event || defaultEvent; + var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback; + + var subscription = new ko.subscription(this, boundCallback, function () { + ko.utils.arrayRemoveItem(this._subscriptions[event], subscription); + }.bind(this)); + + if (!this._subscriptions[event]) + this._subscriptions[event] = []; + this._subscriptions[event].push(subscription); + return subscription; + }, + + "notifySubscribers": function (valueToNotify, event) { + event = event || defaultEvent; + if (this._subscriptions[event]) { + ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) { + // In case a subscription was disposed during the arrayForEach cycle, check + // for isDisposed on each subscription before invoking its callback + if (subscription && (subscription.isDisposed !== true)) + subscription.callback(valueToNotify); + }); + } + }, + + getSubscriptionsCount: function () { + var total = 0; + for (var eventName in this._subscriptions) { + if (this._subscriptions.hasOwnProperty(eventName)) + total += this._subscriptions[eventName].length; + } + return total; + }, + + extend: applyExtenders +}; + + +ko.isSubscribable = function (instance) { + return typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function"; +}; + +ko.exportSymbol('subscribable', ko.subscribable); +ko.exportSymbol('isSubscribable', ko.isSubscribable); + +ko.dependencyDetection = (function () { + var _frames = []; + + return { + begin: function (callback) { + _frames.push({ callback: callback, distinctDependencies:[] }); + }, + + end: function () { + _frames.pop(); + }, + + registerDependency: function (subscribable) { + if (!ko.isSubscribable(subscribable)) + throw new Error("Only subscribable things can act as dependencies"); + if (_frames.length > 0) { + var topFrame = _frames[_frames.length - 1]; + if (ko.utils.arrayIndexOf(topFrame.distinctDependencies, subscribable) >= 0) + return; + topFrame.distinctDependencies.push(subscribable); + topFrame.callback(subscribable); + } + } + }; +})(); +var primitiveTypes = { 'undefined':true, 'boolean':true, 'number':true, 'string':true }; + +ko.observable = function (initialValue) { + var _latestValue = initialValue; + + function observable() { + if (arguments.length > 0) { + // Write + + // Ignore writes if the value hasn't changed + if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) { + observable.valueWillMutate(); + _latestValue = arguments[0]; + if (DEBUG) observable._latestValue = _latestValue; + observable.valueHasMutated(); + } + return this; // Permits chained assignments + } + else { + // Read + ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation + return _latestValue; + } + } + if (DEBUG) observable._latestValue = _latestValue; + ko.subscribable.call(observable); + observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); } + observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); } + ko.utils.extend(observable, ko.observable['fn']); + + ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated); + ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate); + + return observable; +} + +ko.observable['fn'] = { + "equalityComparer": function valuesArePrimitiveAndEqual(a, b) { + var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes); + return oldValueIsPrimitive ? (a === b) : false; + } +}; + +var protoProperty = ko.observable.protoProperty = "__ko_proto__"; +ko.observable['fn'][protoProperty] = ko.observable; + +ko.hasPrototype = function(instance, prototype) { + if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false; + if (instance[protoProperty] === prototype) return true; + return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain +}; + +ko.isObservable = function (instance) { + return ko.hasPrototype(instance, ko.observable); +} +ko.isWriteableObservable = function (instance) { + // Observable + if ((typeof instance == "function") && instance[protoProperty] === ko.observable) + return true; + // Writeable dependent observable + if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction)) + return true; + // Anything else + return false; +} + + +ko.exportSymbol('observable', ko.observable); +ko.exportSymbol('isObservable', ko.isObservable); +ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable); +ko.observableArray = function (initialValues) { + if (arguments.length == 0) { + // Zero-parameter constructor initializes to empty array + initialValues = []; + } + if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues)) + throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined."); + + var result = ko.observable(initialValues); + ko.utils.extend(result, ko.observableArray['fn']); + return result; +} + +ko.observableArray['fn'] = { + 'remove': function (valueOrPredicate) { + var underlyingArray = this(); + var removedValues = []; + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; }; + for (var i = 0; i < underlyingArray.length; i++) { + var value = underlyingArray[i]; + if (predicate(value)) { + if (removedValues.length === 0) { + this.valueWillMutate(); + } + removedValues.push(value); + underlyingArray.splice(i, 1); + i--; + } + } + if (removedValues.length) { + this.valueHasMutated(); + } + return removedValues; + }, + + 'removeAll': function (arrayOfValues) { + // If you passed zero args, we remove everything + if (arrayOfValues === undefined) { + var underlyingArray = this(); + var allValues = underlyingArray.slice(0); + this.valueWillMutate(); + underlyingArray.splice(0, underlyingArray.length); + this.valueHasMutated(); + return allValues; + } + // If you passed an arg, we interpret it as an array of entries to remove + if (!arrayOfValues) + return []; + return this['remove'](function (value) { + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0; + }); + }, + + 'destroy': function (valueOrPredicate) { + var underlyingArray = this(); + var predicate = typeof valueOrPredicate == "function" ? valueOrPredicate : function (value) { return value === valueOrPredicate; }; + this.valueWillMutate(); + for (var i = underlyingArray.length - 1; i >= 0; i--) { + var value = underlyingArray[i]; + if (predicate(value)) + underlyingArray[i]["_destroy"] = true; + } + this.valueHasMutated(); + }, + + 'destroyAll': function (arrayOfValues) { + // If you passed zero args, we destroy everything + if (arrayOfValues === undefined) + return this['destroy'](function() { return true }); + + // If you passed an arg, we interpret it as an array of entries to destroy + if (!arrayOfValues) + return []; + return this['destroy'](function (value) { + return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0; + }); + }, + + 'indexOf': function (item) { + var underlyingArray = this(); + return ko.utils.arrayIndexOf(underlyingArray, item); + }, + + 'replace': function(oldItem, newItem) { + var index = this['indexOf'](oldItem); + if (index >= 0) { + this.valueWillMutate(); + this()[index] = newItem; + this.valueHasMutated(); + } + } +} + +// Populate ko.observableArray.fn with read/write functions from native arrays +ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) { + ko.observableArray['fn'][methodName] = function () { + var underlyingArray = this(); + this.valueWillMutate(); + var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments); + this.valueHasMutated(); + return methodCallResult; + }; +}); + +// Populate ko.observableArray.fn with read-only functions from native arrays +ko.utils.arrayForEach(["slice"], function (methodName) { + ko.observableArray['fn'][methodName] = function () { + var underlyingArray = this(); + return underlyingArray[methodName].apply(underlyingArray, arguments); + }; +}); + +ko.exportSymbol('observableArray', ko.observableArray); +ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) { + var _latestValue, + _hasBeenEvaluated = false, + _isBeingEvaluated = false, + readFunction = evaluatorFunctionOrOptions; + + if (readFunction && typeof readFunction == "object") { + // Single-parameter syntax - everything is on this "options" param + options = readFunction; + readFunction = options["read"]; + } else { + // Multi-parameter syntax - construct the options according to the params passed + options = options || {}; + if (!readFunction) + readFunction = options["read"]; + } + // By here, "options" is always non-null + if (typeof readFunction != "function") + throw new Error("Pass a function that returns the value of the ko.computed"); + + var writeFunction = options["write"]; + if (!evaluatorFunctionTarget) + evaluatorFunctionTarget = options["owner"]; + + var _subscriptionsToDependencies = []; + function disposeAllSubscriptionsToDependencies() { + ko.utils.arrayForEach(_subscriptionsToDependencies, function (subscription) { + subscription.dispose(); + }); + _subscriptionsToDependencies = []; + } + var dispose = disposeAllSubscriptionsToDependencies; + + // Build "disposeWhenNodeIsRemoved" and "disposeWhenNodeIsRemovedCallback" option values + // (Note: "disposeWhenNodeIsRemoved" option both proactively disposes as soon as the node is removed using ko.removeNode(), + // plus adds a "disposeWhen" callback that, on each evaluation, disposes if the node was removed by some other means.) + var disposeWhenNodeIsRemoved = (typeof options["disposeWhenNodeIsRemoved"] == "object") ? options["disposeWhenNodeIsRemoved"] : null; + var disposeWhen = options["disposeWhen"] || function() { return false; }; + if (disposeWhenNodeIsRemoved) { + dispose = function() { + ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, arguments.callee); + disposeAllSubscriptionsToDependencies(); + }; + ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose); + var existingDisposeWhenFunction = disposeWhen; + disposeWhen = function () { + return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || existingDisposeWhenFunction(); + } + } + + var evaluationTimeoutInstance = null; + function evaluatePossiblyAsync() { + var throttleEvaluationTimeout = dependentObservable['throttleEvaluation']; + if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) { + clearTimeout(evaluationTimeoutInstance); + evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout); + } else + evaluateImmediate(); + } + + function evaluateImmediate() { + if (_isBeingEvaluated) { + // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation. + // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost + // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing + // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387 + return; + } + + // Don't dispose on first evaluation, because the "disposeWhen" callback might + // e.g., dispose when the associated DOM element isn't in the doc, and it's not + // going to be in the doc until *after* the first evaluation + if (_hasBeenEvaluated && disposeWhen()) { + dispose(); + return; + } + + _isBeingEvaluated = true; + try { + // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal). + // Then, during evaluation, we cross off any that are in fact still being used. + var disposalCandidates = ko.utils.arrayMap(_subscriptionsToDependencies, function(item) {return item.target;}); + + ko.dependencyDetection.begin(function(subscribable) { + var inOld; + if ((inOld = ko.utils.arrayIndexOf(disposalCandidates, subscribable)) >= 0) + disposalCandidates[inOld] = undefined; // Don't want to dispose this subscription, as it's still being used + else + _subscriptionsToDependencies.push(subscribable.subscribe(evaluatePossiblyAsync)); // Brand new subscription - add it + }); + + var newValue = readFunction.call(evaluatorFunctionTarget); + + // For each subscription no longer being used, remove it from the active subscriptions list and dispose it + for (var i = disposalCandidates.length - 1; i >= 0; i--) { + if (disposalCandidates[i]) + _subscriptionsToDependencies.splice(i, 1)[0].dispose(); + } + _hasBeenEvaluated = true; + + dependentObservable["notifySubscribers"](_latestValue, "beforeChange"); + _latestValue = newValue; + if (DEBUG) dependentObservable._latestValue = _latestValue; + } finally { + ko.dependencyDetection.end(); + } + + dependentObservable["notifySubscribers"](_latestValue); + _isBeingEvaluated = false; + + } + + function dependentObservable() { + if (arguments.length > 0) { + set.apply(dependentObservable, arguments); + } else { + return get(); + } + } + + function set() { + if (typeof writeFunction === "function") { + // Writing a value + writeFunction.apply(evaluatorFunctionTarget, arguments); + } else { + throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters."); + } + } + + function get() { + // Reading the value + if (!_hasBeenEvaluated) + evaluateImmediate(); + ko.dependencyDetection.registerDependency(dependentObservable); + return _latestValue; + } + + dependentObservable.getDependenciesCount = function () { return _subscriptionsToDependencies.length; }; + dependentObservable.hasWriteFunction = typeof options["write"] === "function"; + dependentObservable.dispose = function () { dispose(); }; + + ko.subscribable.call(dependentObservable); + ko.utils.extend(dependentObservable, ko.dependentObservable['fn']); + + if (options['deferEvaluation'] !== true) + evaluateImmediate(); + + ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose); + ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount); + + return dependentObservable; +}; + +ko.isComputed = function(instance) { + return ko.hasPrototype(instance, ko.dependentObservable); +}; + +var protoProp = ko.observable.protoProperty; // == "__ko_proto__" +ko.dependentObservable[protoProp] = ko.observable; + +ko.dependentObservable['fn'] = {}; +ko.dependentObservable['fn'][protoProp] = ko.dependentObservable; + +ko.exportSymbol('dependentObservable', ko.dependentObservable); +ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable" +ko.exportSymbol('isComputed', ko.isComputed); + +(function() { + var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle) + + ko.toJS = function(rootObject) { + if (arguments.length == 0) + throw new Error("When calling ko.toJS, pass the object you want to convert."); + + // We just unwrap everything at every level in the object graph + return mapJsObjectGraph(rootObject, function(valueToMap) { + // Loop because an observable's value might in turn be another observable wrapper + for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++) + valueToMap = valueToMap(); + return valueToMap; + }); + }; + + ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional + var plainJavaScriptObject = ko.toJS(rootObject); + return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space); + }; + + function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) { + visitedObjects = visitedObjects || new objectLookup(); + + rootObject = mapInputCallback(rootObject); + var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)); + if (!canHaveProperties) + return rootObject; + + var outputProperties = rootObject instanceof Array ? [] : {}; + visitedObjects.save(rootObject, outputProperties); + + visitPropertiesOrArrayEntries(rootObject, function(indexer) { + var propertyValue = mapInputCallback(rootObject[indexer]); + + switch (typeof propertyValue) { + case "boolean": + case "number": + case "string": + case "function": + outputProperties[indexer] = propertyValue; + break; + case "object": + case "undefined": + var previouslyMappedValue = visitedObjects.get(propertyValue); + outputProperties[indexer] = (previouslyMappedValue !== undefined) + ? previouslyMappedValue + : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects); + break; + } + }); + + return outputProperties; + } + + function visitPropertiesOrArrayEntries(rootObject, visitorCallback) { + if (rootObject instanceof Array) { + for (var i = 0; i < rootObject.length; i++) + visitorCallback(i); + + // For arrays, also respect toJSON property for custom mappings (fixes #278) + if (typeof rootObject['toJSON'] == 'function') + visitorCallback('toJSON'); + } else { + for (var propertyName in rootObject) + visitorCallback(propertyName); + } + }; + + function objectLookup() { + var keys = []; + var values = []; + this.save = function(key, value) { + var existingIndex = ko.utils.arrayIndexOf(keys, key); + if (existingIndex >= 0) + values[existingIndex] = value; + else { + keys.push(key); + values.push(value); + } + }; + this.get = function(key) { + var existingIndex = ko.utils.arrayIndexOf(keys, key); + return (existingIndex >= 0) ? values[existingIndex] : undefined; + }; + }; +})(); + +ko.exportSymbol('toJS', ko.toJS); +ko.exportSymbol('toJSON', ko.toJSON); +(function () { + var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__'; + + // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values + // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values + // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns. + ko.selectExtensions = { + readValue : function(element) { + switch (ko.utils.tagNameLower(element)) { + case 'option': + if (element[hasDomDataExpandoProperty] === true) + return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey); + return element.getAttribute("value"); + case 'select': + return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined; + default: + return element.value; + } + }, + + writeValue: function(element, value) { + switch (ko.utils.tagNameLower(element)) { + case 'option': + switch(typeof value) { + case "string": + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined); + if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node + delete element[hasDomDataExpandoProperty]; + } + element.value = value; + break; + default: + // Store arbitrary object using DomData + ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value); + element[hasDomDataExpandoProperty] = true; + + // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value. + element.value = typeof value === "number" ? value : ""; + break; + } + break; + case 'select': + for (var i = element.options.length - 1; i >= 0; i--) { + if (ko.selectExtensions.readValue(element.options[i]) == value) { + element.selectedIndex = i; + break; + } + } + break; + default: + if ((value === null) || (value === undefined)) + value = ""; + element.value = value; + break; + } + } + }; +})(); + +ko.exportSymbol('selectExtensions', ko.selectExtensions); +ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue); +ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue); + +ko.jsonExpressionRewriting = (function () { + var restoreCapturedTokensRegex = /\@ko_token_(\d+)\@/g; + var javaScriptAssignmentTarget = /^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i; + var javaScriptReservedWords = ["true", "false"]; + + function restoreTokens(string, tokens) { + var prevValue = null; + while (string != prevValue) { // Keep restoring tokens until it no longer makes a difference (they may be nested) + prevValue = string; + string = string.replace(restoreCapturedTokensRegex, function (match, tokenIndex) { + return tokens[tokenIndex]; + }); + } + return string; + } + + function isWriteableValue(expression) { + if (ko.utils.arrayIndexOf(javaScriptReservedWords, ko.utils.stringTrim(expression).toLowerCase()) >= 0) + return false; + return expression.match(javaScriptAssignmentTarget) !== null; + } + + function ensureQuoted(key) { + var trimmedKey = ko.utils.stringTrim(key); + switch (trimmedKey.length && trimmedKey.charAt(0)) { + case "'": + case '"': + return key; + default: + return "'" + trimmedKey + "'"; + } + } + + return { + bindingRewriteValidators: [], + + parseObjectLiteral: function(objectLiteralString) { + // A full tokeniser+lexer would add too much weight to this library, so here's a simple parser + // that is sufficient just to split an object literal string into a set of top-level key-value pairs + + var str = ko.utils.stringTrim(objectLiteralString); + if (str.length < 3) + return []; + if (str.charAt(0) === "{")// Ignore any braces surrounding the whole object literal + str = str.substring(1, str.length - 1); + + // Pull out any string literals and regex literals + var tokens = []; + var tokenStart = null, tokenEndChar; + for (var position = 0; position < str.length; position++) { + var c = str.charAt(position); + if (tokenStart === null) { + switch (c) { + case '"': + case "'": + case "/": + tokenStart = position; + tokenEndChar = c; + break; + } + } else if ((c == tokenEndChar) && (str.charAt(position - 1) !== "\\")) { + var token = str.substring(tokenStart, position + 1); + tokens.push(token); + var replacement = "@ko_token_" + (tokens.length - 1) + "@"; + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1); + position -= (token.length - replacement.length); + tokenStart = null; + } + } + + // Next pull out balanced paren, brace, and bracket blocks + tokenStart = null; + tokenEndChar = null; + var tokenDepth = 0, tokenStartChar = null; + for (var position = 0; position < str.length; position++) { + var c = str.charAt(position); + if (tokenStart === null) { + switch (c) { + case "{": tokenStart = position; tokenStartChar = c; + tokenEndChar = "}"; + break; + case "(": tokenStart = position; tokenStartChar = c; + tokenEndChar = ")"; + break; + case "[": tokenStart = position; tokenStartChar = c; + tokenEndChar = "]"; + break; + } + } + + if (c === tokenStartChar) + tokenDepth++; + else if (c === tokenEndChar) { + tokenDepth--; + if (tokenDepth === 0) { + var token = str.substring(tokenStart, position + 1); + tokens.push(token); + var replacement = "@ko_token_" + (tokens.length - 1) + "@"; + str = str.substring(0, tokenStart) + replacement + str.substring(position + 1); + position -= (token.length - replacement.length); + tokenStart = null; + } + } + } + + // Now we can safely split on commas to get the key/value pairs + var result = []; + var keyValuePairs = str.split(","); + for (var i = 0, j = keyValuePairs.length; i < j; i++) { + var pair = keyValuePairs[i]; + var colonPos = pair.indexOf(":"); + if ((colonPos > 0) && (colonPos < pair.length - 1)) { + var key = pair.substring(0, colonPos); + var value = pair.substring(colonPos + 1); + result.push({ 'key': restoreTokens(key, tokens), 'value': restoreTokens(value, tokens) }); + } else { + result.push({ 'unknown': restoreTokens(pair, tokens) }); + } + } + return result; + }, + + insertPropertyAccessorsIntoJson: function (objectLiteralStringOrKeyValueArray) { + var keyValueArray = typeof objectLiteralStringOrKeyValueArray === "string" + ? ko.jsonExpressionRewriting.parseObjectLiteral(objectLiteralStringOrKeyValueArray) + : objectLiteralStringOrKeyValueArray; + var resultStrings = [], propertyAccessorResultStrings = []; + + var keyValueEntry; + for (var i = 0; keyValueEntry = keyValueArray[i]; i++) { + if (resultStrings.length > 0) + resultStrings.push(","); + + if (keyValueEntry['key']) { + var quotedKey = ensureQuoted(keyValueEntry['key']), val = keyValueEntry['value']; + resultStrings.push(quotedKey); + resultStrings.push(":"); + resultStrings.push(val); + + if (isWriteableValue(ko.utils.stringTrim(val))) { + if (propertyAccessorResultStrings.length > 0) + propertyAccessorResultStrings.push(", "); + propertyAccessorResultStrings.push(quotedKey + " : function(__ko_value) { " + val + " = __ko_value; }"); + } + } else if (keyValueEntry['unknown']) { + resultStrings.push(keyValueEntry['unknown']); + } + } + + var combinedResult = resultStrings.join(""); + if (propertyAccessorResultStrings.length > 0) { + var allPropertyAccessors = propertyAccessorResultStrings.join(""); + combinedResult = combinedResult + ", '_ko_property_writers' : { " + allPropertyAccessors + " } "; + } + + return combinedResult; + }, + + keyValueArrayContainsKey: function(keyValueArray, key) { + for (var i = 0; i < keyValueArray.length; i++) + if (ko.utils.stringTrim(keyValueArray[i]['key']) == key) + return true; + return false; + }, + + // Internal, private KO utility for updating model properties from within bindings + // property: If the property being updated is (or might be) an observable, pass it here + // If it turns out to be a writable observable, it will be written to directly + // allBindingsAccessor: All bindings in the current execution context. + // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable + // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus' + // value: The value to be written + // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if + // it is !== existing value on that writable observable + writeValueToProperty: function(property, allBindingsAccessor, key, value, checkIfDifferent) { + if (!property || !ko.isWriteableObservable(property)) { + var propWriters = allBindingsAccessor()['_ko_property_writers']; + if (propWriters && propWriters[key]) + propWriters[key](value); + } else if (!checkIfDifferent || property() !== value) { + property(value); + } + } + }; +})(); + +ko.exportSymbol('jsonExpressionRewriting', ko.jsonExpressionRewriting); +ko.exportSymbol('jsonExpressionRewriting.bindingRewriteValidators', ko.jsonExpressionRewriting.bindingRewriteValidators); +ko.exportSymbol('jsonExpressionRewriting.parseObjectLiteral', ko.jsonExpressionRewriting.parseObjectLiteral); +ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson); +(function() { + // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes + // may be used to represent hierarchy (in addition to the DOM's natural hierarchy). + // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state + // of that virtual hierarchy + // + // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->) + // without having to scatter special cases all over the binding and templating code. + + // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186) + // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property. + // So, use node.text where available, and node.nodeValue elsewhere + var commentNodesHaveTextProperty = document.createComment("test").text === "<!--test-->"; + + var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko\s+(.*\:.*)\s*-->$/ : /^\s*ko\s+(.*\:.*)\s*$/; + var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/; + var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true }; + + function isStartComment(node) { + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex); + } + + function isEndComment(node) { + return (node.nodeType == 8) && (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(endCommentRegex); + } + + function getVirtualChildren(startComment, allowUnbalanced) { + var currentNode = startComment; + var depth = 1; + var children = []; + while (currentNode = currentNode.nextSibling) { + if (isEndComment(currentNode)) { + depth--; + if (depth === 0) + return children; + } + + children.push(currentNode); + + if (isStartComment(currentNode)) + depth++; + } + if (!allowUnbalanced) + throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue); + return null; + } + + function getMatchingEndComment(startComment, allowUnbalanced) { + var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced); + if (allVirtualChildren) { + if (allVirtualChildren.length > 0) + return allVirtualChildren[allVirtualChildren.length - 1].nextSibling; + return startComment.nextSibling; + } else + return null; // Must have no matching end comment, and allowUnbalanced is true + } + + function getUnbalancedChildTags(node) { + // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span> + // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko --> + var childNode = node.firstChild, captureRemaining = null; + if (childNode) { + do { + if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes + captureRemaining.push(childNode); + else if (isStartComment(childNode)) { + var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true); + if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set + childNode = matchingEndComment; + else + captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point + } else if (isEndComment(childNode)) { + captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing + } + } while (childNode = childNode.nextSibling); + } + return captureRemaining; + } + + ko.virtualElements = { + allowedBindings: {}, + + childNodes: function(node) { + return isStartComment(node) ? getVirtualChildren(node) : node.childNodes; + }, + + emptyNode: function(node) { + if (!isStartComment(node)) + ko.utils.emptyDomNode(node); + else { + var virtualChildren = ko.virtualElements.childNodes(node); + for (var i = 0, j = virtualChildren.length; i < j; i++) + ko.removeNode(virtualChildren[i]); + } + }, + + setDomNodeChildren: function(node, childNodes) { + if (!isStartComment(node)) + ko.utils.setDomNodeChildren(node, childNodes); + else { + ko.virtualElements.emptyNode(node); + var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children + for (var i = 0, j = childNodes.length; i < j; i++) + endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode); + } + }, + + prepend: function(containerNode, nodeToPrepend) { + if (!isStartComment(containerNode)) { + if (containerNode.firstChild) + containerNode.insertBefore(nodeToPrepend, containerNode.firstChild); + else + containerNode.appendChild(nodeToPrepend); + } else { + // Start comments must always have a parent and at least one following sibling (the end comment) + containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling); + } + }, + + insertAfter: function(containerNode, nodeToInsert, insertAfterNode) { + if (!isStartComment(containerNode)) { + // Insert after insertion point + if (insertAfterNode.nextSibling) + containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling); + else + containerNode.appendChild(nodeToInsert); + } else { + // Children of start comments must always have a parent and at least one following sibling (the end comment) + containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling); + } + }, + + firstChild: function(node) { + if (!isStartComment(node)) + return node.firstChild; + if (!node.nextSibling || isEndComment(node.nextSibling)) + return null; + return node.nextSibling; + }, + + nextSibling: function(node) { + if (isStartComment(node)) + node = getMatchingEndComment(node); + if (node.nextSibling && isEndComment(node.nextSibling)) + return null; + return node.nextSibling; + }, + + virtualNodeBindingValue: function(node) { + var regexMatch = isStartComment(node); + return regexMatch ? regexMatch[1] : null; + }, + + normaliseVirtualElementDomStructure: function(elementVerified) { + // Workaround for https://github.com/SteveSanderson/knockout/issues/155 + // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes + // that are direct descendants of <ul> into the preceding <li>) + if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)]) + return; + + // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags + // must be intended to appear *after* that child, so move them there. + var childNode = elementVerified.firstChild; + if (childNode) { + do { + if (childNode.nodeType === 1) { + var unbalancedTags = getUnbalancedChildTags(childNode); + if (unbalancedTags) { + // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child + var nodeToInsertBefore = childNode.nextSibling; + for (var i = 0; i < unbalancedTags.length; i++) { + if (nodeToInsertBefore) + elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore); + else + elementVerified.appendChild(unbalancedTags[i]); + } + } + } + } while (childNode = childNode.nextSibling); + } + } + }; +})(); +ko.exportSymbol('virtualElements', ko.virtualElements); +ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings); +ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode); +//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified +ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter); +//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified +ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend); +ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren); +(function() { + var defaultBindingAttributeName = "data-bind"; + + ko.bindingProvider = function() { + this.bindingCache = {}; + }; + + ko.utils.extend(ko.bindingProvider.prototype, { + 'nodeHasBindings': function(node) { + switch (node.nodeType) { + case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element + case 8: return ko.virtualElements.virtualNodeBindingValue(node) != null; // Comment node + default: return false; + } + }, + + 'getBindings': function(node, bindingContext) { + var bindingsString = this['getBindingsString'](node, bindingContext); + return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext) : null; + }, + + // The following function is only used internally by this default provider. + // It's not part of the interface definition for a general binding provider. + 'getBindingsString': function(node, bindingContext) { + switch (node.nodeType) { + case 1: return node.getAttribute(defaultBindingAttributeName); // Element + case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node + default: return null; + } + }, + + // The following function is only used internally by this default provider. + // It's not part of the interface definition for a general binding provider. + 'parseBindingsString': function(bindingsString, bindingContext) { + try { + var viewModel = bindingContext['$data'], + scopes = (typeof viewModel == 'object' && viewModel != null) ? [viewModel, bindingContext] : [bindingContext], + bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, scopes.length, this.bindingCache); + return bindingFunction(scopes); + } catch (ex) { + throw new Error("Unable to parse bindings.\nMessage: " + ex + ";\nBindings value: " + bindingsString); + } + } + }); + + ko.bindingProvider['instance'] = new ko.bindingProvider(); + + function createBindingsStringEvaluatorViaCache(bindingsString, scopesCount, cache) { + var cacheKey = scopesCount + '_' + bindingsString; + return cache[cacheKey] + || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, scopesCount)); + } + + function createBindingsStringEvaluator(bindingsString, scopesCount) { + var rewrittenBindings = " { " + ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(bindingsString) + " } "; + return ko.utils.buildEvalWithinScopeFunction(rewrittenBindings, scopesCount); + } +})(); + +ko.exportSymbol('bindingProvider', ko.bindingProvider); +(function () { + ko.bindingHandlers = {}; + + ko.bindingContext = function(dataItem, parentBindingContext) { + if (parentBindingContext) { + ko.utils.extend(this, parentBindingContext); // Inherit $root and any custom properties + this['$parentContext'] = parentBindingContext; + this['$parent'] = parentBindingContext['$data']; + this['$parents'] = (parentBindingContext['$parents'] || []).slice(0); + this['$parents'].unshift(this['$parent']); + } else { + this['$parents'] = []; + this['$root'] = dataItem; + } + this['$data'] = dataItem; + } + ko.bindingContext.prototype['createChildContext'] = function (dataItem) { + return new ko.bindingContext(dataItem, this); + }; + ko.bindingContext.prototype['extend'] = function(properties) { + var clone = ko.utils.extend(new ko.bindingContext(), this); + return ko.utils.extend(clone, properties); + }; + + function validateThatBindingIsAllowedForVirtualElements(bindingName) { + var validator = ko.virtualElements.allowedBindings[bindingName]; + if (!validator) + throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements") + } + + function applyBindingsToDescendantsInternal (viewModel, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) { + var currentChild, nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement); + while (currentChild = nextInQueue) { + // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position + nextInQueue = ko.virtualElements.nextSibling(currentChild); + applyBindingsToNodeAndDescendantsInternal(viewModel, currentChild, bindingContextsMayDifferFromDomParentElement); + } + } + + function applyBindingsToNodeAndDescendantsInternal (viewModel, nodeVerified, bindingContextMayDifferFromDomParentElement) { + var shouldBindDescendants = true; + + // Perf optimisation: Apply bindings only if... + // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context) + // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those + // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template) + var isElement = (nodeVerified.nodeType === 1); + if (isElement) // Workaround IE <= 8 HTML parsing weirdness + ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified); + + var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1) + || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2) + if (shouldApplyBindings) + shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, viewModel, bindingContextMayDifferFromDomParentElement).shouldBindDescendants; + + if (shouldBindDescendants) { + // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So, + // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode, + // hence bindingContextsMayDifferFromDomParentElement is false + // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may + // skip over any number of intermediate virtual elements, any of which might define a custom binding context, + // hence bindingContextsMayDifferFromDomParentElement is true + applyBindingsToDescendantsInternal(viewModel, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement); + } + } + + function applyBindingsToNodeInternal (node, bindings, viewModelOrBindingContext, bindingContextMayDifferFromDomParentElement) { + // Need to be sure that inits are only run once, and updates never run until all the inits have been run + var initPhase = 0; // 0 = before all inits, 1 = during inits, 2 = after all inits + + // Each time the dependentObservable is evaluated (after data changes), + // the binding attribute is reparsed so that it can pick out the correct + // model properties in the context of the changed data. + // DOM event callbacks need to be able to access this changed data, + // so we need a single parsedBindings variable (shared by all callbacks + // associated with this node's bindings) that all the closures can access. + var parsedBindings; + function makeValueAccessor(bindingKey) { + return function () { return parsedBindings[bindingKey] } + } + function parsedBindingsAccessor() { + return parsedBindings; + } + + var bindingHandlerThatControlsDescendantBindings; + ko.dependentObservable( + function () { + // Ensure we have a nonnull binding context to work with + var bindingContextInstance = viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext) + ? viewModelOrBindingContext + : new ko.bindingContext(ko.utils.unwrapObservable(viewModelOrBindingContext)); + var viewModel = bindingContextInstance['$data']; + + // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because + // we can easily recover it just by scanning up the node's ancestors in the DOM + // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent) + if (bindingContextMayDifferFromDomParentElement) + ko.storedBindingContextForNode(node, bindingContextInstance); + + // Use evaluatedBindings if given, otherwise fall back on asking the bindings provider to give us some bindings + var evaluatedBindings = (typeof bindings == "function") ? bindings() : bindings; + parsedBindings = evaluatedBindings || ko.bindingProvider['instance']['getBindings'](node, bindingContextInstance); + + if (parsedBindings) { + // First run all the inits, so bindings can register for notification on changes + if (initPhase === 0) { + initPhase = 1; + for (var bindingKey in parsedBindings) { + var binding = ko.bindingHandlers[bindingKey]; + if (binding && node.nodeType === 8) + validateThatBindingIsAllowedForVirtualElements(bindingKey); + + if (binding && typeof binding["init"] == "function") { + var handlerInitFn = binding["init"]; + var initResult = handlerInitFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance); + + // If this binding handler claims to control descendant bindings, make a note of this + if (initResult && initResult['controlsDescendantBindings']) { + if (bindingHandlerThatControlsDescendantBindings !== undefined) + throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element."); + bindingHandlerThatControlsDescendantBindings = bindingKey; + } + } + } + initPhase = 2; + } + + // ... then run all the updates, which might trigger changes even on the first evaluation + if (initPhase === 2) { + for (var bindingKey in parsedBindings) { + var binding = ko.bindingHandlers[bindingKey]; + if (binding && typeof binding["update"] == "function") { + var handlerUpdateFn = binding["update"]; + handlerUpdateFn(node, makeValueAccessor(bindingKey), parsedBindingsAccessor, viewModel, bindingContextInstance); + } + } + } + } + }, + null, + { 'disposeWhenNodeIsRemoved' : node } + ); + + return { + shouldBindDescendants: bindingHandlerThatControlsDescendantBindings === undefined + }; + }; + + var storedBindingContextDomDataKey = "__ko_bindingContext__"; + ko.storedBindingContextForNode = function (node, bindingContext) { + if (arguments.length == 2) + ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext); + else + return ko.utils.domData.get(node, storedBindingContextDomDataKey); + } + + ko.applyBindingsToNode = function (node, bindings, viewModel) { + if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness + ko.virtualElements.normaliseVirtualElementDomStructure(node); + return applyBindingsToNodeInternal(node, bindings, viewModel, true); + }; + + ko.applyBindingsToDescendants = function(viewModel, rootNode) { + if (rootNode.nodeType === 1 || rootNode.nodeType === 8) + applyBindingsToDescendantsInternal(viewModel, rootNode, true); + }; + + ko.applyBindings = function (viewModel, rootNode) { + if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8)) + throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"); + rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional + + applyBindingsToNodeAndDescendantsInternal(viewModel, rootNode, true); + }; + + // Retrieving binding context from arbitrary nodes + ko.contextFor = function(node) { + // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them) + switch (node.nodeType) { + case 1: + case 8: + var context = ko.storedBindingContextForNode(node); + if (context) return context; + if (node.parentNode) return ko.contextFor(node.parentNode); + break; + } + return undefined; + }; + ko.dataFor = function(node) { + var context = ko.contextFor(node); + return context ? context['$data'] : undefined; + }; + + ko.exportSymbol('bindingHandlers', ko.bindingHandlers); + ko.exportSymbol('applyBindings', ko.applyBindings); + ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants); + ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode); + ko.exportSymbol('contextFor', ko.contextFor); + ko.exportSymbol('dataFor', ko.dataFor); +})(); +// For certain common events (currently just 'click'), allow a simplified data-binding syntax +// e.g. click:handler instead of the usual full-length event:{click:handler} +var eventHandlersWithShortcuts = ['click']; +ko.utils.arrayForEach(eventHandlersWithShortcuts, function(eventName) { + ko.bindingHandlers[eventName] = { + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel) { + var newValueAccessor = function () { + var result = {}; + result[eventName] = valueAccessor(); + return result; + }; + return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindingsAccessor, viewModel); + } + } +}); + + +ko.bindingHandlers['event'] = { + 'init' : function (element, valueAccessor, allBindingsAccessor, viewModel) { + var eventsToHandle = valueAccessor() || {}; + for(var eventNameOutsideClosure in eventsToHandle) { + (function() { + var eventName = eventNameOutsideClosure; // Separate variable to be captured by event handler closure + if (typeof eventName == "string") { + ko.utils.registerEventHandler(element, eventName, function (event) { + var handlerReturnValue; + var handlerFunction = valueAccessor()[eventName]; + if (!handlerFunction) + return; + var allBindings = allBindingsAccessor(); + + try { + // Take all the event args, and prefix with the viewmodel + var argsForHandler = ko.utils.makeArray(arguments); + argsForHandler.unshift(viewModel); + handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler); + } finally { + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true. + if (event.preventDefault) + event.preventDefault(); + else + event.returnValue = false; + } + } + + var bubble = allBindings[eventName + 'Bubble'] !== false; + if (!bubble) { + event.cancelBubble = true; + if (event.stopPropagation) + event.stopPropagation(); + } + }); + } + })(); + } + } +}; + +ko.bindingHandlers['submit'] = { + 'init': function (element, valueAccessor, allBindingsAccessor, viewModel) { + if (typeof valueAccessor() != "function") + throw new Error("The value for a submit binding must be a function"); + ko.utils.registerEventHandler(element, "submit", function (event) { + var handlerReturnValue; + var value = valueAccessor(); + try { handlerReturnValue = value.call(viewModel, element); } + finally { + if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true. + if (event.preventDefault) + event.preventDefault(); + else + event.returnValue = false; + } + } + }); + } +}; + +ko.bindingHandlers['visible'] = { + 'update': function (element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor()); + var isCurrentlyVisible = !(element.style.display == "none"); + if (value && !isCurrentlyVisible) + element.style.display = ""; + else if ((!value) && isCurrentlyVisible) + element.style.display = "none"; + } +} + +ko.bindingHandlers['enable'] = { + 'update': function (element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor()); + if (value && element.disabled) + element.removeAttribute("disabled"); + else if ((!value) && (!element.disabled)) + element.disabled = true; + } +}; + +ko.bindingHandlers['disable'] = { + 'update': function (element, valueAccessor) { + ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) }); + } +}; + +function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) { + if (preferModelValue) { + if (modelValue !== ko.selectExtensions.readValue(element)) + ko.selectExtensions.writeValue(element, modelValue); + } + + // No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value. + // If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way, + // change the model value to match the dropdown. + if (modelValue !== ko.selectExtensions.readValue(element)) + ko.utils.triggerEvent(element, "change"); +}; + +ko.bindingHandlers['value'] = { + 'init': function (element, valueAccessor, allBindingsAccessor) { + // Always catch "change" event; possibly other events too if asked + var eventsToCatch = ["change"]; + var requestedEventsToCatch = allBindingsAccessor()["valueUpdate"]; + if (requestedEventsToCatch) { + if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names + requestedEventsToCatch = [requestedEventsToCatch]; + ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch); + eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch); + } + + var valueUpdateHandler = function() { + var modelValue = valueAccessor(); + var elementValue = ko.selectExtensions.readValue(element); + ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue, /* checkIfDifferent: */ true); + } + + // Workaround for https://github.com/SteveSanderson/knockout/issues/122 + // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list + var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text" + && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off"); + if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) { + var propertyChangedFired = false; + ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true }); + ko.utils.registerEventHandler(element, "blur", function() { + if (propertyChangedFired) { + propertyChangedFired = false; + valueUpdateHandler(); + } + }); + } + + ko.utils.arrayForEach(eventsToCatch, function(eventName) { + // The syntax "after<eventname>" means "run the handler asynchronously after the event" + // This is useful, for example, to catch "keydown" events after the browser has updated the control + // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event) + var handler = valueUpdateHandler; + if (ko.utils.stringStartsWith(eventName, "after")) { + handler = function() { setTimeout(valueUpdateHandler, 0) }; + eventName = eventName.substring("after".length); + } + ko.utils.registerEventHandler(element, eventName, handler); + }); + }, + 'update': function (element, valueAccessor) { + var valueIsSelectOption = ko.utils.tagNameLower(element) === "select"; + var newValue = ko.utils.unwrapObservable(valueAccessor()); + var elementValue = ko.selectExtensions.readValue(element); + var valueHasChanged = (newValue != elementValue); + + // JavaScript's 0 == "" behavious is unfortunate here as it prevents writing 0 to an empty text box (loose equality suggests the values are the same). + // We don't want to do a strict equality comparison as that is more confusing for developers in certain cases, so we specifically special case 0 != "" here. + if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0")) + valueHasChanged = true; + + if (valueHasChanged) { + var applyValueAction = function () { ko.selectExtensions.writeValue(element, newValue); }; + applyValueAction(); + + // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread + // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread + // to apply the value as well. + var alsoApplyAsynchronously = valueIsSelectOption; + if (alsoApplyAsynchronously) + setTimeout(applyValueAction, 0); + } + + // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change, + // because you're not allowed to have a model value that disagrees with a visible UI selection. + if (valueIsSelectOption && (element.length > 0)) + ensureDropdownSelectionIsConsistentWithModelValue(element, newValue, /* preferModelValue */ false); + } +}; + +ko.bindingHandlers['options'] = { + 'update': function (element, valueAccessor, allBindingsAccessor) { + if (ko.utils.tagNameLower(element) !== "select") + throw new Error("options binding applies only to SELECT elements"); + + var selectWasPreviouslyEmpty = element.length == 0; + var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) { + return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected; + }), function (node) { + return ko.selectExtensions.readValue(node) || node.innerText || node.textContent; + }); + var previousScrollTop = element.scrollTop; + + var value = ko.utils.unwrapObservable(valueAccessor()); + var selectedValue = element.value; + + // Remove all existing <option>s. + // Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134) + while (element.length > 0) { + ko.cleanNode(element.options[0]); + element.remove(0); + } + + if (value) { + var allBindings = allBindingsAccessor(); + if (typeof value.length != "number") + value = [value]; + if (allBindings['optionsCaption']) { + var option = document.createElement("option"); + ko.utils.setHtml(option, allBindings['optionsCaption']); + ko.selectExtensions.writeValue(option, undefined); + element.appendChild(option); + } + for (var i = 0, j = value.length; i < j; i++) { + var option = document.createElement("option"); + + // Apply a value to the option element + var optionValue = typeof allBindings['optionsValue'] == "string" ? value[i][allBindings['optionsValue']] : value[i]; + optionValue = ko.utils.unwrapObservable(optionValue); + ko.selectExtensions.writeValue(option, optionValue); + + // Apply some text to the option element + var optionsTextValue = allBindings['optionsText']; + var optionText; + if (typeof optionsTextValue == "function") + optionText = optionsTextValue(value[i]); // Given a function; run it against the data value + else if (typeof optionsTextValue == "string") + optionText = value[i][optionsTextValue]; // Given a string; treat it as a property name on the data value + else + optionText = optionValue; // Given no optionsText arg; use the data value itself + if ((optionText === null) || (optionText === undefined)) + optionText = ""; + + ko.utils.setTextContent(option, optionText); + + element.appendChild(option); + } + + // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document. + // That's why we first added them without selection. Now it's time to set the selection. + var newOptions = element.getElementsByTagName("option"); + var countSelectionsRetained = 0; + for (var i = 0, j = newOptions.length; i < j; i++) { + if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) { + ko.utils.setOptionNodeSelectionState(newOptions[i], true); + countSelectionsRetained++; + } + } + + element.scrollTop = previousScrollTop; + + if (selectWasPreviouslyEmpty && ('value' in allBindings)) { + // Ensure consistency between model value and selected option. + // If the dropdown is being populated for the first time here (or was otherwise previously empty), + // the dropdown selection state is meaningless, so we preserve the model value. + ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.unwrapObservable(allBindings['value']), /* preferModelValue */ true); + } + + // Workaround for IE9 bug + ko.utils.ensureSelectElementIsRenderedCorrectly(element); + } + } +}; +ko.bindingHandlers['options'].optionValueDomDataKey = '__ko.optionValueDomData__'; + +ko.bindingHandlers['selectedOptions'] = { + getSelectedValuesFromSelectNode: function (selectNode) { + var result = []; + var nodes = selectNode.childNodes; + for (var i = 0, j = nodes.length; i < j; i++) { + var node = nodes[i], tagName = ko.utils.tagNameLower(node); + if (tagName == "option" && node.selected) + result.push(ko.selectExtensions.readValue(node)); + else if (tagName == "optgroup") { + var selectedValuesFromOptGroup = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(node); + Array.prototype.splice.apply(result, [result.length, 0].concat(selectedValuesFromOptGroup)); // Add new entries to existing 'result' instance + } + } + return result; + }, + 'init': function (element, valueAccessor, allBindingsAccessor) { + ko.utils.registerEventHandler(element, "change", function () { + var value = valueAccessor(); + var valueToWrite = ko.bindingHandlers['selectedOptions'].getSelectedValuesFromSelectNode(this); + ko.jsonExpressionRewriting.writeValueToProperty(value, allBindingsAccessor, 'value', valueToWrite); + }); + }, + 'update': function (element, valueAccessor) { + if (ko.utils.tagNameLower(element) != "select") + throw new Error("values binding applies only to SELECT elements"); + + var newValue = ko.utils.unwrapObservable(valueAccessor()); + if (newValue && typeof newValue.length == "number") { + var nodes = element.childNodes; + for (var i = 0, j = nodes.length; i < j; i++) { + var node = nodes[i]; + if (ko.utils.tagNameLower(node) === "option") + ko.utils.setOptionNodeSelectionState(node, ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0); + } + } + } +}; + +ko.bindingHandlers['text'] = { + 'update': function (element, valueAccessor) { + ko.utils.setTextContent(element, valueAccessor()); + } +}; + +ko.bindingHandlers['html'] = { + 'init': function() { + // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications) + return { 'controlsDescendantBindings': true }; + }, + 'update': function (element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor()); + ko.utils.setHtml(element, value); + } +}; + +ko.bindingHandlers['css'] = { + 'update': function (element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor() || {}); + for (var className in value) { + if (typeof className == "string") { + var shouldHaveClass = ko.utils.unwrapObservable(value[className]); + ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass); + } + } + } +}; + +ko.bindingHandlers['style'] = { + 'update': function (element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor() || {}); + for (var styleName in value) { + if (typeof styleName == "string") { + var styleValue = ko.utils.unwrapObservable(value[styleName]); + element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect + } + } + } +}; + +ko.bindingHandlers['uniqueName'] = { + 'init': function (element, valueAccessor) { + if (valueAccessor()) { + element.name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex); + + // Workaround IE 6/7 issue + // - https://github.com/SteveSanderson/knockout/issues/197 + // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/ + if (ko.utils.isIe6 || ko.utils.isIe7) + element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false); + } + } +}; +ko.bindingHandlers['uniqueName'].currentIndex = 0; + +ko.bindingHandlers['checked'] = { + 'init': function (element, valueAccessor, allBindingsAccessor) { + var updateHandler = function() { + var valueToWrite; + if (element.type == "checkbox") { + valueToWrite = element.checked; + } else if ((element.type == "radio") && (element.checked)) { + valueToWrite = element.value; + } else { + return; // "checked" binding only responds to checkboxes and selected radio buttons + } + + var modelValue = valueAccessor(); + if ((element.type == "checkbox") && (ko.utils.unwrapObservable(modelValue) instanceof Array)) { + // For checkboxes bound to an array, we add/remove the checkbox value to that array + // This works for both observable and non-observable arrays + var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.unwrapObservable(modelValue), element.value); + if (element.checked && (existingEntryIndex < 0)) + modelValue.push(element.value); + else if ((!element.checked) && (existingEntryIndex >= 0)) + modelValue.splice(existingEntryIndex, 1); + } else { + ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true); + } + }; + ko.utils.registerEventHandler(element, "click", updateHandler); + + // IE 6 won't allow radio buttons to be selected unless they have a name + if ((element.type == "radio") && !element.name) + ko.bindingHandlers['uniqueName']['init'](element, function() { return true }); + }, + 'update': function (element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor()); + + if (element.type == "checkbox") { + if (value instanceof Array) { + // When bound to an array, the checkbox being checked represents its value being present in that array + element.checked = ko.utils.arrayIndexOf(value, element.value) >= 0; + } else { + // When bound to anything other value (not an array), the checkbox being checked represents the value being trueish + element.checked = value; + } + } else if (element.type == "radio") { + element.checked = (element.value == value); + } + } +}; + +var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' }; +ko.bindingHandlers['attr'] = { + 'update': function(element, valueAccessor, allBindingsAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor()) || {}; + for (var attrName in value) { + if (typeof attrName == "string") { + var attrValue = ko.utils.unwrapObservable(value[attrName]); + + // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely + // when someProp is a "no value"-like value (strictly null, false, or undefined) + // (because the absence of the "checked" attr is how to mark an element as not checked, etc.) + var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined); + if (toRemove) + element.removeAttribute(attrName); + + // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the + // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior, + // but instead of figuring out the mode, we'll just set the attribute through the Javascript + // property for IE <= 8. + if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) { + attrName = attrHtmlToJavascriptMap[attrName]; + if (toRemove) + element.removeAttribute(attrName); + else + element[attrName] = attrValue; + } else if (!toRemove) { + element.setAttribute(attrName, attrValue.toString()); + } + } + } + } +}; + +ko.bindingHandlers['hasfocus'] = { + 'init': function(element, valueAccessor, allBindingsAccessor) { + var writeValue = function(valueToWrite) { + var modelValue = valueAccessor(); + ko.jsonExpressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'hasfocus', valueToWrite, true); + }; + ko.utils.registerEventHandler(element, "focus", function() { writeValue(true) }); + ko.utils.registerEventHandler(element, "focusin", function() { writeValue(true) }); // For IE + ko.utils.registerEventHandler(element, "blur", function() { writeValue(false) }); + ko.utils.registerEventHandler(element, "focusout", function() { writeValue(false) }); // For IE + }, + 'update': function(element, valueAccessor) { + var value = ko.utils.unwrapObservable(valueAccessor()); + value ? element.focus() : element.blur(); + ko.utils.triggerEvent(element, value ? "focusin" : "focusout"); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously + } +}; + +// "with: someExpression" is equivalent to "template: { if: someExpression, data: someExpression }" +ko.bindingHandlers['with'] = { + makeTemplateValueAccessor: function(valueAccessor) { + return function() { var value = valueAccessor(); return { 'if': value, 'data': value, 'templateEngine': ko.nativeTemplateEngine.instance } }; + }, + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor)); + }, + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['with'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext); + } +}; +ko.jsonExpressionRewriting.bindingRewriteValidators['with'] = false; // Can't rewrite control flow bindings +ko.virtualElements.allowedBindings['with'] = true; + +// "if: someExpression" is equivalent to "template: { if: someExpression }" +ko.bindingHandlers['if'] = { + makeTemplateValueAccessor: function(valueAccessor) { + return function() { return { 'if': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } }; + }, + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor)); + }, + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['if'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext); + } +}; +ko.jsonExpressionRewriting.bindingRewriteValidators['if'] = false; // Can't rewrite control flow bindings +ko.virtualElements.allowedBindings['if'] = true; + +// "ifnot: someExpression" is equivalent to "template: { ifnot: someExpression }" +ko.bindingHandlers['ifnot'] = { + makeTemplateValueAccessor: function(valueAccessor) { + return function() { return { 'ifnot': valueAccessor(), 'templateEngine': ko.nativeTemplateEngine.instance } }; + }, + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor)); + }, + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['ifnot'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext); + } +}; +ko.jsonExpressionRewriting.bindingRewriteValidators['ifnot'] = false; // Can't rewrite control flow bindings +ko.virtualElements.allowedBindings['ifnot'] = true; + +// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }" +// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }" +ko.bindingHandlers['foreach'] = { + makeTemplateValueAccessor: function(valueAccessor) { + return function() { + var bindingValue = ko.utils.unwrapObservable(valueAccessor()); + + // If bindingValue is the array, just pass it on its own + if ((!bindingValue) || typeof bindingValue.length == "number") + return { 'foreach': bindingValue, 'templateEngine': ko.nativeTemplateEngine.instance }; + + // If bindingValue.data is the array, preserve all relevant options + return { + 'foreach': bindingValue['data'], + 'includeDestroyed': bindingValue['includeDestroyed'], + 'afterAdd': bindingValue['afterAdd'], + 'beforeRemove': bindingValue['beforeRemove'], + 'afterRender': bindingValue['afterRender'], + 'templateEngine': ko.nativeTemplateEngine.instance + }; + }; + }, + 'init': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor)); + }, + 'update': function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindingsAccessor, viewModel, bindingContext); + } +}; +ko.jsonExpressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings +ko.virtualElements.allowedBindings['foreach'] = true; +// If you want to make a custom template engine, +// +// [1] Inherit from this class (like ko.nativeTemplateEngine does) +// [2] Override 'renderTemplateSource', supplying a function with this signature: +// +// function (templateSource, bindingContext, options) { +// // - templateSource.text() is the text of the template you should render +// // - bindingContext.$data is the data you should pass into the template +// // - you might also want to make bindingContext.$parent, bindingContext.$parents, +// // and bindingContext.$root available in the template too +// // - options gives you access to any other properties set on "data-bind: { template: options }" +// // +// // Return value: an array of DOM nodes +// } +// +// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature: +// +// function (script) { +// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result" +// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }' +// } +// +// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables. +// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does) +// and then you don't need to override 'createJavaScriptEvaluatorBlock'. + +ko.templateEngine = function () { }; + +ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) { + throw new Error("Override renderTemplateSource"); +}; + +ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) { + throw new Error("Override createJavaScriptEvaluatorBlock"); +}; + +ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) { + // Named template + if (typeof template == "string") { + templateDocument = templateDocument || document; + var elem = templateDocument.getElementById(template); + if (!elem) + throw new Error("Cannot find template with ID " + template); + return new ko.templateSources.domElement(elem); + } else if ((template.nodeType == 1) || (template.nodeType == 8)) { + // Anonymous template + return new ko.templateSources.anonymousTemplate(template); + } else + throw new Error("Unknown template type: " + template); +}; + +ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) { + var templateSource = this['makeTemplateSource'](template, templateDocument); + return this['renderTemplateSource'](templateSource, bindingContext, options); +}; + +ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) { + // Skip rewriting if requested + if (this['allowTemplateRewriting'] === false) + return true; + + // Perf optimisation - see below + var templateIsInExternalDocument = templateDocument && templateDocument != document; + if (!templateIsInExternalDocument && this.knownRewrittenTemplates && this.knownRewrittenTemplates[template]) + return true; + + return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten"); +}; + +ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) { + var templateSource = this['makeTemplateSource'](template, templateDocument); + var rewritten = rewriterCallback(templateSource['text']()); + templateSource['text'](rewritten); + templateSource['data']("isRewritten", true); + + // Perf optimisation - for named templates, track which ones have been rewritten so we can + // answer 'isTemplateRewritten' *without* having to use getElementById (which is slow on IE < 8) + // + // Note that we only cache the status for templates in the main document, because caching on a per-doc + // basis complicates the implementation excessively. In a future version of KO, we will likely remove + // this 'isRewritten' cache entirely anyway, because the benefit is extremely minor and only applies + // to rewritable templates, which are pretty much deprecated since KO 2.0. + var templateIsInExternalDocument = templateDocument && templateDocument != document; + if (!templateIsInExternalDocument && typeof template == "string") { + this.knownRewrittenTemplates = this.knownRewrittenTemplates || {}; + this.knownRewrittenTemplates[template] = true; + } +}; + +ko.exportSymbol('templateEngine', ko.templateEngine); + +ko.templateRewriting = (function () { + var memoizeDataBindingAttributeSyntaxRegex = /(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi; + var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g; + + function validateDataBindValuesForRewriting(keyValueArray) { + var allValidators = ko.jsonExpressionRewriting.bindingRewriteValidators; + for (var i = 0; i < keyValueArray.length; i++) { + var key = keyValueArray[i]['key']; + if (allValidators.hasOwnProperty(key)) { + var validator = allValidators[key]; + + if (typeof validator === "function") { + var possibleErrorMessage = validator(keyValueArray[i]['value']); + if (possibleErrorMessage) + throw new Error(possibleErrorMessage); + } else if (!validator) { + throw new Error("This template engine does not support the '" + key + "' binding within its templates"); + } + } + } + } + + function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, templateEngine) { + var dataBindKeyValueArray = ko.jsonExpressionRewriting.parseObjectLiteral(dataBindAttributeValue); + validateDataBindValuesForRewriting(dataBindKeyValueArray); + var rewrittenDataBindAttributeValue = ko.jsonExpressionRewriting.insertPropertyAccessorsIntoJson(dataBindKeyValueArray); + + // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional + // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this + // extra indirection. + var applyBindingsToNextSiblingScript = "ko.templateRewriting.applyMemoizedBindingsToNextSibling(function() { \ + return (function() { return { " + rewrittenDataBindAttributeValue + " } })() \ + })"; + return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain; + } + + return { + ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) { + if (!templateEngine['isTemplateRewritten'](template, templateDocument)) + templateEngine['rewriteTemplate'](template, function (htmlString) { + return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine); + }, templateDocument); + }, + + memoizeBindingAttributeSyntax: function (htmlString, templateEngine) { + return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () { + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[6], /* tagToRetain: */ arguments[1], templateEngine); + }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() { + return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", templateEngine); + }); + }, + + applyMemoizedBindingsToNextSibling: function (bindings) { + return ko.memoization.memoize(function (domNode, bindingContext) { + if (domNode.nextSibling) + ko.applyBindingsToNode(domNode.nextSibling, bindings, bindingContext); + }); + } + } +})(); + +ko.exportSymbol('templateRewriting', ko.templateRewriting); +ko.exportSymbol('templateRewriting.applyMemoizedBindingsToNextSibling', ko.templateRewriting.applyMemoizedBindingsToNextSibling); // Exported only because it has to be referenced by string lookup from within rewritten template +(function() { + // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving + // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.) + // + // Two are provided by default: + // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element + // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but + // without reading/writing the actual element text content, since it will be overwritten + // with the rendered template output. + // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements. + // Template sources need to have the following functions: + // text() - returns the template text from your storage location + // text(value) - writes the supplied template text to your storage location + // data(key) - reads values stored using data(key, value) - see below + // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten". + // + // Optionally, template sources can also have the following functions: + // nodes() - returns a DOM element containing the nodes of this template, where available + // nodes(value) - writes the given DOM element to your storage location + // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text() + // for improved speed. However, all templateSources must supply text() even if they don't supply nodes(). + // + // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were + // using and overriding "makeTemplateSource" to return an instance of your custom template source. + + ko.templateSources = {}; + + // ---- ko.templateSources.domElement ----- + + ko.templateSources.domElement = function(element) { + this.domElement = element; + } + + ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) { + var tagNameLower = ko.utils.tagNameLower(this.domElement), + elemContentsProperty = tagNameLower === "script" ? "text" + : tagNameLower === "textarea" ? "value" + : "innerHTML"; + + if (arguments.length == 0) { + return this.domElement[elemContentsProperty]; + } else { + var valueToWrite = arguments[0]; + if (elemContentsProperty === "innerHTML") + ko.utils.setHtml(this.domElement, valueToWrite); + else + this.domElement[elemContentsProperty] = valueToWrite; + } + }; + + ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) { + if (arguments.length === 1) { + return ko.utils.domData.get(this.domElement, "templateSourceData_" + key); + } else { + ko.utils.domData.set(this.domElement, "templateSourceData_" + key, arguments[1]); + } + }; + + // ---- ko.templateSources.anonymousTemplate ----- + // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes". + // For compatibility, you can also read "text"; it will be serialized from the nodes on demand. + // Writing to "text" is still supported, but then the template data will not be available as DOM nodes. + + var anonymousTemplatesDomDataKey = "__ko_anon_template__"; + ko.templateSources.anonymousTemplate = function(element) { + this.domElement = element; + } + ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement(); + ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) { + if (arguments.length == 0) { + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {}; + if (templateData.textData === undefined && templateData.containerData) + templateData.textData = templateData.containerData.innerHTML; + return templateData.textData; + } else { + var valueToWrite = arguments[0]; + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite}); + } + }; + ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) { + if (arguments.length == 0) { + var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {}; + return templateData.containerData; + } else { + var valueToWrite = arguments[0]; + ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite}); + } + }; + + ko.exportSymbol('templateSources', ko.templateSources); + ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement); + ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate); +})(); +(function () { + var _templateEngine; + ko.setTemplateEngine = function (templateEngine) { + if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine)) + throw new Error("templateEngine must inherit from ko.templateEngine"); + _templateEngine = templateEngine; + } + + function invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, action) { + var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode); + while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) { + nextInQueue = ko.virtualElements.nextSibling(node); + if (node.nodeType === 1 || node.nodeType === 8) + action(node); + } + } + + function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) { + // To be used on any nodes that have been rendered by a template and have been inserted into some parent element + // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because + // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense, + // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings + // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting) + + if (continuousNodeArray.length) { + var firstNode = continuousNodeArray[0], lastNode = continuousNodeArray[continuousNodeArray.length - 1]; + + // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind) + // whereas a regular applyBindings won't introduce new memoized nodes + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) { + ko.applyBindings(bindingContext, node); + }); + invokeForEachNodeOrCommentInContinuousRange(firstNode, lastNode, function(node) { + ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]); + }); + } + } + + function getFirstNodeFromPossibleArray(nodeOrNodeArray) { + return nodeOrNodeArray.nodeType ? nodeOrNodeArray + : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0] + : null; + } + + function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) { + options = options || {}; + var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray); + var templateDocument = firstTargetNode && firstTargetNode.ownerDocument; + var templateEngineToUse = (options['templateEngine'] || _templateEngine); + ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument); + var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument); + + // Loosely check result is an array of DOM nodes + if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number")) + throw new Error("Template engine must return an array of DOM nodes"); + + var haveAddedNodesToParent = false; + switch (renderMode) { + case "replaceChildren": + ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray); + haveAddedNodesToParent = true; + break; + case "replaceNode": + ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray); + haveAddedNodesToParent = true; + break; + case "ignoreTargetNode": break; + default: + throw new Error("Unknown renderMode: " + renderMode); + } + + if (haveAddedNodesToParent) { + activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext); + if (options['afterRender']) + options['afterRender'](renderedNodesArray, bindingContext['$data']); + } + + return renderedNodesArray; + } + + ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) { + options = options || {}; + if ((options['templateEngine'] || _templateEngine) == undefined) + throw new Error("Set a template engine before calling renderTemplate"); + renderMode = renderMode || "replaceChildren"; + + if (targetNodeOrNodeArray) { + var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray); + + var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation) + var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode; + + return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes + function () { + // Ensure we've got a proper binding context to work with + var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext)) + ? dataOrBindingContext + : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext)); + + // Support selecting template as a function of the data being rendered + var templateName = typeof(template) == 'function' ? template(bindingContext['$data']) : template; + + var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options); + if (renderMode == "replaceNode") { + targetNodeOrNodeArray = renderedNodesArray; + firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray); + } + }, + null, + { 'disposeWhen': whenToDispose, 'disposeWhenNodeIsRemoved': activelyDisposeWhenNodeIsRemoved } + ); + } else { + // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node + return ko.memoization.memoize(function (domNode) { + ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode"); + }); + } + }; + + ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) { + // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then + // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter. + var arrayItemContext; + + // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode + var executeTemplateForArrayItem = function (arrayValue, index) { + // Support selecting template as a function of the data being rendered + var templateName = typeof(template) == 'function' ? template(arrayValue) : template; + arrayItemContext = parentBindingContext['createChildContext'](ko.utils.unwrapObservable(arrayValue)); + arrayItemContext['$index'] = index; + return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options); + } + + // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode + var activateBindingsCallback = function(arrayValue, addedNodesArray, index) { + activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext); + if (options['afterRender']) + options['afterRender'](addedNodesArray, arrayValue); + }; + + return ko.dependentObservable(function () { + var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || []; + if (typeof unwrappedArray.length == "undefined") // Coerce single value into array + unwrappedArray = [unwrappedArray]; + + // Filter out any entries marked as destroyed + var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) { + return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']); + }); + + ko.utils.setDomNodeChildrenFromArrayMapping(targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback); + + }, null, { 'disposeWhenNodeIsRemoved': targetNode }); + }; + + var templateSubscriptionDomDataKey = '__ko__templateSubscriptionDomDataKey__'; + function disposeOldSubscriptionAndStoreNewOne(element, newSubscription) { + var oldSubscription = ko.utils.domData.get(element, templateSubscriptionDomDataKey); + if (oldSubscription && (typeof(oldSubscription.dispose) == 'function')) + oldSubscription.dispose(); + ko.utils.domData.set(element, templateSubscriptionDomDataKey, newSubscription); + } + + ko.bindingHandlers['template'] = { + 'init': function(element, valueAccessor) { + // Support anonymous templates + var bindingValue = ko.utils.unwrapObservable(valueAccessor()); + if ((typeof bindingValue != "string") && (!bindingValue['name']) && (element.nodeType == 1 || element.nodeType == 8)) { + // It's an anonymous template - store the element contents, then clear the element + var templateNodes = element.nodeType == 1 ? element.childNodes : ko.virtualElements.childNodes(element), + container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent + new ko.templateSources.anonymousTemplate(element)['nodes'](container); + } + return { 'controlsDescendantBindings': true }; + }, + 'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + var bindingValue = ko.utils.unwrapObservable(valueAccessor()); + var templateName; + var shouldDisplay = true; + + if (typeof bindingValue == "string") { + templateName = bindingValue; + } else { + templateName = bindingValue['name']; + + // Support "if"/"ifnot" conditions + if ('if' in bindingValue) + shouldDisplay = shouldDisplay && ko.utils.unwrapObservable(bindingValue['if']); + if ('ifnot' in bindingValue) + shouldDisplay = shouldDisplay && !ko.utils.unwrapObservable(bindingValue['ifnot']); + } + + var templateSubscription = null; + + if ((typeof bindingValue === 'object') && ('foreach' in bindingValue)) { // Note: can't use 'in' operator on strings + // Render once for each data point (treating data set as empty if shouldDisplay==false) + var dataArray = (shouldDisplay && bindingValue['foreach']) || []; + templateSubscription = ko.renderTemplateForEach(templateName || element, dataArray, /* options: */ bindingValue, element, bindingContext); + } else { + if (shouldDisplay) { + // Render once for this single data point (or use the viewModel if no data was provided) + var innerBindingContext = (typeof bindingValue == 'object') && ('data' in bindingValue) + ? bindingContext['createChildContext'](ko.utils.unwrapObservable(bindingValue['data'])) // Given an explitit 'data' value, we create a child binding context for it + : bindingContext; // Given no explicit 'data' value, we retain the same binding context + templateSubscription = ko.renderTemplate(templateName || element, innerBindingContext, /* options: */ bindingValue, element); + } else + ko.virtualElements.emptyNode(element); + } + + // It only makes sense to have a single template subscription per element (otherwise which one should have its output displayed?) + disposeOldSubscriptionAndStoreNewOne(element, templateSubscription); + } + }; + + // Anonymous templates can't be rewritten. Give a nice error message if you try to do it. + ko.jsonExpressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) { + var parsedBindingValue = ko.jsonExpressionRewriting.parseObjectLiteral(bindingValue); + + if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown']) + return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting) + + if (ko.jsonExpressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name")) + return null; // Named templates can be rewritten, so return "no error" + return "This template engine does not support anonymous templates nested within its templates"; + }; + + ko.virtualElements.allowedBindings['template'] = true; +})(); + +ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine); +ko.exportSymbol('renderTemplate', ko.renderTemplate); + +(function () { + // Simple calculation based on Levenshtein distance. + function calculateEditDistanceMatrix(oldArray, newArray, maxAllowedDistance) { + var distances = []; + for (var i = 0; i <= newArray.length; i++) + distances[i] = []; + + // Top row - transform old array into empty array via deletions + for (var i = 0, j = Math.min(oldArray.length, maxAllowedDistance); i <= j; i++) + distances[0][i] = i; + + // Left row - transform empty array into new array via additions + for (var i = 1, j = Math.min(newArray.length, maxAllowedDistance); i <= j; i++) { + distances[i][0] = i; + } + + // Fill out the body of the array + var oldIndex, oldIndexMax = oldArray.length, newIndex, newIndexMax = newArray.length; + var distanceViaAddition, distanceViaDeletion; + for (oldIndex = 1; oldIndex <= oldIndexMax; oldIndex++) { + var newIndexMinForRow = Math.max(1, oldIndex - maxAllowedDistance); + var newIndexMaxForRow = Math.min(newIndexMax, oldIndex + maxAllowedDistance); + for (newIndex = newIndexMinForRow; newIndex <= newIndexMaxForRow; newIndex++) { + if (oldArray[oldIndex - 1] === newArray[newIndex - 1]) + distances[newIndex][oldIndex] = distances[newIndex - 1][oldIndex - 1]; + else { + var northDistance = distances[newIndex - 1][oldIndex] === undefined ? Number.MAX_VALUE : distances[newIndex - 1][oldIndex] + 1; + var westDistance = distances[newIndex][oldIndex - 1] === undefined ? Number.MAX_VALUE : distances[newIndex][oldIndex - 1] + 1; + distances[newIndex][oldIndex] = Math.min(northDistance, westDistance); + } + } + } + + return distances; + } + + function findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray) { + var oldIndex = oldArray.length; + var newIndex = newArray.length; + var editScript = []; + var maxDistance = editDistanceMatrix[newIndex][oldIndex]; + if (maxDistance === undefined) + return null; // maxAllowedDistance must be too small + while ((oldIndex > 0) || (newIndex > 0)) { + var me = editDistanceMatrix[newIndex][oldIndex]; + var distanceViaAdd = (newIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex] : maxDistance + 1; + var distanceViaDelete = (oldIndex > 0) ? editDistanceMatrix[newIndex][oldIndex - 1] : maxDistance + 1; + var distanceViaRetain = (newIndex > 0) && (oldIndex > 0) ? editDistanceMatrix[newIndex - 1][oldIndex - 1] : maxDistance + 1; + if ((distanceViaAdd === undefined) || (distanceViaAdd < me - 1)) distanceViaAdd = maxDistance + 1; + if ((distanceViaDelete === undefined) || (distanceViaDelete < me - 1)) distanceViaDelete = maxDistance + 1; + if (distanceViaRetain < me - 1) distanceViaRetain = maxDistance + 1; + + if ((distanceViaAdd <= distanceViaDelete) && (distanceViaAdd < distanceViaRetain)) { + editScript.push({ status: "added", value: newArray[newIndex - 1] }); + newIndex--; + } else if ((distanceViaDelete < distanceViaAdd) && (distanceViaDelete < distanceViaRetain)) { + editScript.push({ status: "deleted", value: oldArray[oldIndex - 1] }); + oldIndex--; + } else { + editScript.push({ status: "retained", value: oldArray[oldIndex - 1] }); + newIndex--; + oldIndex--; + } + } + return editScript.reverse(); + } + + ko.utils.compareArrays = function (oldArray, newArray, maxEditsToConsider) { + if (maxEditsToConsider === undefined) { + return ko.utils.compareArrays(oldArray, newArray, 1) // First consider likely case where there is at most one edit (very fast) + || ko.utils.compareArrays(oldArray, newArray, 10) // If that fails, account for a fair number of changes while still being fast + || ko.utils.compareArrays(oldArray, newArray, Number.MAX_VALUE); // Ultimately give the right answer, even though it may take a long time + } else { + oldArray = oldArray || []; + newArray = newArray || []; + var editDistanceMatrix = calculateEditDistanceMatrix(oldArray, newArray, maxEditsToConsider); + return findEditScriptFromEditDistanceMatrix(editDistanceMatrix, oldArray, newArray); + } + }; +})(); + +ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays); + +(function () { + // Objective: + // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes, + // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node + // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node + // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we + // previously mapped - retain those nodes, and just insert/delete other ones + + // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node + // You can use this, for example, to activate bindings on those nodes. + + function fixUpVirtualElements(contiguousNodeArray) { + // Ensures that contiguousNodeArray really *is* an array of contiguous siblings, even if some of the interior + // ones have changed since your array was first built (e.g., because your array contains virtual elements, and + // their virtual children changed when binding was applied to them). + // This is needed so that we can reliably remove or update the nodes corresponding to a given array item + + if (contiguousNodeArray.length > 2) { + // Build up the actual new contiguous node set + var current = contiguousNodeArray[0], last = contiguousNodeArray[contiguousNodeArray.length - 1], newContiguousSet = [current]; + while (current !== last) { + current = current.nextSibling; + if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario) + return; + newContiguousSet.push(current); + } + + // ... then mutate the input array to match this. + // (The following line replaces the contents of contiguousNodeArray with newContiguousSet) + Array.prototype.splice.apply(contiguousNodeArray, [0, contiguousNodeArray.length].concat(newContiguousSet)); + } + } + + function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) { + // Map this array value inside a dependentObservable so we re-map when any dependency changes + var mappedNodes = []; + var dependentObservable = ko.dependentObservable(function() { + var newMappedNodes = mapping(valueToMap, index) || []; + + // On subsequent evaluations, just replace the previously-inserted DOM nodes + if (mappedNodes.length > 0) { + fixUpVirtualElements(mappedNodes); + ko.utils.replaceDomNodes(mappedNodes, newMappedNodes); + if (callbackAfterAddingNodes) + callbackAfterAddingNodes(valueToMap, newMappedNodes); + } + + // Replace the contents of the mappedNodes array, thereby updating the record + // of which nodes would be deleted if valueToMap was itself later removed + mappedNodes.splice(0, mappedNodes.length); + ko.utils.arrayPushAll(mappedNodes, newMappedNodes); + }, null, { 'disposeWhenNodeIsRemoved': containerNode, 'disposeWhen': function() { return (mappedNodes.length == 0) || !ko.utils.domNodeIsAttachedToDocument(mappedNodes[0]) } }); + return { mappedNodes : mappedNodes, dependentObservable : dependentObservable }; + } + + var lastMappingResultDomDataKey = "setDomNodeChildrenFromArrayMapping_lastMappingResult"; + + ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) { + // Compare the provided array against the previous one + array = array || []; + options = options || {}; + var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined; + var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || []; + var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; }); + var editScript = ko.utils.compareArrays(lastArray, array); + + // Build the new mapping result + var newMappingResult = []; + var lastMappingResultIndex = 0; + var nodesToDelete = []; + var newMappingResultIndex = 0; + var nodesAdded = []; + var insertAfterNode = null; + for (var i = 0, j = editScript.length; i < j; i++) { + switch (editScript[i].status) { + case "retained": + // Just keep the information - don't touch the nodes + var dataToRetain = lastMappingResult[lastMappingResultIndex]; + dataToRetain.indexObservable(newMappingResultIndex); + newMappingResultIndex = newMappingResult.push(dataToRetain); + if (dataToRetain.domNodes.length > 0) + insertAfterNode = dataToRetain.domNodes[dataToRetain.domNodes.length - 1]; + lastMappingResultIndex++; + break; + + case "deleted": + // Stop tracking changes to the mapping for these nodes + lastMappingResult[lastMappingResultIndex].dependentObservable.dispose(); + + // Queue these nodes for later removal + fixUpVirtualElements(lastMappingResult[lastMappingResultIndex].domNodes); + ko.utils.arrayForEach(lastMappingResult[lastMappingResultIndex].domNodes, function (node) { + nodesToDelete.push({ + element: node, + index: i, + value: editScript[i].value + }); + insertAfterNode = node; + }); + lastMappingResultIndex++; + break; + + case "added": + var valueToMap = editScript[i].value; + var indexObservable = ko.observable(newMappingResultIndex); + var mapData = mapNodeAndRefreshWhenChanged(domNode, mapping, valueToMap, callbackAfterAddingNodes, indexObservable); + var mappedNodes = mapData.mappedNodes; + + // On the first evaluation, insert the nodes at the current insertion point + newMappingResultIndex = newMappingResult.push({ + arrayEntry: editScript[i].value, + domNodes: mappedNodes, + dependentObservable: mapData.dependentObservable, + indexObservable: indexObservable + }); + for (var nodeIndex = 0, nodeIndexMax = mappedNodes.length; nodeIndex < nodeIndexMax; nodeIndex++) { + var node = mappedNodes[nodeIndex]; + nodesAdded.push({ + element: node, + index: i, + value: editScript[i].value + }); + if (insertAfterNode == null) { + // Insert "node" (the newly-created node) as domNode's first child + ko.virtualElements.prepend(domNode, node); + } else { + // Insert "node" into "domNode" immediately after "insertAfterNode" + ko.virtualElements.insertAfter(domNode, node, insertAfterNode); + } + insertAfterNode = node; + } + if (callbackAfterAddingNodes) + callbackAfterAddingNodes(valueToMap, mappedNodes, indexObservable); + break; + } + } + + ko.utils.arrayForEach(nodesToDelete, function (node) { ko.cleanNode(node.element) }); + + var invokedBeforeRemoveCallback = false; + if (!isFirstExecution) { + if (options['afterAdd']) { + for (var i = 0; i < nodesAdded.length; i++) + options['afterAdd'](nodesAdded[i].element, nodesAdded[i].index, nodesAdded[i].value); + } + if (options['beforeRemove']) { + for (var i = 0; i < nodesToDelete.length; i++) + options['beforeRemove'](nodesToDelete[i].element, nodesToDelete[i].index, nodesToDelete[i].value); + invokedBeforeRemoveCallback = true; + } + } + if (!invokedBeforeRemoveCallback && nodesToDelete.length) { + for (var i = 0; i < nodesToDelete.length; i++) { + var element = nodesToDelete[i].element; + if (element.parentNode) + element.parentNode.removeChild(element); + } + } + + // Store a copy of the array items we just considered so we can difference it next time + ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult); + } +})(); + +ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping); +ko.nativeTemplateEngine = function () { + this['allowTemplateRewriting'] = false; +} + +ko.nativeTemplateEngine.prototype = new ko.templateEngine(); +ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) { + var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly + templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null, + templateNodes = templateNodesFunc ? templateSource['nodes']() : null; + + if (templateNodes) { + return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes); + } else { + var templateText = templateSource['text'](); + return ko.utils.parseHtmlFragment(templateText); + } +}; + +ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine(); +ko.setTemplateEngine(ko.nativeTemplateEngine.instance); + +ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine); +(function() { + ko.jqueryTmplTemplateEngine = function () { + // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl + // doesn't expose a version number, so we have to infer it. + // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later, + // which KO internally refers to as version "2", so older versions are no longer detected. + var jQueryTmplVersion = this.jQueryTmplVersion = (function() { + if ((typeof(jQuery) == "undefined") || !(jQuery['tmpl'])) + return 0; + // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves. + try { + if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) { + // Since 1.0.0pre, custom tags should append markup to an array called "__" + return 2; // Final version of jquery.tmpl + } + } catch(ex) { /* Apparently not the version we were looking for */ } + + return 1; // Any older version that we don't support + })(); + + function ensureHasReferencedJQueryTemplates() { + if (jQueryTmplVersion < 2) + throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later."); + } + + function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) { + return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions); + } + + this['renderTemplateSource'] = function(templateSource, bindingContext, options) { + options = options || {}; + ensureHasReferencedJQueryTemplates(); + + // Ensure we have stored a precompiled version of this template (don't want to reparse on every render) + var precompiled = templateSource['data']('precompiled'); + if (!precompiled) { + var templateText = templateSource['text']() || ""; + // Wrap in "with($whatever.koBindingContext) { ... }" + templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}"; + + precompiled = jQuery['template'](null, templateText); + templateSource['data']('precompiled', precompiled); + } + + var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays + var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']); + + var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions); + resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work + + jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders + return resultNodes; + }; + + this['createJavaScriptEvaluatorBlock'] = function(script) { + return "{{ko_code ((function() { return " + script + " })()) }}"; + }; + + this['addTemplate'] = function(templateName, templateMarkup) { + document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "</script>"); + }; + + if (jQueryTmplVersion > 0) { + jQuery['tmpl']['tag']['ko_code'] = { + open: "__.push($1 || '');" + }; + jQuery['tmpl']['tag']['ko_with'] = { + open: "with($1) {", + close: "} " + }; + } + }; + + ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine(); + + // Use this one by default *only if jquery.tmpl is referenced* + var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine(); + if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0) + ko.setTemplateEngine(jqueryTmplTemplateEngineInstance); + + ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine); +})(); +}); +})(window,document,navigator); diff --git a/samples/OAuth2ProtectedWebApi/Scripts/knockout-2.1.0.js b/samples/OAuth2ProtectedWebApi/Scripts/knockout-2.1.0.js new file mode 100644 index 0000000..107026d --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/knockout-2.1.0.js @@ -0,0 +1,86 @@ +// Knockout JavaScript library v2.1.0 +// (c) Steven Sanderson - http://knockoutjs.com/ +// License: MIT (http://www.opensource.org/licenses/mit-license.php) + +(function(window,document,navigator,undefined){ +function m(w){throw w;}var n=void 0,p=!0,s=null,t=!1;function A(w){return function(){return w}};function E(w){function B(b,c,d){d&&c!==a.k.r(b)&&a.k.S(b,c);c!==a.k.r(b)&&a.a.va(b,"change")}var a="undefined"!==typeof w?w:{};a.b=function(b,c){for(var d=b.split("."),f=a,g=0;g<d.length-1;g++)f=f[d[g]];f[d[d.length-1]]=c};a.B=function(a,c,d){a[c]=d};a.version="2.1.0";a.b("version",a.version);a.a=new function(){function b(b,c){if("input"!==a.a.o(b)||!b.type||"click"!=c.toLowerCase())return t;var e=b.type;return"checkbox"==e||"radio"==e}var c=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,d={},f={};d[/Firefox\/2/i.test(navigator.userAgent)? +"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];d.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");for(var g in d){var e=d[g];if(e.length)for(var h=0,j=e.length;h<j;h++)f[e[h]]=g}var k={propertychange:p},i=function(){for(var a=3,b=document.createElement("div"),c=b.getElementsByTagName("i");b.innerHTML="<\!--[if gt IE "+ ++a+"]><i></i><![endif]--\>",c[0];);return 4<a?a:n}();return{Ca:["authenticity_token",/^__RequestVerificationToken(_.*)?$/], +v:function(a,b){for(var c=0,e=a.length;c<e;c++)b(a[c])},j:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var c=0,e=a.length;c<e;c++)if(a[c]===b)return c;return-1},ab:function(a,b,c){for(var e=0,f=a.length;e<f;e++)if(b.call(c,a[e]))return a[e];return s},ba:function(b,c){var e=a.a.j(b,c);0<=e&&b.splice(e,1)},za:function(b){for(var b=b||[],c=[],e=0,f=b.length;e<f;e++)0>a.a.j(c,b[e])&&c.push(b[e]);return c},T:function(a,b){for(var a=a||[],c=[], +e=0,f=a.length;e<f;e++)c.push(b(a[e]));return c},aa:function(a,b){for(var a=a||[],c=[],e=0,f=a.length;e<f;e++)b(a[e])&&c.push(a[e]);return c},N:function(a,b){if(b instanceof Array)a.push.apply(a,b);else for(var c=0,e=b.length;c<e;c++)a.push(b[c]);return a},extend:function(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a},ga:function(b){for(;b.firstChild;)a.removeNode(b.firstChild)},Ab:function(b){for(var b=a.a.L(b),c=document.createElement("div"),e=0,f=b.length;e<f;e++)a.F(b[e]), +c.appendChild(b[e]);return c},X:function(b,c){a.a.ga(b);if(c)for(var e=0,f=c.length;e<f;e++)b.appendChild(c[e])},Na:function(b,c){var e=b.nodeType?[b]:b;if(0<e.length){for(var f=e[0],d=f.parentNode,g=0,h=c.length;g<h;g++)d.insertBefore(c[g],f);g=0;for(h=e.length;g<h;g++)a.removeNode(e[g])}},Pa:function(a,b){0<=navigator.userAgent.indexOf("MSIE 6")?a.setAttribute("selected",b):a.selected=b},w:function(a){return(a||"").replace(c,"")},Ib:function(b,c){for(var e=[],f=(b||"").split(c),g=0,d=f.length;g< +d;g++){var h=a.a.w(f[g]);""!==h&&e.push(h)}return e},Hb:function(a,b){a=a||"";return b.length>a.length?t:a.substring(0,b.length)===b},eb:function(a,b){for(var c="return ("+a+")",e=0;e<b;e++)c="with(sc["+e+"]) { "+c+" } ";return new Function("sc",c)},kb:function(a,b){if(b.compareDocumentPosition)return 16==(b.compareDocumentPosition(a)&16);for(;a!=s;){if(a==b)return p;a=a.parentNode}return t},fa:function(b){return a.a.kb(b,b.ownerDocument)},o:function(a){return a&&a.tagName&&a.tagName.toLowerCase()}, +n:function(a,c,e){var f=i&&k[c];if(!f&&"undefined"!=typeof jQuery){if(b(a,c))var g=e,e=function(a,b){var c=this.checked;b&&(this.checked=b.fb!==p);g.call(this,a);this.checked=c};jQuery(a).bind(c,e)}else!f&&"function"==typeof a.addEventListener?a.addEventListener(c,e,t):"undefined"!=typeof a.attachEvent?a.attachEvent("on"+c,function(b){e.call(a,b)}):m(Error("Browser doesn't support addEventListener or attachEvent"))},va:function(a,c){(!a||!a.nodeType)&&m(Error("element must be a DOM node when calling triggerEvent")); +if("undefined"!=typeof jQuery){var e=[];b(a,c)&&e.push({fb:a.checked});jQuery(a).trigger(c,e)}else"function"==typeof document.createEvent?"function"==typeof a.dispatchEvent?(e=document.createEvent(f[c]||"HTMLEvents"),e.initEvent(c,p,p,window,0,0,0,0,0,t,t,t,t,0,a),a.dispatchEvent(e)):m(Error("The supplied element doesn't support dispatchEvent")):"undefined"!=typeof a.fireEvent?(b(a,c)&&(a.checked=a.checked!==p),a.fireEvent("on"+c)):m(Error("Browser doesn't support triggering events"))},d:function(b){return a.la(b)? +b():b},Ua:function(b,c,e){var f=(b.className||"").split(/\s+/),g=0<=a.a.j(f,c);if(e&&!g)b.className+=(f[0]?" ":"")+c;else if(g&&!e){e="";for(g=0;g<f.length;g++)f[g]!=c&&(e+=f[g]+" ");b.className=a.a.w(e)}},Qa:function(b,c){var e=a.a.d(c);if(e===s||e===n)e="";"innerText"in b?b.innerText=e:b.textContent=e;9<=i&&(b.style.display=b.style.display)},lb:function(a){if(9<=i){var b=a.style.width;a.style.width=0;a.style.width=b}},Eb:function(b,e){for(var b=a.a.d(b),e=a.a.d(e),c=[],f=b;f<=e;f++)c.push(f);return c}, +L:function(a){for(var b=[],e=0,c=a.length;e<c;e++)b.push(a[e]);return b},tb:6===i,ub:7===i,ja:i,Da:function(b,e){for(var c=a.a.L(b.getElementsByTagName("input")).concat(a.a.L(b.getElementsByTagName("textarea"))),f="string"==typeof e?function(a){return a.name===e}:function(a){return e.test(a.name)},g=[],d=c.length-1;0<=d;d--)f(c[d])&&g.push(c[d]);return g},Bb:function(b){return"string"==typeof b&&(b=a.a.w(b))?window.JSON&&window.JSON.parse?window.JSON.parse(b):(new Function("return "+b))():s},sa:function(b, +e,c){("undefined"==typeof JSON||"undefined"==typeof JSON.stringify)&&m(Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js"));return JSON.stringify(a.a.d(b),e,c)},Cb:function(b,e,c){var c=c||{},f=c.params||{},g=c.includeFields||this.Ca,d=b;if("object"==typeof b&&"form"===a.a.o(b))for(var d=b.action,h=g.length-1;0<=h;h--)for(var k=a.a.Da(b,g[h]), +j=k.length-1;0<=j;j--)f[k[j].name]=k[j].value;var e=a.a.d(e),i=document.createElement("form");i.style.display="none";i.action=d;i.method="post";for(var z in e)b=document.createElement("input"),b.name=z,b.value=a.a.sa(a.a.d(e[z])),i.appendChild(b);for(z in f)b=document.createElement("input"),b.name=z,b.value=f[z],i.appendChild(b);document.body.appendChild(i);c.submitter?c.submitter(i):i.submit();setTimeout(function(){i.parentNode.removeChild(i)},0)}}};a.b("utils",a.a);a.b("utils.arrayForEach",a.a.v); +a.b("utils.arrayFirst",a.a.ab);a.b("utils.arrayFilter",a.a.aa);a.b("utils.arrayGetDistinctValues",a.a.za);a.b("utils.arrayIndexOf",a.a.j);a.b("utils.arrayMap",a.a.T);a.b("utils.arrayPushAll",a.a.N);a.b("utils.arrayRemoveItem",a.a.ba);a.b("utils.extend",a.a.extend);a.b("utils.fieldsIncludedWithJsonPost",a.a.Ca);a.b("utils.getFormFields",a.a.Da);a.b("utils.postJson",a.a.Cb);a.b("utils.parseJson",a.a.Bb);a.b("utils.registerEventHandler",a.a.n);a.b("utils.stringifyJson",a.a.sa);a.b("utils.range",a.a.Eb); +a.b("utils.toggleDomNodeCssClass",a.a.Ua);a.b("utils.triggerEvent",a.a.va);a.b("utils.unwrapObservable",a.a.d);Function.prototype.bind||(Function.prototype.bind=function(a){var c=this,d=Array.prototype.slice.call(arguments),a=d.shift();return function(){return c.apply(a,d.concat(Array.prototype.slice.call(arguments)))}});a.a.f=new function(){var b=0,c="__ko__"+(new Date).getTime(),d={};return{get:function(b,c){var e=a.a.f.getAll(b,t);return e===n?n:e[c]},set:function(b,c,e){e===n&&a.a.f.getAll(b, +t)===n||(a.a.f.getAll(b,p)[c]=e)},getAll:function(a,g){var e=a[c];if(!(e&&"null"!==e)){if(!g)return;e=a[c]="ko"+b++;d[e]={}}return d[e]},clear:function(a){var b=a[c];b&&(delete d[b],a[c]=s)}}};a.b("utils.domData",a.a.f);a.b("utils.domData.clear",a.a.f.clear);a.a.G=new function(){function b(b,c){var f=a.a.f.get(b,d);f===n&&c&&(f=[],a.a.f.set(b,d,f));return f}function c(e){var f=b(e,t);if(f)for(var f=f.slice(0),d=0;d<f.length;d++)f[d](e);a.a.f.clear(e);"function"==typeof jQuery&&"function"==typeof jQuery.cleanData&& +jQuery.cleanData([e]);if(g[e.nodeType])for(f=e.firstChild;e=f;)f=e.nextSibling,8===e.nodeType&&c(e)}var d="__ko_domNodeDisposal__"+(new Date).getTime(),f={1:p,8:p,9:p},g={1:p,9:p};return{wa:function(a,c){"function"!=typeof c&&m(Error("Callback must be a function"));b(a,p).push(c)},Ma:function(c,f){var g=b(c,t);g&&(a.a.ba(g,f),0==g.length&&a.a.f.set(c,d,n))},F:function(b){if(f[b.nodeType]&&(c(b),g[b.nodeType])){var d=[];a.a.N(d,b.getElementsByTagName("*"));for(var b=0,j=d.length;b<j;b++)c(d[b])}}, +removeNode:function(b){a.F(b);b.parentNode&&b.parentNode.removeChild(b)}}};a.F=a.a.G.F;a.removeNode=a.a.G.removeNode;a.b("cleanNode",a.F);a.b("removeNode",a.removeNode);a.b("utils.domNodeDisposal",a.a.G);a.b("utils.domNodeDisposal.addDisposeCallback",a.a.G.wa);a.b("utils.domNodeDisposal.removeDisposeCallback",a.a.G.Ma);(function(){a.a.pa=function(b){var c;if("undefined"!=typeof jQuery){if((c=jQuery.clean([b]))&&c[0]){for(b=c[0];b.parentNode&&11!==b.parentNode.nodeType;)b=b.parentNode;b.parentNode&& +b.parentNode.removeChild(b)}}else{var d=a.a.w(b).toLowerCase();c=document.createElement("div");d=d.match(/^<(thead|tbody|tfoot)/)&&[1,"<table>","</table>"]||!d.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!d.indexOf("<td")||!d.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||[0,"",""];b="ignored<div>"+d[1]+b+d[2]+"</div>";for("function"==typeof window.innerShiv?c.appendChild(window.innerShiv(b)):c.innerHTML=b;d[0]--;)c=c.lastChild;c=a.a.L(c.lastChild.childNodes)}return c}; +a.a.Y=function(b,c){a.a.ga(b);if(c!==s&&c!==n)if("string"!=typeof c&&(c=c.toString()),"undefined"!=typeof jQuery)jQuery(b).html(c);else for(var d=a.a.pa(c),f=0;f<d.length;f++)b.appendChild(d[f])}})();a.b("utils.parseHtmlFragment",a.a.pa);a.b("utils.setHtml",a.a.Y);a.s=function(){function b(){return(4294967296*(1+Math.random())|0).toString(16).substring(1)}function c(b,g){if(b)if(8==b.nodeType){var e=a.s.Ja(b.nodeValue);e!=s&&g.push({jb:b,yb:e})}else if(1==b.nodeType)for(var e=0,d=b.childNodes,j=d.length;e< +j;e++)c(d[e],g)}var d={};return{na:function(a){"function"!=typeof a&&m(Error("You can only pass a function to ko.memoization.memoize()"));var c=b()+b();d[c]=a;return"<\!--[ko_memo:"+c+"]--\>"},Va:function(a,b){var c=d[a];c===n&&m(Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized."));try{return c.apply(s,b||[]),p}finally{delete d[a]}},Wa:function(b,d){var e=[];c(b,e);for(var h=0,j=e.length;h<j;h++){var k=e[h].jb,i=[k];d&&a.a.N(i,d);a.s.Va(e[h].yb,i);k.nodeValue="";k.parentNode&& +k.parentNode.removeChild(k)}},Ja:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:s}}}();a.b("memoization",a.s);a.b("memoization.memoize",a.s.na);a.b("memoization.unmemoize",a.s.Va);a.b("memoization.parseMemoText",a.s.Ja);a.b("memoization.unmemoizeDomNodeAndDescendants",a.s.Wa);a.Ba={throttle:function(b,c){b.throttleEvaluation=c;var d=s;return a.h({read:b,write:function(a){clearTimeout(d);d=setTimeout(function(){b(a)},c)}})},notify:function(b,c){b.equalityComparer="always"==c?A(t):a.m.fn.equalityComparer; +return b}};a.b("extenders",a.Ba);a.Sa=function(b,c,d){this.target=b;this.ca=c;this.ib=d;a.B(this,"dispose",this.A)};a.Sa.prototype.A=function(){this.sb=p;this.ib()};a.R=function(){this.u={};a.a.extend(this,a.R.fn);a.B(this,"subscribe",this.ta);a.B(this,"extend",this.extend);a.B(this,"getSubscriptionsCount",this.ob)};a.R.fn={ta:function(b,c,d){var d=d||"change",b=c?b.bind(c):b,f=new a.Sa(this,b,function(){a.a.ba(this.u[d],f)}.bind(this));this.u[d]||(this.u[d]=[]);this.u[d].push(f);return f},notifySubscribers:function(b, +c){c=c||"change";this.u[c]&&a.a.v(this.u[c].slice(0),function(a){a&&a.sb!==p&&a.ca(b)})},ob:function(){var a=0,c;for(c in this.u)this.u.hasOwnProperty(c)&&(a+=this.u[c].length);return a},extend:function(b){var c=this;if(b)for(var d in b){var f=a.Ba[d];"function"==typeof f&&(c=f(c,b[d]))}return c}};a.Ga=function(a){return"function"==typeof a.ta&&"function"==typeof a.notifySubscribers};a.b("subscribable",a.R);a.b("isSubscribable",a.Ga);a.U=function(){var b=[];return{bb:function(a){b.push({ca:a,Aa:[]})}, +end:function(){b.pop()},La:function(c){a.Ga(c)||m(Error("Only subscribable things can act as dependencies"));if(0<b.length){var d=b[b.length-1];0<=a.a.j(d.Aa,c)||(d.Aa.push(c),d.ca(c))}}}}();var G={undefined:p,"boolean":p,number:p,string:p};a.m=function(b){function c(){if(0<arguments.length){if(!c.equalityComparer||!c.equalityComparer(d,arguments[0]))c.I(),d=arguments[0],c.H();return this}a.U.La(c);return d}var d=b;a.R.call(c);c.H=function(){c.notifySubscribers(d)};c.I=function(){c.notifySubscribers(d, +"beforeChange")};a.a.extend(c,a.m.fn);a.B(c,"valueHasMutated",c.H);a.B(c,"valueWillMutate",c.I);return c};a.m.fn={equalityComparer:function(a,c){return a===s||typeof a in G?a===c:t}};var x=a.m.Db="__ko_proto__";a.m.fn[x]=a.m;a.ia=function(b,c){return b===s||b===n||b[x]===n?t:b[x]===c?p:a.ia(b[x],c)};a.la=function(b){return a.ia(b,a.m)};a.Ha=function(b){return"function"==typeof b&&b[x]===a.m||"function"==typeof b&&b[x]===a.h&&b.pb?p:t};a.b("observable",a.m);a.b("isObservable",a.la);a.b("isWriteableObservable", +a.Ha);a.Q=function(b){0==arguments.length&&(b=[]);b!==s&&(b!==n&&!("length"in b))&&m(Error("The argument passed when initializing an observable array must be an array, or null, or undefined."));var c=a.m(b);a.a.extend(c,a.Q.fn);return c};a.Q.fn={remove:function(a){for(var c=this(),d=[],f="function"==typeof a?a:function(c){return c===a},g=0;g<c.length;g++){var e=c[g];f(e)&&(0===d.length&&this.I(),d.push(e),c.splice(g,1),g--)}d.length&&this.H();return d},removeAll:function(b){if(b===n){var c=this(), +d=c.slice(0);this.I();c.splice(0,c.length);this.H();return d}return!b?[]:this.remove(function(c){return 0<=a.a.j(b,c)})},destroy:function(a){var c=this(),d="function"==typeof a?a:function(c){return c===a};this.I();for(var f=c.length-1;0<=f;f--)d(c[f])&&(c[f]._destroy=p);this.H()},destroyAll:function(b){return b===n?this.destroy(A(p)):!b?[]:this.destroy(function(c){return 0<=a.a.j(b,c)})},indexOf:function(b){var c=this();return a.a.j(c,b)},replace:function(a,c){var d=this.indexOf(a);0<=d&&(this.I(), +this()[d]=c,this.H())}};a.a.v("pop push reverse shift sort splice unshift".split(" "),function(b){a.Q.fn[b]=function(){var a=this();this.I();a=a[b].apply(a,arguments);this.H();return a}});a.a.v(["slice"],function(b){a.Q.fn[b]=function(){var a=this();return a[b].apply(a,arguments)}});a.b("observableArray",a.Q);a.h=function(b,c,d){function f(){a.a.v(v,function(a){a.A()});v=[]}function g(){var a=h.throttleEvaluation;a&&0<=a?(clearTimeout(x),x=setTimeout(e,a)):e()}function e(){if(!l)if(i&&w())u();else{l= +p;try{var b=a.a.T(v,function(a){return a.target});a.U.bb(function(c){var e;0<=(e=a.a.j(b,c))?b[e]=n:v.push(c.ta(g))});for(var e=q.call(c),f=b.length-1;0<=f;f--)b[f]&&v.splice(f,1)[0].A();i=p;h.notifySubscribers(k,"beforeChange");k=e}finally{a.U.end()}h.notifySubscribers(k);l=t}}function h(){if(0<arguments.length)j.apply(h,arguments);else return i||e(),a.U.La(h),k}function j(){"function"===typeof o?o.apply(c,arguments):m(Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters."))} +var k,i=t,l=t,q=b;q&&"object"==typeof q?(d=q,q=d.read):(d=d||{},q||(q=d.read));"function"!=typeof q&&m(Error("Pass a function that returns the value of the ko.computed"));var o=d.write;c||(c=d.owner);var v=[],u=f,r="object"==typeof d.disposeWhenNodeIsRemoved?d.disposeWhenNodeIsRemoved:s,w=d.disposeWhen||A(t);if(r){u=function(){a.a.G.Ma(r,arguments.callee);f()};a.a.G.wa(r,u);var y=w,w=function(){return!a.a.fa(r)||y()}}var x=s;h.nb=function(){return v.length};h.pb="function"===typeof d.write;h.A=function(){u()}; +a.R.call(h);a.a.extend(h,a.h.fn);d.deferEvaluation!==p&&e();a.B(h,"dispose",h.A);a.B(h,"getDependenciesCount",h.nb);return h};a.rb=function(b){return a.ia(b,a.h)};w=a.m.Db;a.h[w]=a.m;a.h.fn={};a.h.fn[w]=a.h;a.b("dependentObservable",a.h);a.b("computed",a.h);a.b("isComputed",a.rb);(function(){function b(a,g,e){e=e||new d;a=g(a);if(!("object"==typeof a&&a!==s&&a!==n&&!(a instanceof Date)))return a;var h=a instanceof Array?[]:{};e.save(a,h);c(a,function(c){var d=g(a[c]);switch(typeof d){case "boolean":case "number":case "string":case "function":h[c]= +d;break;case "object":case "undefined":var i=e.get(d);h[c]=i!==n?i:b(d,g,e)}});return h}function c(a,b){if(a instanceof Array){for(var c=0;c<a.length;c++)b(c);"function"==typeof a.toJSON&&b("toJSON")}else for(c in a)b(c)}function d(){var b=[],c=[];this.save=function(e,d){var j=a.a.j(b,e);0<=j?c[j]=d:(b.push(e),c.push(d))};this.get=function(e){e=a.a.j(b,e);return 0<=e?c[e]:n}}a.Ta=function(c){0==arguments.length&&m(Error("When calling ko.toJS, pass the object you want to convert."));return b(c,function(b){for(var c= +0;a.la(b)&&10>c;c++)b=b();return b})};a.toJSON=function(b,c,e){b=a.Ta(b);return a.a.sa(b,c,e)}})();a.b("toJS",a.Ta);a.b("toJSON",a.toJSON);(function(){a.k={r:function(b){switch(a.a.o(b)){case "option":return b.__ko__hasDomDataOptionValue__===p?a.a.f.get(b,a.c.options.oa):b.getAttribute("value");case "select":return 0<=b.selectedIndex?a.k.r(b.options[b.selectedIndex]):n;default:return b.value}},S:function(b,c){switch(a.a.o(b)){case "option":switch(typeof c){case "string":a.a.f.set(b,a.c.options.oa, +n);"__ko__hasDomDataOptionValue__"in b&&delete b.__ko__hasDomDataOptionValue__;b.value=c;break;default:a.a.f.set(b,a.c.options.oa,c),b.__ko__hasDomDataOptionValue__=p,b.value="number"===typeof c?c:""}break;case "select":for(var d=b.options.length-1;0<=d;d--)if(a.k.r(b.options[d])==c){b.selectedIndex=d;break}break;default:if(c===s||c===n)c="";b.value=c}}}})();a.b("selectExtensions",a.k);a.b("selectExtensions.readValue",a.k.r);a.b("selectExtensions.writeValue",a.k.S);a.g=function(){function b(a,b){for(var d= +s;a!=d;)d=a,a=a.replace(c,function(a,c){return b[c]});return a}var c=/\@ko_token_(\d+)\@/g,d=/^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$/i,f=["true","false"];return{D:[],W:function(c){var e=a.a.w(c);if(3>e.length)return[];"{"===e.charAt(0)&&(e=e.substring(1,e.length-1));for(var c=[],d=s,f,k=0;k<e.length;k++){var i=e.charAt(k);if(d===s)switch(i){case '"':case "'":case "/":d=k,f=i}else if(i==f&&"\\"!==e.charAt(k-1)){i=e.substring(d,k+1);c.push(i);var l="@ko_token_"+(c.length- +1)+"@",e=e.substring(0,d)+l+e.substring(k+1),k=k-(i.length-l.length),d=s}}f=d=s;for(var q=0,o=s,k=0;k<e.length;k++){i=e.charAt(k);if(d===s)switch(i){case "{":d=k;o=i;f="}";break;case "(":d=k;o=i;f=")";break;case "[":d=k,o=i,f="]"}i===o?q++:i===f&&(q--,0===q&&(i=e.substring(d,k+1),c.push(i),l="@ko_token_"+(c.length-1)+"@",e=e.substring(0,d)+l+e.substring(k+1),k-=i.length-l.length,d=s))}f=[];e=e.split(",");d=0;for(k=e.length;d<k;d++)q=e[d],o=q.indexOf(":"),0<o&&o<q.length-1?(i=q.substring(o+1),f.push({key:b(q.substring(0, +o),c),value:b(i,c)})):f.push({unknown:b(q,c)});return f},ka:function(b){for(var c="string"===typeof b?a.g.W(b):b,h=[],b=[],j,k=0;j=c[k];k++)if(0<h.length&&h.push(","),j.key){var i;a:{i=j.key;var l=a.a.w(i);switch(l.length&&l.charAt(0)){case "'":case '"':break a;default:i="'"+l+"'"}}j=j.value;h.push(i);h.push(":");h.push(j);l=a.a.w(j);if(0<=a.a.j(f,a.a.w(l).toLowerCase())?0:l.match(d)!==s)0<b.length&&b.push(", "),b.push(i+" : function(__ko_value) { "+j+" = __ko_value; }")}else j.unknown&&h.push(j.unknown); +c=h.join("");0<b.length&&(c=c+", '_ko_property_writers' : { "+b.join("")+" } ");return c},wb:function(b,c){for(var d=0;d<b.length;d++)if(a.a.w(b[d].key)==c)return p;return t},$:function(b,c,d,f,k){if(!b||!a.Ha(b)){if((b=c()._ko_property_writers)&&b[d])b[d](f)}else(!k||b()!==f)&&b(f)}}}();a.b("jsonExpressionRewriting",a.g);a.b("jsonExpressionRewriting.bindingRewriteValidators",a.g.D);a.b("jsonExpressionRewriting.parseObjectLiteral",a.g.W);a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson", +a.g.ka);(function(){function b(a){return 8==a.nodeType&&(g?a.text:a.nodeValue).match(e)}function c(a){return 8==a.nodeType&&(g?a.text:a.nodeValue).match(h)}function d(a,e){for(var d=a,f=1,g=[];d=d.nextSibling;){if(c(d)&&(f--,0===f))return g;g.push(d);b(d)&&f++}e||m(Error("Cannot find closing comment tag to match: "+a.nodeValue));return s}function f(a,b){var c=d(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:s}var g="<\!--test--\>"===document.createComment("test").text,e=g?/^<\!--\s*ko\s+(.*\:.*)\s*--\>$/: +/^\s*ko\s+(.*\:.*)\s*$/,h=g?/^<\!--\s*\/ko\s*--\>$/:/^\s*\/ko\s*$/,j={ul:p,ol:p};a.e={C:{},childNodes:function(a){return b(a)?d(a):a.childNodes},ha:function(c){if(b(c))for(var c=a.e.childNodes(c),e=0,d=c.length;e<d;e++)a.removeNode(c[e]);else a.a.ga(c)},X:function(c,e){if(b(c)){a.e.ha(c);for(var d=c.nextSibling,f=0,g=e.length;f<g;f++)d.parentNode.insertBefore(e[f],d)}else a.a.X(c,e)},Ka:function(a,c){b(a)?a.parentNode.insertBefore(c,a.nextSibling):a.firstChild?a.insertBefore(c,a.firstChild):a.appendChild(c)}, +Fa:function(a,c,e){b(a)?a.parentNode.insertBefore(c,e.nextSibling):e.nextSibling?a.insertBefore(c,e.nextSibling):a.appendChild(c)},firstChild:function(a){return!b(a)?a.firstChild:!a.nextSibling||c(a.nextSibling)?s:a.nextSibling},nextSibling:function(a){b(a)&&(a=f(a));return a.nextSibling&&c(a.nextSibling)?s:a.nextSibling},Xa:function(a){return(a=b(a))?a[1]:s},Ia:function(e){if(j[a.a.o(e)]){var d=e.firstChild;if(d){do if(1===d.nodeType){var g;g=d.firstChild;var h=s;if(g){do if(h)h.push(g);else if(b(g)){var o= +f(g,p);o?g=o:h=[g]}else c(g)&&(h=[g]);while(g=g.nextSibling)}if(g=h){h=d.nextSibling;for(o=0;o<g.length;o++)h?e.insertBefore(g[o],h):e.appendChild(g[o])}}while(d=d.nextSibling)}}}}})();a.b("virtualElements",a.e);a.b("virtualElements.allowedBindings",a.e.C);a.b("virtualElements.emptyNode",a.e.ha);a.b("virtualElements.insertAfter",a.e.Fa);a.b("virtualElements.prepend",a.e.Ka);a.b("virtualElements.setDomNodeChildren",a.e.X);(function(){a.J=function(){this.cb={}};a.a.extend(a.J.prototype,{nodeHasBindings:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind")!= +s;case 8:return a.e.Xa(b)!=s;default:return t}},getBindings:function(a,c){var d=this.getBindingsString(a,c);return d?this.parseBindingsString(d,c):s},getBindingsString:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind");case 8:return a.e.Xa(b);default:return s}},parseBindingsString:function(b,c){try{var d=c.$data,d="object"==typeof d&&d!=s?[d,c]:[c],f=d.length,g=this.cb,e=f+"_"+b,h;if(!(h=g[e])){var j=" { "+a.g.ka(b)+" } ";h=g[e]=a.a.eb(j,f)}return h(d)}catch(k){m(Error("Unable to parse bindings.\nMessage: "+ +k+";\nBindings value: "+b))}}});a.J.instance=new a.J})();a.b("bindingProvider",a.J);(function(){function b(b,d,e){for(var h=a.e.firstChild(d);d=h;)h=a.e.nextSibling(d),c(b,d,e)}function c(c,g,e){var h=p,j=1===g.nodeType;j&&a.e.Ia(g);if(j&&e||a.J.instance.nodeHasBindings(g))h=d(g,s,c,e).Gb;h&&b(c,g,!j)}function d(b,c,e,d){function j(a){return function(){return l[a]}}function k(){return l}var i=0,l,q;a.h(function(){var o=e&&e instanceof a.z?e:new a.z(a.a.d(e)),v=o.$data;d&&a.Ra(b,o);if(l=("function"== +typeof c?c():c)||a.J.instance.getBindings(b,o)){if(0===i){i=1;for(var u in l){var r=a.c[u];r&&8===b.nodeType&&!a.e.C[u]&&m(Error("The binding '"+u+"' cannot be used with virtual elements"));if(r&&"function"==typeof r.init&&(r=(0,r.init)(b,j(u),k,v,o))&&r.controlsDescendantBindings)q!==n&&m(Error("Multiple bindings ("+q+" and "+u+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.")),q=u}i=2}if(2===i)for(u in l)(r=a.c[u])&&"function"== +typeof r.update&&(0,r.update)(b,j(u),k,v,o)}},s,{disposeWhenNodeIsRemoved:b});return{Gb:q===n}}a.c={};a.z=function(b,c){c?(a.a.extend(this,c),this.$parentContext=c,this.$parent=c.$data,this.$parents=(c.$parents||[]).slice(0),this.$parents.unshift(this.$parent)):(this.$parents=[],this.$root=b);this.$data=b};a.z.prototype.createChildContext=function(b){return new a.z(b,this)};a.z.prototype.extend=function(b){var c=a.a.extend(new a.z,this);return a.a.extend(c,b)};a.Ra=function(b,c){if(2==arguments.length)a.a.f.set(b, +"__ko_bindingContext__",c);else return a.a.f.get(b,"__ko_bindingContext__")};a.ya=function(b,c,e){1===b.nodeType&&a.e.Ia(b);return d(b,c,e,p)};a.Ya=function(a,c){(1===c.nodeType||8===c.nodeType)&&b(a,c,p)};a.xa=function(a,b){b&&(1!==b.nodeType&&8!==b.nodeType)&&m(Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"));b=b||window.document.body;c(a,b,p)};a.ea=function(b){switch(b.nodeType){case 1:case 8:var c=a.Ra(b);if(c)return c;if(b.parentNode)return a.ea(b.parentNode)}}; +a.hb=function(b){return(b=a.ea(b))?b.$data:n};a.b("bindingHandlers",a.c);a.b("applyBindings",a.xa);a.b("applyBindingsToDescendants",a.Ya);a.b("applyBindingsToNode",a.ya);a.b("contextFor",a.ea);a.b("dataFor",a.hb)})();a.a.v(["click"],function(b){a.c[b]={init:function(c,d,f,g){return a.c.event.init.call(this,c,function(){var a={};a[b]=d();return a},f,g)}}});a.c.event={init:function(b,c,d,f){var g=c()||{},e;for(e in g)(function(){var g=e;"string"==typeof g&&a.a.n(b,g,function(b){var e,i=c()[g];if(i){var l= +d();try{var q=a.a.L(arguments);q.unshift(f);e=i.apply(f,q)}finally{e!==p&&(b.preventDefault?b.preventDefault():b.returnValue=t)}l[g+"Bubble"]===t&&(b.cancelBubble=p,b.stopPropagation&&b.stopPropagation())}})})()}};a.c.submit={init:function(b,c,d,f){"function"!=typeof c()&&m(Error("The value for a submit binding must be a function"));a.a.n(b,"submit",function(a){var e,d=c();try{e=d.call(f,b)}finally{e!==p&&(a.preventDefault?a.preventDefault():a.returnValue=t)}})}};a.c.visible={update:function(b,c){var d= +a.a.d(c()),f="none"!=b.style.display;d&&!f?b.style.display="":!d&&f&&(b.style.display="none")}};a.c.enable={update:function(b,c){var d=a.a.d(c());d&&b.disabled?b.removeAttribute("disabled"):!d&&!b.disabled&&(b.disabled=p)}};a.c.disable={update:function(b,c){a.c.enable.update(b,function(){return!a.a.d(c())})}};a.c.value={init:function(b,c,d){function f(){var e=c(),f=a.k.r(b);a.g.$(e,d,"value",f,p)}var g=["change"],e=d().valueUpdate;e&&("string"==typeof e&&(e=[e]),a.a.N(g,e),g=a.a.za(g));if(a.a.ja&& +("input"==b.tagName.toLowerCase()&&"text"==b.type&&"off"!=b.autocomplete&&(!b.form||"off"!=b.form.autocomplete))&&-1==a.a.j(g,"propertychange")){var h=t;a.a.n(b,"propertychange",function(){h=p});a.a.n(b,"blur",function(){if(h){h=t;f()}})}a.a.v(g,function(c){var e=f;if(a.a.Hb(c,"after")){e=function(){setTimeout(f,0)};c=c.substring(5)}a.a.n(b,c,e)})},update:function(b,c){var d="select"===a.a.o(b),f=a.a.d(c()),g=a.k.r(b),e=f!=g;0===f&&(0!==g&&"0"!==g)&&(e=p);e&&(g=function(){a.k.S(b,f)},g(),d&&setTimeout(g, +0));d&&0<b.length&&B(b,f,t)}};a.c.options={update:function(b,c,d){"select"!==a.a.o(b)&&m(Error("options binding applies only to SELECT elements"));for(var f=0==b.length,g=a.a.T(a.a.aa(b.childNodes,function(b){return b.tagName&&"option"===a.a.o(b)&&b.selected}),function(b){return a.k.r(b)||b.innerText||b.textContent}),e=b.scrollTop,h=a.a.d(c());0<b.length;)a.F(b.options[0]),b.remove(0);if(h){d=d();"number"!=typeof h.length&&(h=[h]);if(d.optionsCaption){var j=document.createElement("option");a.a.Y(j, +d.optionsCaption);a.k.S(j,n);b.appendChild(j)}for(var c=0,k=h.length;c<k;c++){var j=document.createElement("option"),i="string"==typeof d.optionsValue?h[c][d.optionsValue]:h[c],i=a.a.d(i);a.k.S(j,i);var l=d.optionsText,i="function"==typeof l?l(h[c]):"string"==typeof l?h[c][l]:i;if(i===s||i===n)i="";a.a.Qa(j,i);b.appendChild(j)}h=b.getElementsByTagName("option");c=j=0;for(k=h.length;c<k;c++)0<=a.a.j(g,a.k.r(h[c]))&&(a.a.Pa(h[c],p),j++);b.scrollTop=e;f&&"value"in d&&B(b,a.a.d(d.value),p);a.a.lb(b)}}}; +a.c.options.oa="__ko.optionValueDomData__";a.c.selectedOptions={Ea:function(b){for(var c=[],b=b.childNodes,d=0,f=b.length;d<f;d++){var g=b[d],e=a.a.o(g);"option"==e&&g.selected?c.push(a.k.r(g)):"optgroup"==e&&(g=a.c.selectedOptions.Ea(g),Array.prototype.splice.apply(c,[c.length,0].concat(g)))}return c},init:function(b,c,d){a.a.n(b,"change",function(){var b=c(),g=a.c.selectedOptions.Ea(this);a.g.$(b,d,"value",g)})},update:function(b,c){"select"!=a.a.o(b)&&m(Error("values binding applies only to SELECT elements")); +var d=a.a.d(c());if(d&&"number"==typeof d.length)for(var f=b.childNodes,g=0,e=f.length;g<e;g++){var h=f[g];"option"===a.a.o(h)&&a.a.Pa(h,0<=a.a.j(d,a.k.r(h)))}}};a.c.text={update:function(b,c){a.a.Qa(b,c())}};a.c.html={init:function(){return{controlsDescendantBindings:p}},update:function(b,c){var d=a.a.d(c());a.a.Y(b,d)}};a.c.css={update:function(b,c){var d=a.a.d(c()||{}),f;for(f in d)if("string"==typeof f){var g=a.a.d(d[f]);a.a.Ua(b,f,g)}}};a.c.style={update:function(b,c){var d=a.a.d(c()||{}),f; +for(f in d)if("string"==typeof f){var g=a.a.d(d[f]);b.style[f]=g||""}}};a.c.uniqueName={init:function(b,c){c()&&(b.name="ko_unique_"+ ++a.c.uniqueName.gb,(a.a.tb||a.a.ub)&&b.mergeAttributes(document.createElement("<input name='"+b.name+"'/>"),t))}};a.c.uniqueName.gb=0;a.c.checked={init:function(b,c,d){a.a.n(b,"click",function(){var f;if("checkbox"==b.type)f=b.checked;else if("radio"==b.type&&b.checked)f=b.value;else return;var g=c();"checkbox"==b.type&&a.a.d(g)instanceof Array?(f=a.a.j(a.a.d(g),b.value), +b.checked&&0>f?g.push(b.value):!b.checked&&0<=f&&g.splice(f,1)):a.g.$(g,d,"checked",f,p)});"radio"==b.type&&!b.name&&a.c.uniqueName.init(b,A(p))},update:function(b,c){var d=a.a.d(c());"checkbox"==b.type?b.checked=d instanceof Array?0<=a.a.j(d,b.value):d:"radio"==b.type&&(b.checked=b.value==d)}};var F={"class":"className","for":"htmlFor"};a.c.attr={update:function(b,c){var d=a.a.d(c())||{},f;for(f in d)if("string"==typeof f){var g=a.a.d(d[f]),e=g===t||g===s||g===n;e&&b.removeAttribute(f);8>=a.a.ja&& +f in F?(f=F[f],e?b.removeAttribute(f):b[f]=g):e||b.setAttribute(f,g.toString())}}};a.c.hasfocus={init:function(b,c,d){function f(b){var e=c();a.g.$(e,d,"hasfocus",b,p)}a.a.n(b,"focus",function(){f(p)});a.a.n(b,"focusin",function(){f(p)});a.a.n(b,"blur",function(){f(t)});a.a.n(b,"focusout",function(){f(t)})},update:function(b,c){var d=a.a.d(c());d?b.focus():b.blur();a.a.va(b,d?"focusin":"focusout")}};a.c["with"]={p:function(b){return function(){var c=b();return{"if":c,data:c,templateEngine:a.q.K}}}, +init:function(b,c){return a.c.template.init(b,a.c["with"].p(c))},update:function(b,c,d,f,g){return a.c.template.update(b,a.c["with"].p(c),d,f,g)}};a.g.D["with"]=t;a.e.C["with"]=p;a.c["if"]={p:function(b){return function(){return{"if":b(),templateEngine:a.q.K}}},init:function(b,c){return a.c.template.init(b,a.c["if"].p(c))},update:function(b,c,d,f,g){return a.c.template.update(b,a.c["if"].p(c),d,f,g)}};a.g.D["if"]=t;a.e.C["if"]=p;a.c.ifnot={p:function(b){return function(){return{ifnot:b(),templateEngine:a.q.K}}}, +init:function(b,c){return a.c.template.init(b,a.c.ifnot.p(c))},update:function(b,c,d,f,g){return a.c.template.update(b,a.c.ifnot.p(c),d,f,g)}};a.g.D.ifnot=t;a.e.C.ifnot=p;a.c.foreach={p:function(b){return function(){var c=a.a.d(b());return!c||"number"==typeof c.length?{foreach:c,templateEngine:a.q.K}:{foreach:c.data,includeDestroyed:c.includeDestroyed,afterAdd:c.afterAdd,beforeRemove:c.beforeRemove,afterRender:c.afterRender,templateEngine:a.q.K}}},init:function(b,c){return a.c.template.init(b,a.c.foreach.p(c))}, +update:function(b,c,d,f,g){return a.c.template.update(b,a.c.foreach.p(c),d,f,g)}};a.g.D.foreach=t;a.e.C.foreach=p;a.t=function(){};a.t.prototype.renderTemplateSource=function(){m(Error("Override renderTemplateSource"))};a.t.prototype.createJavaScriptEvaluatorBlock=function(){m(Error("Override createJavaScriptEvaluatorBlock"))};a.t.prototype.makeTemplateSource=function(b,c){if("string"==typeof b){var c=c||document,d=c.getElementById(b);d||m(Error("Cannot find template with ID "+b));return new a.l.i(d)}if(1== +b.nodeType||8==b.nodeType)return new a.l.M(b);m(Error("Unknown template type: "+b))};a.t.prototype.renderTemplate=function(a,c,d,f){return this.renderTemplateSource(this.makeTemplateSource(a,f),c,d)};a.t.prototype.isTemplateRewritten=function(a,c){return this.allowTemplateRewriting===t||!(c&&c!=document)&&this.V&&this.V[a]?p:this.makeTemplateSource(a,c).data("isRewritten")};a.t.prototype.rewriteTemplate=function(a,c,d){var f=this.makeTemplateSource(a,d),c=c(f.text());f.text(c);f.data("isRewritten", +p);!(d&&d!=document)&&"string"==typeof a&&(this.V=this.V||{},this.V[a]=p)};a.b("templateEngine",a.t);a.Z=function(){function b(b,c,e){for(var b=a.g.W(b),d=a.g.D,j=0;j<b.length;j++){var k=b[j].key;if(d.hasOwnProperty(k)){var i=d[k];"function"===typeof i?(k=i(b[j].value))&&m(Error(k)):i||m(Error("This template engine does not support the '"+k+"' binding within its templates"))}}b="ko.templateRewriting.applyMemoizedBindingsToNextSibling(function() { return (function() { return { "+a.g.ka(b)+ +" } })() })";return e.createJavaScriptEvaluatorBlock(b)+c}var c=/(<[a-z]+\d*(\s+(?!data-bind=)[a-z0-9\-]+(=(\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind=(["'])([\s\S]*?)\5/gi,d=/<\!--\s*ko\b\s*([\s\S]*?)\s*--\>/g;return{mb:function(b,c,e){c.isTemplateRewritten(b,e)||c.rewriteTemplate(b,function(b){return a.Z.zb(b,c)},e)},zb:function(a,g){return a.replace(c,function(a,c,d,f,i,l,q){return b(q,c,g)}).replace(d,function(a,c){return b(c,"<\!-- ko --\>",g)})},Za:function(b){return a.s.na(function(c, +e){c.nextSibling&&a.ya(c.nextSibling,b,e)})}}}();a.b("templateRewriting",a.Z);a.b("templateRewriting.applyMemoizedBindingsToNextSibling",a.Z.Za);(function(){a.l={};a.l.i=function(a){this.i=a};a.l.i.prototype.text=function(){var b=a.a.o(this.i),b="script"===b?"text":"textarea"===b?"value":"innerHTML";if(0==arguments.length)return this.i[b];var c=arguments[0];"innerHTML"===b?a.a.Y(this.i,c):this.i[b]=c};a.l.i.prototype.data=function(b){if(1===arguments.length)return a.a.f.get(this.i,"templateSourceData_"+ +b);a.a.f.set(this.i,"templateSourceData_"+b,arguments[1])};a.l.M=function(a){this.i=a};a.l.M.prototype=new a.l.i;a.l.M.prototype.text=function(){if(0==arguments.length){var b=a.a.f.get(this.i,"__ko_anon_template__")||{};b.ua===n&&b.da&&(b.ua=b.da.innerHTML);return b.ua}a.a.f.set(this.i,"__ko_anon_template__",{ua:arguments[0]})};a.l.i.prototype.nodes=function(){if(0==arguments.length)return(a.a.f.get(this.i,"__ko_anon_template__")||{}).da;a.a.f.set(this.i,"__ko_anon_template__",{da:arguments[0]})}; +a.b("templateSources",a.l);a.b("templateSources.domElement",a.l.i);a.b("templateSources.anonymousTemplate",a.l.M)})();(function(){function b(b,c,d){for(var f,c=a.e.nextSibling(c);b&&(f=b)!==c;)b=a.e.nextSibling(f),(1===f.nodeType||8===f.nodeType)&&d(f)}function c(c,d){if(c.length){var f=c[0],g=c[c.length-1];b(f,g,function(b){a.xa(d,b)});b(f,g,function(b){a.s.Wa(b,[d])})}}function d(a){return a.nodeType?a:0<a.length?a[0]:s}function f(b,f,j,k,i){var i=i||{},l=b&&d(b),l=l&&l.ownerDocument,q=i.templateEngine|| +g;a.Z.mb(j,q,l);j=q.renderTemplate(j,k,i,l);("number"!=typeof j.length||0<j.length&&"number"!=typeof j[0].nodeType)&&m(Error("Template engine must return an array of DOM nodes"));l=t;switch(f){case "replaceChildren":a.e.X(b,j);l=p;break;case "replaceNode":a.a.Na(b,j);l=p;break;case "ignoreTargetNode":break;default:m(Error("Unknown renderMode: "+f))}l&&(c(j,k),i.afterRender&&i.afterRender(j,k.$data));return j}var g;a.ra=function(b){b!=n&&!(b instanceof a.t)&&m(Error("templateEngine must inherit from ko.templateEngine")); +g=b};a.qa=function(b,c,j,k,i){j=j||{};(j.templateEngine||g)==n&&m(Error("Set a template engine before calling renderTemplate"));i=i||"replaceChildren";if(k){var l=d(k);return a.h(function(){var g=c&&c instanceof a.z?c:new a.z(a.a.d(c)),o="function"==typeof b?b(g.$data):b,g=f(k,i,o,g,j);"replaceNode"==i&&(k=g,l=d(k))},s,{disposeWhen:function(){return!l||!a.a.fa(l)},disposeWhenNodeIsRemoved:l&&"replaceNode"==i?l.parentNode:l})}return a.s.na(function(d){a.qa(b,c,j,d,"replaceNode")})};a.Fb=function(b, +d,g,k,i){function l(a,b){c(b,o);g.afterRender&&g.afterRender(b,a)}function q(c,d){var h="function"==typeof b?b(c):b;o=i.createChildContext(a.a.d(c));o.$index=d;return f(s,"ignoreTargetNode",h,o,g)}var o;return a.h(function(){var b=a.a.d(d)||[];"undefined"==typeof b.length&&(b=[b]);b=a.a.aa(b,function(b){return g.includeDestroyed||b===n||b===s||!a.a.d(b._destroy)});a.a.Oa(k,b,q,g,l)},s,{disposeWhenNodeIsRemoved:k})};a.c.template={init:function(b,c){var d=a.a.d(c());if("string"!=typeof d&&!d.name&& +(1==b.nodeType||8==b.nodeType))d=1==b.nodeType?b.childNodes:a.e.childNodes(b),d=a.a.Ab(d),(new a.l.M(b)).nodes(d);return{controlsDescendantBindings:p}},update:function(b,c,d,f,g){c=a.a.d(c());f=p;"string"==typeof c?d=c:(d=c.name,"if"in c&&(f=f&&a.a.d(c["if"])),"ifnot"in c&&(f=f&&!a.a.d(c.ifnot)));var l=s;"object"===typeof c&&"foreach"in c?l=a.Fb(d||b,f&&c.foreach||[],c,b,g):f?(g="object"==typeof c&&"data"in c?g.createChildContext(a.a.d(c.data)):g,l=a.qa(d||b,g,c,b)):a.e.ha(b);g=l;(c=a.a.f.get(b,"__ko__templateSubscriptionDomDataKey__"))&& +"function"==typeof c.A&&c.A();a.a.f.set(b,"__ko__templateSubscriptionDomDataKey__",g)}};a.g.D.template=function(b){b=a.g.W(b);return 1==b.length&&b[0].unknown||a.g.wb(b,"name")?s:"This template engine does not support anonymous templates nested within its templates"};a.e.C.template=p})();a.b("setTemplateEngine",a.ra);a.b("renderTemplate",a.qa);(function(){a.a.O=function(b,c,d){if(d===n)return a.a.O(b,c,1)||a.a.O(b,c,10)||a.a.O(b,c,Number.MAX_VALUE);for(var b=b||[],c=c||[],f=b,g=c,e=[],h=0;h<=g.length;h++)e[h]= +[];for(var h=0,j=Math.min(f.length,d);h<=j;h++)e[0][h]=h;h=1;for(j=Math.min(g.length,d);h<=j;h++)e[h][0]=h;for(var j=f.length,k,i=g.length,h=1;h<=j;h++){k=Math.max(1,h-d);for(var l=Math.min(i,h+d);k<=l;k++)e[k][h]=f[h-1]===g[k-1]?e[k-1][h-1]:Math.min(e[k-1][h]===n?Number.MAX_VALUE:e[k-1][h]+1,e[k][h-1]===n?Number.MAX_VALUE:e[k][h-1]+1)}d=b.length;f=c.length;g=[];h=e[f][d];if(h===n)e=s;else{for(;0<d||0<f;){j=e[f][d];i=0<f?e[f-1][d]:h+1;l=0<d?e[f][d-1]:h+1;k=0<f&&0<d?e[f-1][d-1]:h+1;if(i===n||i<j-1)i= +h+1;if(l===n||l<j-1)l=h+1;k<j-1&&(k=h+1);i<=l&&i<k?(g.push({status:"added",value:c[f-1]}),f--):(l<i&&l<k?g.push({status:"deleted",value:b[d-1]}):(g.push({status:"retained",value:b[d-1]}),f--),d--)}e=g.reverse()}return e}})();a.b("utils.compareArrays",a.a.O);(function(){function b(a){if(2<a.length){for(var b=a[0],c=a[a.length-1],e=[b];b!==c;){b=b.nextSibling;if(!b)return;e.push(b)}Array.prototype.splice.apply(a,[0,a.length].concat(e))}}function c(c,f,g,e,h){var j=[],c=a.h(function(){var c=f(g,h)|| +[];0<j.length&&(b(j),a.a.Na(j,c),e&&e(g,c));j.splice(0,j.length);a.a.N(j,c)},s,{disposeWhenNodeIsRemoved:c,disposeWhen:function(){return 0==j.length||!a.a.fa(j[0])}});return{xb:j,h:c}}a.a.Oa=function(d,f,g,e,h){for(var f=f||[],e=e||{},j=a.a.f.get(d,"setDomNodeChildrenFromArrayMapping_lastMappingResult")===n,k=a.a.f.get(d,"setDomNodeChildrenFromArrayMapping_lastMappingResult")||[],i=a.a.T(k,function(a){return a.$a}),l=a.a.O(i,f),f=[],q=0,o=[],v=0,i=[],u=s,r=0,w=l.length;r<w;r++)switch(l[r].status){case "retained":var y= +k[q];y.qb(v);v=f.push(y);0<y.P.length&&(u=y.P[y.P.length-1]);q++;break;case "deleted":k[q].h.A();b(k[q].P);a.a.v(k[q].P,function(a){o.push({element:a,index:r,value:l[r].value});u=a});q++;break;case "added":for(var y=l[r].value,x=a.m(v),v=c(d,g,y,h,x),C=v.xb,v=f.push({$a:l[r].value,P:C,h:v.h,qb:x}),z=0,B=C.length;z<B;z++){var D=C[z];i.push({element:D,index:r,value:l[r].value});u==s?a.e.Ka(d,D):a.e.Fa(d,D,u);u=D}h&&h(y,C,x)}a.a.v(o,function(b){a.F(b.element)});g=t;if(!j){if(e.afterAdd)for(r=0;r<i.length;r++)e.afterAdd(i[r].element, +i[r].index,i[r].value);if(e.beforeRemove){for(r=0;r<o.length;r++)e.beforeRemove(o[r].element,o[r].index,o[r].value);g=p}}if(!g&&o.length)for(r=0;r<o.length;r++)e=o[r].element,e.parentNode&&e.parentNode.removeChild(e);a.a.f.set(d,"setDomNodeChildrenFromArrayMapping_lastMappingResult",f)}})();a.b("utils.setDomNodeChildrenFromArrayMapping",a.a.Oa);a.q=function(){this.allowTemplateRewriting=t};a.q.prototype=new a.t;a.q.prototype.renderTemplateSource=function(b){var c=!(9>a.a.ja)&&b.nodes?b.nodes():s; +if(c)return a.a.L(c.cloneNode(p).childNodes);b=b.text();return a.a.pa(b)};a.q.K=new a.q;a.ra(a.q.K);a.b("nativeTemplateEngine",a.q);(function(){a.ma=function(){var a=this.vb=function(){if("undefined"==typeof jQuery||!jQuery.tmpl)return 0;try{if(0<=jQuery.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,f,g){g=g||{};2>a&&m(Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later."));var e=b.data("precompiled"); +e||(e=b.text()||"",e=jQuery.template(s,"{{ko_with $item.koBindingContext}}"+e+"{{/ko_with}}"),b.data("precompiled",e));b=[f.$data];f=jQuery.extend({koBindingContext:f},g.templateOptions);f=jQuery.tmpl(e,b,f);f.appendTo(document.createElement("div"));jQuery.fragments={};return f};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){document.write("<script type='text/html' id='"+a+"'>"+b+"<\/script>")};0<a&&(jQuery.tmpl.tag.ko_code= +{open:"__.push($1 || '');"},jQuery.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};a.ma.prototype=new a.t;var b=new a.ma;0<b.vb&&a.ra(b);a.b("jqueryTmplTemplateEngine",a.ma)})()}"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?E(module.exports||exports):"function"===typeof define&&define.amd?define(["exports"],E):E(window.ko={});p; +})(window,document,navigator); diff --git a/samples/OAuth2ProtectedWebApi/Scripts/modernizr-2.5.3.js b/samples/OAuth2ProtectedWebApi/Scripts/modernizr-2.5.3.js new file mode 100644 index 0000000..c1a6a9a --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Scripts/modernizr-2.5.3.js @@ -0,0 +1,1265 @@ +/*! + * Modernizr v2.5.3 + * www.modernizr.com + * + * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton + * Available under the BSD and MIT licenses: www.modernizr.com/license/ + */ + +/* + * Modernizr tests which native CSS3 and HTML5 features are available in + * the current UA and makes the results available to you in two ways: + * as properties on a global Modernizr object, and as classes on the + * <html> element. This information allows you to progressively enhance + * your pages with a granular level of control over the experience. + * + * Modernizr has an optional (not included) conditional resource loader + * called Modernizr.load(), based on Yepnope.js (yepnopejs.com). + * To get a build that includes Modernizr.load(), as well as choosing + * which tests to include, go to www.modernizr.com/download/ + * + * Authors Faruk Ates, Paul Irish, Alex Sexton + * Contributors Ryan Seddon, Ben Alman + */ + +window.Modernizr = (function( window, document, undefined ) { + + var version = '2.5.3', + + Modernizr = {}, + + // option for enabling the HTML classes to be added + enableClasses = true, + + docElement = document.documentElement, + + /** + * Create our "modernizr" element that we do most feature tests on. + */ + mod = 'modernizr', + modElem = document.createElement(mod), + mStyle = modElem.style, + + /** + * Create the input element for various Web Forms feature tests. + */ + inputElem = document.createElement('input'), + + smile = ':)', + + toString = {}.toString, + + // List of property values to set for css tests. See ticket #21 + prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), + + // Following spec is to expose vendor-specific style properties as: + // elem.style.WebkitBorderRadius + // and the following would be incorrect: + // elem.style.webkitBorderRadius + + // Webkit ghosts their properties in lowercase but Opera & Moz do not. + // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+ + // erik.eae.net/archives/2008/03/10/21.48.10/ + + // More here: github.com/Modernizr/Modernizr/issues/issue/21 + omPrefixes = 'Webkit Moz O ms', + + cssomPrefixes = omPrefixes.split(' '), + + domPrefixes = omPrefixes.toLowerCase().split(' '), + + ns = {'svg': 'http://www.w3.org/2000/svg'}, + + tests = {}, + inputs = {}, + attrs = {}, + + classes = [], + + slice = classes.slice, + + featureName, // used in testing loop + + + // Inject element with style element and some CSS rules + injectElementWithStyles = function( rule, callback, nodes, testnames ) { + + var style, ret, node, + div = document.createElement('div'), + // After page load injecting a fake body doesn't work so check if body exists + body = document.body, + // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it. + fakeBody = body ? body : document.createElement('body'); + + if ( parseInt(nodes, 10) ) { + // In order not to give false positives we create a node for each test + // This also allows the method to scale for unspecified uses + while ( nodes-- ) { + node = document.createElement('div'); + node.id = testnames ? testnames[nodes] : mod + (nodes + 1); + div.appendChild(node); + } + } + + // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed + // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element + // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements. + // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx + // Documents served as xml will throw if using ­ so use xml friendly encoded version. See issue #277 + style = ['­','<style>', rule, '</style>'].join(''); + div.id = mod; + // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. + // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 + fakeBody.innerHTML += style; + fakeBody.appendChild(div); + if(!body){ + //avoid crashing IE8, if background image is used + fakeBody.style.background = ""; + docElement.appendChild(fakeBody); + } + + ret = callback(div, rule); + // If this is done after page load we don't want to remove the body so check if body exists + !body ? fakeBody.parentNode.removeChild(fakeBody) : div.parentNode.removeChild(div); + + return !!ret; + + }, + + + // adapted from matchMedia polyfill + // by Scott Jehl and Paul Irish + // gist.github.com/786768 + testMediaQuery = function( mq ) { + + var matchMedia = window.matchMedia || window.msMatchMedia; + if ( matchMedia ) { + return matchMedia(mq).matches; + } + + var bool; + + injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) { + bool = (window.getComputedStyle ? + getComputedStyle(node, null) : + node.currentStyle)['position'] == 'absolute'; + }); + + return bool; + + }, + + + /** + * isEventSupported determines if a given element supports the given event + * function from yura.thinkweb2.com/isEventSupported/ + */ + isEventSupported = (function() { + + var TAGNAMES = { + 'select': 'input', 'change': 'input', + 'submit': 'form', 'reset': 'form', + 'error': 'img', 'load': 'img', 'abort': 'img' + }; + + function isEventSupported( eventName, element ) { + + element = element || document.createElement(TAGNAMES[eventName] || 'div'); + eventName = 'on' + eventName; + + // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those + var isSupported = eventName in element; + + if ( !isSupported ) { + // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element + if ( !element.setAttribute ) { + element = document.createElement('div'); + } + if ( element.setAttribute && element.removeAttribute ) { + element.setAttribute(eventName, ''); + isSupported = is(element[eventName], 'function'); + + // If property was created, "remove it" (by setting value to `undefined`) + if ( !is(element[eventName], 'undefined') ) { + element[eventName] = undefined; + } + element.removeAttribute(eventName); + } + } + + element = null; + return isSupported; + } + return isEventSupported; + })(); + + // hasOwnProperty shim by kangax needed for Safari 2.0 support + var _hasOwnProperty = ({}).hasOwnProperty, hasOwnProperty; + if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { + hasOwnProperty = function (object, property) { + return _hasOwnProperty.call(object, property); + }; + } + else { + hasOwnProperty = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */ + return ((property in object) && is(object.constructor.prototype[property], 'undefined')); + }; + } + + // Taken from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js + // ES-5 15.3.4.5 + // http://es5.github.com/#x15.3.4.5 + + if (!Function.prototype.bind) { + + Function.prototype.bind = function bind(that) { + + var target = this; + + if (typeof target != "function") { + throw new TypeError(); + } + + var args = slice.call(arguments, 1), + bound = function () { + + if (this instanceof bound) { + + var F = function(){}; + F.prototype = target.prototype; + var self = new F; + + var result = target.apply( + self, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return self; + + } else { + + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + + } + + }; + + return bound; + }; + } + + /** + * setCss applies given styles to the Modernizr DOM node. + */ + function setCss( str ) { + mStyle.cssText = str; + } + + /** + * setCssAll extrapolates all vendor-specific css strings. + */ + function setCssAll( str1, str2 ) { + return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); + } + + /** + * is returns a boolean for if typeof obj is exactly type. + */ + function is( obj, type ) { + return typeof obj === type; + } + + /** + * contains returns a boolean for if substr is found within str. + */ + function contains( str, substr ) { + return !!~('' + str).indexOf(substr); + } + + /** + * testProps is a generic CSS / DOM property test; if a browser supports + * a certain property, it won't return undefined for it. + * A supported CSS property returns empty string when its not yet set. + */ + function testProps( props, prefixed ) { + for ( var i in props ) { + if ( mStyle[ props[i] ] !== undefined ) { + return prefixed == 'pfx' ? props[i] : true; + } + } + return false; + } + + /** + * testDOMProps is a generic DOM property test; if a browser supports + * a certain property, it won't return undefined for it. + */ + function testDOMProps( props, obj, elem ) { + for ( var i in props ) { + var item = obj[props[i]]; + if ( item !== undefined) { + + // return the property name as a string + if (elem === false) return props[i]; + + // let's bind a function + if (is(item, 'function')){ + // default to autobind unless override + return item.bind(elem || obj); + } + + // return the unbound function or obj or value + return item; + } + } + return false; + } + + /** + * testPropsAll tests a list of DOM properties we want to check against. + * We specify literally ALL possible (known and/or likely) properties on + * the element including the non-vendor prefixed one, for forward- + * compatibility. + */ + function testPropsAll( prop, prefixed, elem ) { + + var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1), + props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); + + // did they call .prefixed('boxSizing') or are we just testing a prop? + if(is(prefixed, "string") || is(prefixed, "undefined")) { + return testProps(props, prefixed); + + // otherwise, they called .prefixed('requestAnimationFrame', window[, elem]) + } else { + props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); + return testDOMProps(props, prefixed, elem); + } + } + + /** + * testBundle tests a list of CSS features that require element and style injection. + * By bundling them together we can reduce the need to touch the DOM multiple times. + */ + /*>>testBundle*/ + var testBundle = (function( styles, tests ) { + var style = styles.join(''), + len = tests.length; + + injectElementWithStyles(style, function( node, rule ) { + var style = document.styleSheets[document.styleSheets.length - 1], + // IE8 will bork if you create a custom build that excludes both fontface and generatedcontent tests. + // So we check for cssRules and that there is a rule available + // More here: github.com/Modernizr/Modernizr/issues/288 & github.com/Modernizr/Modernizr/issues/293 + cssText = style ? (style.cssRules && style.cssRules[0] ? style.cssRules[0].cssText : style.cssText || '') : '', + children = node.childNodes, hash = {}; + + while ( len-- ) { + hash[children[len].id] = children[len]; + } + + /*>>touch*/ Modernizr['touch'] = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch || (hash['touch'] && hash['touch'].offsetTop) === 9; /*>>touch*/ + /*>>csstransforms3d*/ Modernizr['csstransforms3d'] = (hash['csstransforms3d'] && hash['csstransforms3d'].offsetLeft) === 9 && hash['csstransforms3d'].offsetHeight === 3; /*>>csstransforms3d*/ + /*>>generatedcontent*/Modernizr['generatedcontent'] = (hash['generatedcontent'] && hash['generatedcontent'].offsetHeight) >= 1; /*>>generatedcontent*/ + /*>>fontface*/ Modernizr['fontface'] = /src/i.test(cssText) && + cssText.indexOf(rule.split(' ')[0]) === 0; /*>>fontface*/ + }, len, tests); + + })([ + // Pass in styles to be injected into document + /*>>fontface*/ '@font-face {font-family:"font";src:url("https://")}' /*>>fontface*/ + + /*>>touch*/ ,['@media (',prefixes.join('touch-enabled),('),mod,')', + '{#touch{top:9px;position:absolute}}'].join('') /*>>touch*/ + + /*>>csstransforms3d*/ ,['@media (',prefixes.join('transform-3d),('),mod,')', + '{#csstransforms3d{left:9px;position:absolute;height:3px;}}'].join('')/*>>csstransforms3d*/ + + /*>>generatedcontent*/,['#generatedcontent:after{content:"',smile,'";visibility:hidden}'].join('') /*>>generatedcontent*/ + ], + [ + /*>>fontface*/ 'fontface' /*>>fontface*/ + /*>>touch*/ ,'touch' /*>>touch*/ + /*>>csstransforms3d*/ ,'csstransforms3d' /*>>csstransforms3d*/ + /*>>generatedcontent*/,'generatedcontent' /*>>generatedcontent*/ + + ]);/*>>testBundle*/ + + + /** + * Tests + * ----- + */ + + // The *new* flexbox + // dev.w3.org/csswg/css3-flexbox + + tests['flexbox'] = function() { + return testPropsAll('flexOrder'); + }; + + // The *old* flexbox + // www.w3.org/TR/2009/WD-css3-flexbox-20090723/ + + tests['flexbox-legacy'] = function() { + return testPropsAll('boxDirection'); + }; + + // On the S60 and BB Storm, getContext exists, but always returns undefined + // so we actually have to call getContext() to verify + // github.com/Modernizr/Modernizr/issues/issue/97/ + + tests['canvas'] = function() { + var elem = document.createElement('canvas'); + return !!(elem.getContext && elem.getContext('2d')); + }; + + tests['canvastext'] = function() { + return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')); + }; + + // this test initiates a new webgl context. + // webk.it/70117 is tracking a legit feature detect proposal + + tests['webgl'] = function() { + try { + var canvas = document.createElement('canvas'), + ret; + ret = !!(window.WebGLRenderingContext && (canvas.getContext('experimental-webgl') || canvas.getContext('webgl'))); + canvas = undefined; + } catch (e){ + ret = false; + } + return ret; + }; + + /* + * The Modernizr.touch test only indicates if the browser supports + * touch events, which does not necessarily reflect a touchscreen + * device, as evidenced by tablets running Windows 7 or, alas, + * the Palm Pre / WebOS (touch) phones. + * + * Additionally, Chrome (desktop) used to lie about its support on this, + * but that has since been rectified: crbug.com/36415 + * + * We also test for Firefox 4 Multitouch Support. + * + * For more info, see: modernizr.github.com/Modernizr/touch.html + */ + + tests['touch'] = function() { + return Modernizr['touch']; + }; + + /** + * geolocation tests for the new Geolocation API specification. + * This test is a standards compliant-only test; for more complete + * testing, including a Google Gears fallback, please see: + * code.google.com/p/geo-location-javascript/ + * or view a fallback solution using google's geo API: + * gist.github.com/366184 + */ + tests['geolocation'] = function() { + return !!navigator.geolocation; + }; + + // Per 1.6: + // This used to be Modernizr.crosswindowmessaging but the longer + // name has been deprecated in favor of a shorter and property-matching one. + // The old API is still available in 1.6, but as of 2.0 will throw a warning, + // and in the first release thereafter disappear entirely. + tests['postmessage'] = function() { + return !!window.postMessage; + }; + + + // Chrome incognito mode used to throw an exception when using openDatabase + // It doesn't anymore. + tests['websqldatabase'] = function() { + return !!window.openDatabase; + }; + + // Vendors had inconsistent prefixing with the experimental Indexed DB: + // - Webkit's implementation is accessible through webkitIndexedDB + // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB + // For speed, we don't test the legacy (and beta-only) indexedDB + tests['indexedDB'] = function() { + return !!testPropsAll("indexedDB",window); + }; + + // documentMode logic from YUI to filter out IE8 Compat Mode + // which false positives. + tests['hashchange'] = function() { + return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7); + }; + + // Per 1.6: + // This used to be Modernizr.historymanagement but the longer + // name has been deprecated in favor of a shorter and property-matching one. + // The old API is still available in 1.6, but as of 2.0 will throw a warning, + // and in the first release thereafter disappear entirely. + tests['history'] = function() { + return !!(window.history && history.pushState); + }; + + tests['draganddrop'] = function() { + var div = document.createElement('div'); + return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); + }; + + // FIXME: Once FF10 is sunsetted, we can drop prefixed MozWebSocket + // bugzil.la/695635 + tests['websockets'] = function() { + for ( var i = -1, len = cssomPrefixes.length; ++i < len; ){ + if ( window[cssomPrefixes[i] + 'WebSocket'] ){ + return true; + } + } + return 'WebSocket' in window; + }; + + + // css-tricks.com/rgba-browser-support/ + tests['rgba'] = function() { + // Set an rgba() color and check the returned value + + setCss('background-color:rgba(150,255,150,.5)'); + + return contains(mStyle.backgroundColor, 'rgba'); + }; + + tests['hsla'] = function() { + // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally, + // except IE9 who retains it as hsla + + setCss('background-color:hsla(120,40%,100%,.5)'); + + return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla'); + }; + + tests['multiplebgs'] = function() { + // Setting multiple images AND a color on the background shorthand property + // and then querying the style.background property value for the number of + // occurrences of "url(" is a reliable method for detecting ACTUAL support for this! + + setCss('background:url(https://),url(https://),red url(https://)'); + + // If the UA supports multiple backgrounds, there should be three occurrences + // of the string "url(" in the return value for elemStyle.background + + return /(url\s*\(.*?){3}/.test(mStyle.background); + }; + + + // In testing support for a given CSS property, it's legit to test: + // `elem.style[styleName] !== undefined` + // If the property is supported it will return an empty string, + // if unsupported it will return undefined. + + // We'll take advantage of this quick test and skip setting a style + // on our modernizr element, but instead just testing undefined vs + // empty string. + + + tests['backgroundsize'] = function() { + return testPropsAll('backgroundSize'); + }; + + tests['borderimage'] = function() { + return testPropsAll('borderImage'); + }; + + + // Super comprehensive table about all the unique implementations of + // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance + + tests['borderradius'] = function() { + return testPropsAll('borderRadius'); + }; + + // WebOS unfortunately false positives on this test. + tests['boxshadow'] = function() { + return testPropsAll('boxShadow'); + }; + + // FF3.0 will false positive on this test + tests['textshadow'] = function() { + return document.createElement('div').style.textShadow === ''; + }; + + + tests['opacity'] = function() { + // Browsers that actually have CSS Opacity implemented have done so + // according to spec, which means their return values are within the + // range of [0.0,1.0] - including the leading zero. + + setCssAll('opacity:.55'); + + // The non-literal . in this regex is intentional: + // German Chrome returns this value as 0,55 + // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632 + return /^0.55$/.test(mStyle.opacity); + }; + + + // Note, Android < 4 will pass this test, but can only animate + // a single property at a time + // daneden.me/2011/12/putting-up-with-androids-bullshit/ + tests['cssanimations'] = function() { + return testPropsAll('animationName'); + }; + + + tests['csscolumns'] = function() { + return testPropsAll('columnCount'); + }; + + + tests['cssgradients'] = function() { + /** + * For CSS Gradients syntax, please see: + * webkit.org/blog/175/introducing-css-gradients/ + * developer.mozilla.org/en/CSS/-moz-linear-gradient + * developer.mozilla.org/en/CSS/-moz-radial-gradient + * dev.w3.org/csswg/css3-images/#gradients- + */ + + var str1 = 'background-image:', + str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', + str3 = 'linear-gradient(left top,#9f9, white);'; + + setCss( + // legacy webkit syntax (FIXME: remove when syntax not in use anymore) + (str1 + '-webkit- '.split(' ').join(str2 + str1) + // standard syntax // trailing 'background-image:' + + prefixes.join(str3 + str1)).slice(0, -str1.length) + ); + + return contains(mStyle.backgroundImage, 'gradient'); + }; + + + tests['cssreflections'] = function() { + return testPropsAll('boxReflect'); + }; + + + tests['csstransforms'] = function() { + return !!testPropsAll('transform'); + }; + + + tests['csstransforms3d'] = function() { + + var ret = !!testPropsAll('perspective'); + + // Webkit's 3D transforms are passed off to the browser's own graphics renderer. + // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in + // some conditions. As a result, Webkit typically recognizes the syntax but + // will sometimes throw a false positive, thus we must do a more thorough check: + if ( ret && 'webkitPerspective' in docElement.style ) { + + // Webkit allows this media query to succeed only if the feature is enabled. + // `@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){ ... }` + ret = Modernizr['csstransforms3d']; + } + return ret; + }; + + + tests['csstransitions'] = function() { + return testPropsAll('transition'); + }; + + + /*>>fontface*/ + // @font-face detection routine by Diego Perini + // javascript.nwbox.com/CSSSupport/ + + // false positives in WebOS: github.com/Modernizr/Modernizr/issues/342 + tests['fontface'] = function() { + return Modernizr['fontface']; + }; + /*>>fontface*/ + + // CSS generated content detection + tests['generatedcontent'] = function() { + return Modernizr['generatedcontent']; + }; + + + + // These tests evaluate support of the video/audio elements, as well as + // testing what types of content they support. + // + // We're using the Boolean constructor here, so that we can extend the value + // e.g. Modernizr.video // true + // Modernizr.video.ogg // 'probably' + // + // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 + // thx to NielsLeenheer and zcorpan + + // Note: in some older browsers, "no" was a return value instead of empty string. + // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 + // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 + + tests['video'] = function() { + var elem = document.createElement('video'), + bool = false; + + // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224 + try { + if ( bool = !!elem.canPlayType ) { + bool = new Boolean(bool); + bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); + + bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); + + bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); + } + + } catch(e) { } + + return bool; + }; + + tests['audio'] = function() { + var elem = document.createElement('audio'), + bool = false; + + try { + if ( bool = !!elem.canPlayType ) { + bool = new Boolean(bool); + bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); + bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); + + // Mimetypes accepted: + // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements + // bit.ly/iphoneoscodecs + bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); + bool.m4a = ( elem.canPlayType('audio/x-m4a;') || + elem.canPlayType('audio/aac;')) .replace(/^no$/,''); + } + } catch(e) { } + + return bool; + }; + + + // In FF4, if disabled, window.localStorage should === null. + + // Normally, we could not test that directly and need to do a + // `('localStorage' in window) && ` test first because otherwise Firefox will + // throw bugzil.la/365772 if cookies are disabled + + // Also in iOS5 Private Browsing mode, attepting to use localStorage.setItem + // will throw the exception: + // QUOTA_EXCEEDED_ERRROR DOM Exception 22. + // Peculiarly, getItem and removeItem calls do not throw. + + // Because we are forced to try/catch this, we'll go aggressive. + + // Just FWIW: IE8 Compat mode supports these features completely: + // www.quirksmode.org/dom/html5.html + // But IE8 doesn't support either with local files + + tests['localstorage'] = function() { + try { + localStorage.setItem(mod, mod); + localStorage.removeItem(mod); + return true; + } catch(e) { + return false; + } + }; + + tests['sessionstorage'] = function() { + try { + sessionStorage.setItem(mod, mod); + sessionStorage.removeItem(mod); + return true; + } catch(e) { + return false; + } + }; + + + tests['webworkers'] = function() { + return !!window.Worker; + }; + + + tests['applicationcache'] = function() { + return !!window.applicationCache; + }; + + + // Thanks to Erik Dahlstrom + tests['svg'] = function() { + return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; + }; + + // specifically for SVG inline in HTML, not within XHTML + // test page: paulirish.com/demo/inline-svg + tests['inlinesvg'] = function() { + var div = document.createElement('div'); + div.innerHTML = '<svg/>'; + return (div.firstChild && div.firstChild.namespaceURI) == ns.svg; + }; + + // SVG SMIL animation + tests['smil'] = function() { + return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))); + }; + + // This test is only for clip paths in SVG proper, not clip paths on HTML content + // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg + + // However read the comments to dig into applying SVG clippaths to HTML content here: + // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491 + tests['svgclippaths'] = function() { + return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))); + }; + + // input features and input types go directly onto the ret object, bypassing the tests loop. + // Hold this guy to execute in a moment. + function webforms() { + // Run through HTML5's new input attributes to see if the UA understands any. + // We're using f which is the <input> element created early on + // Mike Taylr has created a comprehensive resource for testing these attributes + // when applied to all input types: + // miketaylr.com/code/input-type-attr.html + // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary + + // Only input placeholder is tested while textarea's placeholder is not. + // Currently Safari 4 and Opera 11 have support only for the input placeholder + // Both tests are available in feature-detects/forms-placeholder.js + Modernizr['input'] = (function( props ) { + for ( var i = 0, len = props.length; i < len; i++ ) { + attrs[ props[i] ] = !!(props[i] in inputElem); + } + if (attrs.list){ + // safari false positive's on datalist: webk.it/74252 + // see also github.com/Modernizr/Modernizr/issues/146 + attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); + } + return attrs; + })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); + + // Run through HTML5's new input types to see if the UA understands any. + // This is put behind the tests runloop because it doesn't return a + // true/false like all the other tests; instead, it returns an object + // containing each input type with its corresponding true/false value + + // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/ + Modernizr['inputtypes'] = (function(props) { + + for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { + + inputElem.setAttribute('type', inputElemType = props[i]); + bool = inputElem.type !== 'text'; + + // We first check to see if the type we give it sticks.. + // If the type does, we feed it a textual value, which shouldn't be valid. + // If the value doesn't stick, we know there's input sanitization which infers a custom UI + if ( bool ) { + + inputElem.value = smile; + inputElem.style.cssText = 'position:absolute;visibility:hidden;'; + + if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { + + docElement.appendChild(inputElem); + defaultView = document.defaultView; + + // Safari 2-4 allows the smiley as a value, despite making a slider + bool = defaultView.getComputedStyle && + defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && + // Mobile android web browser has false positive, so must + // check the height to see if the widget is actually there. + (inputElem.offsetHeight !== 0); + + docElement.removeChild(inputElem); + + } else if ( /^(search|tel)$/.test(inputElemType) ){ + // Spec doesnt define any special parsing or detectable UI + // behaviors so we pass these through as true + + // Interestingly, opera fails the earlier test, so it doesn't + // even make it here. + + } else if ( /^(url|email)$/.test(inputElemType) ) { + // Real url and email support comes with prebaked validation. + bool = inputElem.checkValidity && inputElem.checkValidity() === false; + + } else if ( /^color$/.test(inputElemType) ) { + // chuck into DOM and force reflow for Opera bug in 11.00 + // github.com/Modernizr/Modernizr/issues#issue/159 + docElement.appendChild(inputElem); + docElement.offsetWidth; + bool = inputElem.value != smile; + docElement.removeChild(inputElem); + + } else { + // If the upgraded input compontent rejects the :) text, we got a winner + bool = inputElem.value != smile; + } + } + + inputs[ props[i] ] = !!bool; + } + return inputs; + })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); + } + + + // End of test definitions + // ----------------------- + + + + // Run through all tests and detect their support in the current UA. + // todo: hypothetically we could be doing an array of tests and use a basic loop here. + for ( var feature in tests ) { + if ( hasOwnProperty(tests, feature) ) { + // run the test, throw the return value into the Modernizr, + // then based on that boolean, define an appropriate className + // and push it into an array of classes we'll join later. + featureName = feature.toLowerCase(); + Modernizr[featureName] = tests[feature](); + + classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); + } + } + + // input tests need to run. + Modernizr.input || webforms(); + + + /** + * addTest allows the user to define their own feature tests + * the result will be added onto the Modernizr object, + * as well as an appropriate className set on the html element + * + * @param feature - String naming the feature + * @param test - Function returning true if feature is supported, false if not + */ + Modernizr.addTest = function ( feature, test ) { + if ( typeof feature == 'object' ) { + for ( var key in feature ) { + if ( hasOwnProperty( feature, key ) ) { + Modernizr.addTest( key, feature[ key ] ); + } + } + } else { + + feature = feature.toLowerCase(); + + if ( Modernizr[feature] !== undefined ) { + // we're going to quit if you're trying to overwrite an existing test + // if we were to allow it, we'd do this: + // var re = new RegExp("\\b(no-)?" + feature + "\\b"); + // docElement.className = docElement.className.replace( re, '' ); + // but, no rly, stuff 'em. + return Modernizr; + } + + test = typeof test == 'function' ? test() : test; + + docElement.className += ' ' + (test ? '' : 'no-') + feature; + Modernizr[feature] = test; + + } + + return Modernizr; // allow chaining. + }; + + + // Reset modElem.cssText to nothing to reduce memory footprint. + setCss(''); + modElem = inputElem = null; + + //>>BEGIN IEPP + // Enable HTML 5 elements for styling in IE & add HTML5 css + /*! HTML5 Shiv v3.4 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ + ;(function(window, document) { + + /** Preset options */ + var options = window.html5 || {}; + + /** Used to skip problem elements */ + var reSkip = /^<|^(?:button|form|map|select|textarea)$/i; + + /** Detect whether the browser supports default html5 styles */ + var supportsHtml5Styles; + + /** Detect whether the browser supports unknown elements */ + var supportsUnknownElements; + + (function() { + var a = document.createElement('a'); + + a.innerHTML = '<xyz></xyz>'; + + //if the hidden property is implemented we can assume, that the browser supports HTML5 Styles + supportsHtml5Styles = ('hidden' in a); + supportsUnknownElements = a.childNodes.length == 1 || (function() { + // assign a false positive if unable to shiv + try { + (document.createElement)('a'); + } catch(e) { + return true; + } + var frag = document.createDocumentFragment(); + return ( + typeof frag.cloneNode == 'undefined' || + typeof frag.createDocumentFragment == 'undefined' || + typeof frag.createElement == 'undefined' + ); + }()); + + }()); + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a style sheet with the given CSS text and adds it to the document. + * @private + * @param {Document} ownerDocument The document. + * @param {String} cssText The CSS text. + * @returns {StyleSheet} The style element. + */ + function addStyleSheet(ownerDocument, cssText) { + var p = ownerDocument.createElement('p'), + parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; + + p.innerHTML = 'x<style>' + cssText + '</style>'; + return parent.insertBefore(p.lastChild, parent.firstChild); + } + + /** + * Returns the value of `html5.elements` as an array. + * @private + * @returns {Array} An array of shived element node names. + */ + function getElements() { + var elements = html5.elements; + return typeof elements == 'string' ? elements.split(' ') : elements; + } + + /** + * Shivs the `createElement` and `createDocumentFragment` methods of the document. + * @private + * @param {Document|DocumentFragment} ownerDocument The document. + */ + function shivMethods(ownerDocument) { + var cache = {}, + docCreateElement = ownerDocument.createElement, + docCreateFragment = ownerDocument.createDocumentFragment, + frag = docCreateFragment(); + + ownerDocument.createElement = function(nodeName) { + // Avoid adding some elements to fragments in IE < 9 because + // * Attributes like `name` or `type` cannot be set/changed once an element + // is inserted into a document/fragment + // * Link elements with `src` attributes that are inaccessible, as with + // a 403 response, will cause the tab/window to crash + // * Script elements appended to fragments will execute when their `src` + // or `text` property is set + var node = (cache[nodeName] || (cache[nodeName] = docCreateElement(nodeName))).cloneNode(); + return html5.shivMethods && node.canHaveChildren && !reSkip.test(nodeName) ? frag.appendChild(node) : node; + }; + + ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + + 'var n=f.cloneNode(),c=n.createElement;' + + 'h.shivMethods&&(' + + // unroll the `createElement` calls + getElements().join().replace(/\w+/g, function(nodeName) { + cache[nodeName] = docCreateElement(nodeName); + frag.createElement(nodeName); + return 'c("' + nodeName + '")'; + }) + + ');return n}' + )(html5, frag); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Shivs the given document. + * @memberOf html5 + * @param {Document} ownerDocument The document to shiv. + * @returns {Document} The shived document. + */ + function shivDocument(ownerDocument) { + var shived; + if (ownerDocument.documentShived) { + return ownerDocument; + } + if (html5.shivCSS && !supportsHtml5Styles) { + shived = !!addStyleSheet(ownerDocument, + // corrects block display not defined in IE6/7/8/9 + 'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' + + // corrects audio display not defined in IE6/7/8/9 + 'audio{display:none}' + + // corrects canvas and video display not defined in IE6/7/8/9 + 'canvas,video{display:inline-block;*display:inline;*zoom:1}' + + // corrects 'hidden' attribute and audio[controls] display not present in IE7/8/9 + '[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}' + + // adds styling not present in IE6/7/8/9 + 'mark{background:#FF0;color:#000}' + ); + } + if (!supportsUnknownElements) { + shived = !shivMethods(ownerDocument); + } + if (shived) { + ownerDocument.documentShived = shived; + } + return ownerDocument; + } + + /*--------------------------------------------------------------------------*/ + + /** + * The `html5` object is exposed so that more elements can be shived and + * existing shiving can be detected on iframes. + * @type Object + * @example + * + * // options can be changed before the script is included + * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false }; + */ + var html5 = { + + /** + * An array or space separated string of node names of the elements to shiv. + * @memberOf html5 + * @type Array|String + */ + 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video', + + /** + * A flag to indicate that the HTML5 style sheet should be inserted. + * @memberOf html5 + * @type Boolean + */ + 'shivCSS': !(options.shivCSS === false), + + /** + * A flag to indicate that the document's `createElement` and `createDocumentFragment` + * methods should be overwritten. + * @memberOf html5 + * @type Boolean + */ + 'shivMethods': !(options.shivMethods === false), + + /** + * A string to describe the type of `html5` object ("default" or "default print"). + * @memberOf html5 + * @type String + */ + 'type': 'default', + + // shivs the document according to the specified `html5` object options + 'shivDocument': shivDocument + }; + + /*--------------------------------------------------------------------------*/ + + // expose html5 + window.html5 = html5; + + // shiv the document + shivDocument(document); + + }(this, document)); + + //>>END IEPP + + // Assign private properties to the return object with prefix + Modernizr._version = version; + + // expose these for the plugin API. Look in the source for how to join() them against your input + Modernizr._prefixes = prefixes; + Modernizr._domPrefixes = domPrefixes; + Modernizr._cssomPrefixes = cssomPrefixes; + + // Modernizr.mq tests a given media query, live against the current state of the window + // A few important notes: + // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false + // * A max-width or orientation query will be evaluated against the current state, which may change later. + // * You must specify values. Eg. If you are testing support for the min-width media query use: + // Modernizr.mq('(min-width:0)') + // usage: + // Modernizr.mq('only screen and (max-width:768)') + Modernizr.mq = testMediaQuery; + + // Modernizr.hasEvent() detects support for a given event, with an optional element to test on + // Modernizr.hasEvent('gesturestart', elem) + Modernizr.hasEvent = isEventSupported; + + // Modernizr.testProp() investigates whether a given style property is recognized + // Note that the property names must be provided in the camelCase variant. + // Modernizr.testProp('pointerEvents') + Modernizr.testProp = function(prop){ + return testProps([prop]); + }; + + // Modernizr.testAllProps() investigates whether a given style property, + // or any of its vendor-prefixed variants, is recognized + // Note that the property names must be provided in the camelCase variant. + // Modernizr.testAllProps('boxSizing') + Modernizr.testAllProps = testPropsAll; + + + + // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards + // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... }) + Modernizr.testStyles = injectElementWithStyles; + + + // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input + // Modernizr.prefixed('boxSizing') // 'MozBoxSizing' + + // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style. + // Return values will also be the camelCase variant, if you need to translate that to hypenated style use: + // + // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); + + // If you're trying to ascertain which transition end event to bind to, you might do something like... + // + // var transEndEventNames = { + // 'WebkitTransition' : 'webkitTransitionEnd', + // 'MozTransition' : 'transitionend', + // 'OTransition' : 'oTransitionEnd', + // 'msTransition' : 'MsTransitionEnd', + // 'transition' : 'transitionend' + // }, + // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ]; + + Modernizr.prefixed = function(prop, obj, elem){ + if(!obj) { + return testPropsAll(prop, 'pfx'); + } else { + // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame' + return testPropsAll(prop, obj, elem); + } + }; + + + + // Remove "no-js" class from <html> element, if it exists: + docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + + + // Add the new classes to the <html> element. + (enableClasses ? ' js ' + classes.join(' ') : ''); + + return Modernizr; + +})(this, this.document); diff --git a/samples/OAuth2ProtectedWebApi/Views/Home/Index.cshtml b/samples/OAuth2ProtectedWebApi/Views/Home/Index.cshtml new file mode 100644 index 0000000..9d0b4a9 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Views/Home/Index.cshtml @@ -0,0 +1,53 @@ +<header> + <div class="content-wrapper"> + <div class="float-left"> + <p class="site-title"> + <a href="~/">ASP.NET Web API</a></p> + </div> + </div> +</header> +<div id="body"> + <section class="featured"> + <div class="content-wrapper"> + <hgroup class="title"> + <h1>Welcome to ASP.NET Web API!</h1> + <h2>Modify the code in this template to jump-start your ASP.NET Web API development.</h2> + </hgroup> + <p> + ASP.NET Web API allows you to expose your applications, data and services to the + web directly over HTTP. + </p> + <p> + To learn more about ASP.NET Web API visit + <a href="http://go.microsoft.com/fwlink/?LinkID=238195" title="ASP.NET Web API Website">http://asp.net/web-api</a>. + The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET Web API. + If you have any questions about ASP.NET Web API, visit + <a href="http://go.microsoft.com/fwlink/?LinkID=238196" title="ASP.NET Web API Forum">our forums</a>. + </p> + </div> + </section> + <section class="content-wrapper main-content clear-fix"> + <h3>We suggest the following steps:</h3> + <ol class="round"> + <li class="one"> + <h5>Getting Started</h5> + ASP.NET Web API is a framework that makes it easy to build HTTP services that reach + a broad range of clients, including browsers and mobile devices. ASP.NET Web API + is an ideal platform for building RESTful applications on the .NET Framework. + <a href="http://go.microsoft.com/fwlink/?LinkId=245160">Learn more…</a> + </li> + + <li class="two"> + <h5>Add NuGet packages and jump-start your coding</h5> + NuGet makes it easy to install and update free libraries and tools. + <a href="http://go.microsoft.com/fwlink/?LinkId=245161">Learn more…</a> + </li> + <li class="three"> + <h5>Find Web Hosting</h5> + You can easily find a web hosting company that offers the right mix of features + and price for your applications. + <a href="http://go.microsoft.com/fwlink/?LinkId=245164">Learn more…</a> + </li> + </ol> + </section> +</div> diff --git a/samples/OAuth2ProtectedWebApi/Views/Shared/Error.cshtml b/samples/OAuth2ProtectedWebApi/Views/Shared/Error.cshtml new file mode 100644 index 0000000..54c5886 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Views/Shared/Error.cshtml @@ -0,0 +1,16 @@ +@{ + Layout = null; +} + +<!DOCTYPE html> +<html> +<head> + <meta name="viewport" content="width=device-width" /> + <title>Error</title> +</head> +<body> + <h2> + Sorry, an error occurred while processing your request. + </h2> +</body> +</html>
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Views/Shared/_Layout.cshtml b/samples/OAuth2ProtectedWebApi/Views/Shared/_Layout.cshtml new file mode 100644 index 0000000..cdd3281 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Views/Shared/_Layout.cshtml @@ -0,0 +1,16 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width" /> + <title>@ViewBag.Title</title> + @Styles.Render("~/Content/css") + @Scripts.Render("~/bundles/modernizr") +</head> +<body> + @RenderBody() + + @Scripts.Render("~/bundles/jquery") + @RenderSection("scripts", required: false) +</body> +</html> diff --git a/samples/OAuth2ProtectedWebApi/Views/User/Authorize.cshtml b/samples/OAuth2ProtectedWebApi/Views/User/Authorize.cshtml new file mode 100644 index 0000000..930788e --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Views/User/Authorize.cshtml @@ -0,0 +1,14 @@ +@{ + ViewBag.Title = "Authorize"; + Layout = "~/Views/Shared/_Layout.cshtml"; +} + +<h2>Authorize</h2> + +@using (Html.BeginForm("Respond", "User", FormMethod.Post)) { + @AntiForgery.GetHtml() + @Html.Hidden("request", this.ViewData["request"]) + <p>Are you sure you want to allow the client to access your data, with this scope: <b>@string.Join(" ", (IEnumerable<string>)ViewData["Scope"])</b></p> + <input type="submit" name="approval" value="true" /> + <input type="submit" name="approval" value="false" /> +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Views/Web.config b/samples/OAuth2ProtectedWebApi/Views/Web.config new file mode 100644 index 0000000..aa52615 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Views/Web.config @@ -0,0 +1,59 @@ +<?xml version="1.0"?> + +<configuration> + <configSections> + <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> + <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> + <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> + </sectionGroup> + </configSections> + + <system.web.webPages.razor> + <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> + <pages pageBaseType="System.Web.Mvc.WebViewPage"> + <namespaces> + <add namespace="System.Web.Mvc" /> + <add namespace="System.Web.Mvc.Ajax" /> + <add namespace="System.Web.Mvc.Html" /> + <add namespace="System.Web.Optimization"/> + <add namespace="System.Web.Routing" /> + </namespaces> + </pages> + </system.web.webPages.razor> + + <appSettings> + <add key="webpages:Enabled" value="false" /> + </appSettings> + + <system.web> + <httpHandlers> + <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/> + </httpHandlers> + + <!-- + Enabling request validation in view pages would cause validation to occur + after the input has already been processed by the controller. By default + MVC performs request validation before a controller processes the input. + To change this behavior apply the ValidateInputAttribute to a + controller or action. + --> + <pages + validateRequest="false" + pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" + pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" + userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> + <controls> + <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" /> + </controls> + </pages> + </system.web> + + <system.webServer> + <validation validateIntegratedModeConfiguration="false" /> + + <handlers> + <remove name="BlockViewHandler"/> + <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /> + </handlers> + </system.webServer> +</configuration> diff --git a/samples/OAuth2ProtectedWebApi/Views/_ViewStart.cshtml b/samples/OAuth2ProtectedWebApi/Views/_ViewStart.cshtml new file mode 100644 index 0000000..efda124 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Views/_ViewStart.cshtml @@ -0,0 +1,3 @@ +@{ + Layout = "~/Views/Shared/_Layout.cshtml"; +}
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Web.Debug.config b/samples/OAuth2ProtectedWebApi/Web.Debug.config new file mode 100644 index 0000000..3e2a97c --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Web.Debug.config @@ -0,0 +1,30 @@ +<?xml version="1.0"?> + +<!-- For more information on using Web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 --> + +<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> + <!-- + In the example below, the "SetAttributes" transform will change the value of + "connectionString" to use "ReleaseSQLServer" only when the "Match" locator + finds an atrribute "name" that has a value of "MyDB". + + <connectionStrings> + <add name="MyDB" + connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" + xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> + </connectionStrings> + --> + <system.web> + <!-- + In the example below, the "Replace" transform will replace the entire + <customErrors> section of your Web.config file. + Note that because there is only one customErrors section under the + <system.web> node, there is no need to use the "xdt:Locator" attribute. + + <customErrors defaultRedirect="GenericError.htm" + mode="RemoteOnly" xdt:Transform="Replace"> + <error statusCode="500" redirect="InternalError.htm"/> + </customErrors> + --> + </system.web> +</configuration>
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Web.Release.config b/samples/OAuth2ProtectedWebApi/Web.Release.config new file mode 100644 index 0000000..9fd481f --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Web.Release.config @@ -0,0 +1,31 @@ +<?xml version="1.0"?> + +<!-- For more information on using Web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 --> + +<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> + <!-- + In the example below, the "SetAttributes" transform will change the value of + "connectionString" to use "ReleaseSQLServer" only when the "Match" locator + finds an atrribute "name" that has a value of "MyDB". + + <connectionStrings> + <add name="MyDB" + connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" + xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> + </connectionStrings> + --> + <system.web> + <compilation xdt:Transform="RemoveAttributes(debug)" /> + <!-- + In the example below, the "Replace" transform will replace the entire + <customErrors> section of your Web.config file. + Note that because there is only one customErrors section under the + <system.web> node, there is no need to use the "xdt:Locator" attribute. + + <customErrors defaultRedirect="GenericError.htm" + mode="RemoteOnly" xdt:Transform="Replace"> + <error statusCode="500" redirect="InternalError.htm"/> + </customErrors> + --> + </system.web> +</configuration>
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/Web.config b/samples/OAuth2ProtectedWebApi/Web.config new file mode 100644 index 0000000..ef67291 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/Web.config @@ -0,0 +1,124 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + For more information on how to configure your ASP.NET application, please visit + http://go.microsoft.com/fwlink/?LinkId=169433 + --> +<configuration> + <configSections> + <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> + <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> + <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false"/> + <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core"> + <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" /> + <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" /> + <sectionGroup name="oauth2" type="DotNetOpenAuth.Configuration.OAuth2SectionGroup, DotNetOpenAuth.OAuth2"> + <section name="authorizationServer" type="DotNetOpenAuth.Configuration.OAuth2AuthorizationServerSection, DotNetOpenAuth.OAuth2.AuthorizationServer" requirePermission="false" allowLocation="true" /> + </sectionGroup> + <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /> + <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /> + </sectionGroup> + </configSections> + <connectionStrings> + <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-OAuth2ProtectedWebApi-20130228210758;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-OAuth2ProtectedWebApi-20130228210758.mdf" /> + </connectionStrings> + <appSettings> + <add key="webpages:Version" value="2.0.0.0" /> + <add key="webpages:Enabled" value="false" /> + <add key="PreserveLoginUrl" value="true" /> + <add key="ClientValidationEnabled" value="true" /> + <add key="UnobtrusiveJavaScriptEnabled" value="true" /> + </appSettings> + <system.web> + <compilation debug="true" targetFramework="4.5" /> + <httpRuntime targetFramework="4.5" /> + <authentication mode="Forms"> + <forms loginUrl="/user/login" defaultUrl="/" /> + </authentication> + <pages> + <namespaces> + <add namespace="System.Web.Helpers" /> + <add namespace="System.Web.Mvc" /> + <add namespace="System.Web.Mvc.Ajax" /> + <add namespace="System.Web.Mvc.Html" /> + <add namespace="System.Web.Optimization" /> + <add namespace="System.Web.Routing" /> + <add namespace="System.Web.WebPages" /> + </namespaces> + </pages> + <profile defaultProvider="DefaultProfileProvider"> + <providers> + <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" /> + </providers> + </profile> + <membership defaultProvider="DefaultMembershipProvider"> + <providers> + <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> + </providers> + </membership> + <roleManager defaultProvider="DefaultRoleProvider"> + <providers> + <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" /> + </providers> + </roleManager> + <!-- + If you are deploying to a cloud environment that has multiple web server instances, + you should change session state mode from "InProc" to "Custom". In addition, + change the connection string named "DefaultConnection" to connect to an instance + of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express. + --> + <sessionState mode="InProc" customProvider="DefaultSessionProvider"> + <providers> + <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" /> + </providers> + </sessionState> + </system.web> + <system.webServer> + <validation validateIntegratedModeConfiguration="false" /> + <handlers> + <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> + <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> + <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> + <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> + <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> + <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> + </handlers> + </system.webServer> + <!-- this is an optional configuration section where aspects of dotnetopenauth can be customized --> + <dotNetOpenAuth> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> + <oauth2> + <authorizationServer> + </authorizationServer> + </oauth2> + + <!-- Relaxing SSL requirements is useful for simple samples, but NOT a good idea in production. --> + <messaging relaxSslRequirements="true"> + <untrustedWebRequest> + <whitelistHosts> + <!-- since this is a sample, and will often be used with localhost --> + <add name="localhost"/> + </whitelistHosts> + </untrustedWebRequest> + </messaging> + </dotNetOpenAuth> + <runtime> + <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> + <dependentAssembly> + <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> + <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> + </dependentAssembly> + <dependentAssembly> + <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> + <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> + </dependentAssembly> + <dependentAssembly> + <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> + <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> + </dependentAssembly> + </assemblyBinding> + </runtime> + <entityFramework> + <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> + </entityFramework> +</configuration>
\ No newline at end of file diff --git a/samples/OAuth2ProtectedWebApi/favicon.ico b/samples/OAuth2ProtectedWebApi/favicon.ico Binary files differnew file mode 100644 index 0000000..a3a7999 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/favicon.ico diff --git a/samples/OAuth2ProtectedWebApi/packages.config b/samples/OAuth2ProtectedWebApi/packages.config new file mode 100644 index 0000000..9aada29 --- /dev/null +++ b/samples/OAuth2ProtectedWebApi/packages.config @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="EntityFramework" version="5.0.0" targetFramework="net45" /> + <package id="jQuery" version="1.7.1.1" targetFramework="net45" /> + <package id="jQuery.UI.Combined" version="1.8.20.1" targetFramework="net45" /> + <package id="jQuery.Validation" version="1.9.0.1" targetFramework="net45" /> + <package id="knockoutjs" version="2.1.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Providers.Core" version="1.1" targetFramework="net45" /> + <package id="Microsoft.AspNet.Providers.LocalDB" version="1.1" targetFramework="net45" /> + <package id="Microsoft.AspNet.Razor" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Web.Optimization" version="1.0.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebApi" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebApi.Core" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebApi.WebHost" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.jQuery.Unobtrusive.Ajax" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.jQuery.Unobtrusive.Validation" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> + <package id="Modernizr" version="2.5.3" targetFramework="net45" /> + <package id="Newtonsoft.Json" version="4.5.6" targetFramework="net45" /> + <package id="WebGrease" version="1.1.0" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/samples/OAuthAuthorizationServer/Controllers/AccountController.cs b/samples/OAuthAuthorizationServer/Controllers/AccountController.cs index d69a3b5..336f9bd 100644 --- a/samples/OAuthAuthorizationServer/Controllers/AccountController.cs +++ b/samples/OAuthAuthorizationServer/Controllers/AccountController.cs @@ -1,13 +1,12 @@ namespace OAuthAuthorizationServer.Controllers { using System; using System.Linq; + using System.Threading.Tasks; using System.Web.Mvc; using System.Web.Security; - using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; - using OAuthAuthorizationServer.Code; using OAuthAuthorizationServer.Models; @@ -21,16 +20,17 @@ } [HttpPost] - public ActionResult LogOn(LogOnModel model, string returnUrl) { + public async Task<ActionResult> LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { var rp = new OpenIdRelyingParty(); - var request = rp.CreateRequest(model.UserSuppliedIdentifier, Realm.AutoDetect, new Uri(Request.Url, Url.Action("Authenticate"))); + var request = await rp.CreateRequestAsync(model.UserSuppliedIdentifier, Realm.AutoDetect, new Uri(Request.Url, Url.Action("Authenticate")), Response.ClientDisconnectedToken); if (request != null) { if (returnUrl != null) { request.AddCallbackArguments("returnUrl", returnUrl); } - return request.RedirectingResponse.AsActionResult(); + var response = await request.GetRedirectingResponseAsync(Response.ClientDisconnectedToken); + return response.AsActionResult(); } else { ModelState.AddModelError(string.Empty, "The identifier you supplied is not recognized as a valid OpenID Identifier."); } @@ -40,9 +40,9 @@ return View(model); } - public ActionResult Authenticate(string returnUrl) { + public async Task<ActionResult> Authenticate(string returnUrl) { var rp = new OpenIdRelyingParty(); - var response = rp.GetResponse(); + var response = await rp.GetResponseAsync(Request, Response.ClientDisconnectedToken); if (response != null) { switch (response.Status) { case AuthenticationStatus.Authenticated: diff --git a/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs b/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs index 4c3e4d4..3ab4096 100644 --- a/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs +++ b/samples/OAuthAuthorizationServer/Controllers/OAuthController.cs @@ -4,12 +4,11 @@ using System.Linq;
using System.Net;
using System.Security.Cryptography;
+ using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
-
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;
-
using OAuthAuthorizationServer.Code;
using OAuthAuthorizationServer.Models;
@@ -20,8 +19,9 @@ /// The OAuth 2.0 token endpoint.
/// </summary>
/// <returns>The response to the Client.</returns>
- public ActionResult Token() {
- return this.authorizationServer.HandleTokenRequest(this.Request).AsActionResult();
+ public async Task<ActionResult> Token() {
+ var request = await this.authorizationServer.HandleTokenRequestAsync(this.Request, this.Response.ClientDisconnectedToken);
+ return request.AsActionResult();
}
/// <summary>
@@ -30,8 +30,8 @@ /// <returns>The browser HTML response that prompts the user to authorize the client.</returns>
[Authorize, AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
[HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
- public ActionResult Authorize() {
- var pendingRequest = this.authorizationServer.ReadAuthorizationRequest();
+ public async Task<ActionResult> Authorize() {
+ var pendingRequest = await this.authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);
if (pendingRequest == null) {
throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
}
@@ -41,7 +41,8 @@ // Consider auto-approving if safe to do so.
if (((OAuth2AuthorizationServer)this.authorizationServer.AuthorizationServerServices).CanBeAutoApproved(pendingRequest)) {
var approval = this.authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, HttpContext.User.Identity.Name);
- return this.authorizationServer.Channel.PrepareResponse(approval).AsActionResult();
+ var response = await this.authorizationServer.Channel.PrepareResponseAsync(approval, Response.ClientDisconnectedToken);
+ return response.AsActionResult();
}
var model = new AccountAuthorizeModel {
@@ -59,8 +60,8 @@ /// <param name="isApproved">if set to <c>true</c>, the user has authorized the Client; <c>false</c> otherwise.</param>
/// <returns>HTML response that redirects the browser to the Client.</returns>
[Authorize, HttpPost, ValidateAntiForgeryToken]
- public ActionResult AuthorizeResponse(bool isApproved) {
- var pendingRequest = this.authorizationServer.ReadAuthorizationRequest();
+ public async Task<ActionResult> AuthorizeResponse(bool isApproved) {
+ var pendingRequest = await this.authorizationServer.ReadAuthorizationRequestAsync(Request, Response.ClientDisconnectedToken);
if (pendingRequest == null) {
throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
}
@@ -86,7 +87,8 @@ response = this.authorizationServer.PrepareRejectAuthorizationRequest(pendingRequest);
}
- return this.authorizationServer.Channel.PrepareResponse(response).AsActionResult();
+ var preparedResponse = await this.authorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
+ return preparedResponse.AsActionResult();
}
}
}
diff --git a/samples/OAuthAuthorizationServer/OAuthAuthorizationServer.csproj b/samples/OAuthAuthorizationServer/OAuthAuthorizationServer.csproj index 7715fe2..82402c8 100644 --- a/samples/OAuthAuthorizationServer/OAuthAuthorizationServer.csproj +++ b/samples/OAuthAuthorizationServer/OAuthAuthorizationServer.csproj @@ -48,6 +48,10 @@ <HintPath>..\..\src\packages\log4net.2.0.0\lib\net40-full\log4net.dll</HintPath> </Reference> <Reference Include="Microsoft.CSharp" /> + <Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath> + </Reference> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Data.Linq" /> @@ -66,7 +70,30 @@ <Reference Include="System.Data.DataSetExtensions"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> - <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> + <Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.Helpers.dll</HintPath> + </Reference> + <Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Mvc.4.0.20710.0\lib\net40\System.Web.Mvc.dll</HintPath> + </Reference> + <Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Razor.2.0.20715.0\lib\net40\System.Web.Razor.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath> + </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> diff --git a/samples/OAuthAuthorizationServer/Web.config b/samples/OAuthAuthorizationServer/Web.config index 37157fd..4e25f1e 100644 --- a/samples/OAuthAuthorizationServer/Web.config +++ b/samples/OAuthAuthorizationServer/Web.config @@ -75,12 +75,17 @@ providerName="System.Data.SqlClient" /> </connectionStrings> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> + <system.web> + <httpRuntime targetFramework="4.5" /> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> - <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> + <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> @@ -104,12 +109,10 @@ </system.webServer> <runtime> - <!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink - to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it. --> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> - <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> + <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> diff --git a/samples/OAuthAuthorizationServer/packages.config b/samples/OAuthAuthorizationServer/packages.config index 8e40260..ce88802 100644 --- a/samples/OAuthAuthorizationServer/packages.config +++ b/samples/OAuthAuthorizationServer/packages.config @@ -1,5 +1,9 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Razor" version="2.0.20715.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" /> <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OAuthClient/Facebook.aspx b/samples/OAuthClient/Facebook.aspx index c227814..4cdc4b1 100644 --- a/samples/OAuthClient/Facebook.aspx +++ b/samples/OAuthClient/Facebook.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" Inherits="OAuthClient.Facebook" Codebehind="Facebook.aspx.cs" %> +<%@ Page Language="C#" AutoEventWireup="true" Inherits="OAuthClient.Facebook" Codebehind="Facebook.aspx.cs" Async="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> diff --git a/samples/OAuthClient/Facebook.aspx.cs b/samples/OAuthClient/Facebook.aspx.cs index 4701d24..19211bc 100644 --- a/samples/OAuthClient/Facebook.aspx.cs +++ b/samples/OAuthClient/Facebook.aspx.cs @@ -3,8 +3,11 @@ using System.Configuration; using System.Net; using System.Web; + using System.Web.UI; + using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.ApplicationBlock.Facebook; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; public partial class Facebook : System.Web.UI.Page { @@ -14,19 +17,29 @@ }; protected void Page_Load(object sender, EventArgs e) { - IAuthorizationState authorization = client.ProcessUserAuthorization(); - if (authorization == null) { - // Kick off authorization request - client.RequestUserAuthorization(); - } else { - var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); - using (var response = request.GetResponse()) { - using (var responseStream = response.GetResponseStream()) { - var graph = FacebookGraph.Deserialize(responseStream); - this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); - } - } - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + IAuthorizationState authorization = + await client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), ct); + if (authorization == null) { + // Kick off authorization request + var request = + await client.PrepareRequestUserAuthorizationAsync(cancellationToken: ct); + await request.SendAsync(new HttpContextWrapper(Context), ct); + this.Context.Response.End(); + } else { + var request = + WebRequest.Create( + "https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); + using (var response = request.GetResponse()) { + using (var responseStream = response.GetResponseStream()) { + var graph = FacebookGraph.Deserialize(responseStream); + this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); + } + } + } + })); } } }
\ No newline at end of file diff --git a/samples/OAuthClient/GoogleAddressBook.aspx b/samples/OAuthClient/GoogleAddressBook.aspx deleted file mode 100644 index 11891f2..0000000 --- a/samples/OAuthClient/GoogleAddressBook.aspx +++ /dev/null @@ -1,26 +0,0 @@ -<%@ Page Title="Gmail address book demo" Language="C#" MasterPageFile="~/MasterPage.master" - AutoEventWireup="true" Inherits="OAuthClient.GoogleAddressBook" Codebehind="GoogleAddressBook.aspx.cs" %> - -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View runat="server"> - <h2>Google setup</h2> - <p>A Google client app must be endorsed by a Google user. </p> - <ol> - <li><a target="_blank" href="https://www.google.com/accounts/ManageDomains">Visit Google - and create a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret. - </li> - </ol> - </asp:View> - <asp:View runat="server"> - <h2>Updates</h2> - <p>Ok, Google has authorized us to download your contacts. Click 'Get address book' - to download the first 5 contacts to this sample. Notice how we never asked you - for your Google username or password. </p> - <asp:Button ID="getAddressBookButton" runat="server" OnClick="getAddressBookButton_Click" - Text="Get address book" /> - <asp:PlaceHolder ID="resultsPlaceholder" runat="server" /> - </asp:View> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/GoogleAddressBook.aspx.cs b/samples/OAuthClient/GoogleAddressBook.aspx.cs deleted file mode 100644 index b7221af..0000000 --- a/samples/OAuthClient/GoogleAddressBook.aspx.cs +++ /dev/null @@ -1,75 +0,0 @@ -namespace OAuthClient { - using System; - using System.Configuration; - using System.Linq; - using System.Text; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using System.Xml.Linq; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.OAuth; - - /// <summary> - /// A page to demonstrate downloading a Gmail address book using OAuth. - /// </summary> - public partial class GoogleAddressBook : System.Web.UI.Page { - private string AccessToken { - get { return (string)Session["GoogleAccessToken"]; } - set { Session["GoogleAccessToken"] = value; } - } - - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["GoogleTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["GoogleTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.ActiveViewIndex = 1; - - if (!IsPostBack) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - - // Is Google calling back with authorization? - var accessTokenResponse = google.ProcessUserAuthorization(); - if (accessTokenResponse != null) { - this.AccessToken = accessTokenResponse.AccessToken; - } else if (this.AccessToken == null) { - // If we don't yet have access, immediately request it. - GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Contacts); - } - } - } - } - - protected void getAddressBookButton_Click(object sender, EventArgs e) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - - XDocument contactsDocument = GoogleConsumer.GetContacts(google, this.AccessToken, 5, 1); - var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) - select new { Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value }; - StringBuilder tableBuilder = new StringBuilder(); - tableBuilder.Append("<table><tr><td>Name</td><td>Email</td></tr>"); - foreach (var contact in contacts) { - tableBuilder.AppendFormat( - "<tr><td>{0}</td><td>{1}</td></tr>", - HttpUtility.HtmlEncode(contact.Name), - HttpUtility.HtmlEncode(contact.Email)); - } - tableBuilder.Append("</table>"); - this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/GoogleAddressBook.aspx.designer.cs b/samples/OAuthClient/GoogleAddressBook.aspx.designer.cs deleted file mode 100644 index 576072e..0000000 --- a/samples/OAuthClient/GoogleAddressBook.aspx.designer.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class GoogleAddressBook { - - /// <summary> - /// MultiView1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.MultiView MultiView1; - - /// <summary> - /// getAddressBookButton control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Button getAddressBookButton; - - /// <summary> - /// resultsPlaceholder control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/GoogleApps2Legged.aspx b/samples/OAuthClient/GoogleApps2Legged.aspx deleted file mode 100644 index cd9d9a1..0000000 --- a/samples/OAuthClient/GoogleApps2Legged.aspx +++ /dev/null @@ -1,25 +0,0 @@ -<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master"CodeBehind="GoogleApps2Legged.aspx.cs" Inherits="OAuthConsumer.GoogleApps2Legged" %> - -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View runat="server"> - <h2>Google setup</h2> - <p>A Google client app must be endorsed by a Google user. </p> - <ol> - <li><a target="_blank" href="https://www.google.com/accounts/ManageDomains">Visit Google - and create a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret. - </li> - </ol> - </asp:View> - <asp:View runat="server"> - <h2>Updates</h2> - <p>Ok, Google has authorized us to download your contacts. Click 'Get address book' - to download the first 5 contacts to this sample. Notice how we never asked you - for your Google username or password. </p> - <asp:Button ID="getAddressBookButton" runat="server" OnClick="getAddressBookButton_Click" - Text="Get address book" /> - <asp:PlaceHolder ID="resultsPlaceholder" runat="server" /> - </asp:View> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/GoogleApps2Legged.aspx.cs b/samples/OAuthClient/GoogleApps2Legged.aspx.cs deleted file mode 100644 index afb156b..0000000 --- a/samples/OAuthClient/GoogleApps2Legged.aspx.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace OAuthConsumer { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth; - using DotNetOpenAuth.OAuth.Messages; - - public partial class GoogleApps2Legged : System.Web.UI.Page { - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["GoogleTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["GoogleTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - string accessToken = google.RequestNewClientAccount(); - ////string tokenSecret = google.TokenManager.GetTokenSecret(accessToken); - MessageReceivingEndpoint ep = null; // set up your authorized call here. - google.PrepareAuthorizedRequestAndSend(ep, accessToken); - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/GoogleApps2Legged.aspx.designer.cs b/samples/OAuthClient/GoogleApps2Legged.aspx.designer.cs deleted file mode 100644 index f952937..0000000 --- a/samples/OAuthClient/GoogleApps2Legged.aspx.designer.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthConsumer { - - - public partial class GoogleApps2Legged { - - /// <summary> - /// MultiView1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.MultiView MultiView1; - - /// <summary> - /// getAddressBookButton control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Button getAddressBookButton; - - /// <summary> - /// resultsPlaceholder control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/OAuthClient.csproj b/samples/OAuthClient/OAuthClient.csproj index 8a5cc88..3c94f38 100644 --- a/samples/OAuthClient/OAuthClient.csproj +++ b/samples/OAuthClient/OAuthClient.csproj @@ -55,6 +55,8 @@ <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.ServiceModel" /> <Reference Include="System.Web.Abstractions" /> @@ -75,15 +77,12 @@ <Content Include="Facebook.aspx" /> <Content Include="favicon.ico" /> <Content Include="Global.asax" /> - <Content Include="GoogleAddressBook.aspx" /> - <Content Include="GoogleApps2Legged.aspx" /> <Content Include="images\Sign-in-with-Twitter-darker.png" /> <Content Include="SampleWcf2Javascript.html" /> <Content Include="SampleWcf2Javascript.js" /> <Content Include="Scripts\jquery-1.6.1.js" /> <Content Include="Scripts\jquery-1.6.1.min.js" /> <Content Include="WindowsLive.aspx" /> - <Content Include="Yammer.aspx" /> <Content Include="packages.config" /> <None Include="Service References\SampleResourceServer\DataApi.disco" /> <None Include="Service References\SampleResourceServer\configuration91.svcinfo" /> @@ -93,9 +92,7 @@ <LastGenOutput>Reference.cs</LastGenOutput> </None> <Content Include="SampleWcf2.aspx" /> - <Content Include="SignInWithTwitter.aspx" /> <Content Include="TracePage.aspx" /> - <Content Include="Twitter.aspx" /> <Content Include="Web.config" /> <None Include="Service References\SampleResourceServer\DataApi1.xsd"> <SubType>Designer</SubType> @@ -105,9 +102,7 @@ </None> </ItemGroup> <ItemGroup> - <Compile Include="..\DotNetOpenAuth.ApplicationBlock\InMemoryTokenManager.cs"> - <Link>Code\InMemoryTokenManager.cs</Link> - </Compile> + <Compile Include="Code\Logging.cs" /> <Compile Include="Facebook.aspx.cs"> <DependentUpon>Facebook.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -118,20 +113,10 @@ <Compile Include="Global.asax.cs"> <DependentUpon>Global.asax</DependentUpon> </Compile> - <Compile Include="GoogleAddressBook.aspx.designer.cs"> - <DependentUpon>GoogleAddressBook.aspx</DependentUpon> - </Compile> <Compile Include="SampleWcf2.aspx.cs"> <DependentUpon>SampleWcf2.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> </Compile> - <Compile Include="GoogleApps2Legged.aspx.cs"> - <DependentUpon>GoogleApps2Legged.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="GoogleApps2Legged.aspx.designer.cs"> - <DependentUpon>GoogleApps2Legged.aspx</DependentUpon> - </Compile> <Compile Include="SampleWcf2.aspx.designer.cs"> <DependentUpon>SampleWcf2.aspx</DependentUpon> </Compile> @@ -140,13 +125,6 @@ <DesignTime>True</DesignTime> <DependentUpon>Reference.svcmap</DependentUpon> </Compile> - <Compile Include="SignInWithTwitter.aspx.cs"> - <DependentUpon>SignInWithTwitter.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="SignInWithTwitter.aspx.designer.cs"> - <DependentUpon>SignInWithTwitter.aspx</DependentUpon> - </Compile> <Compile Include="TracePage.aspx.cs"> <DependentUpon>TracePage.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -154,20 +132,8 @@ <Compile Include="TracePage.aspx.designer.cs"> <DependentUpon>TracePage.aspx</DependentUpon> </Compile> - <Compile Include="Twitter.aspx.cs"> - <DependentUpon>Twitter.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="Code\Logging.cs" /> <Compile Include="Code\TracePageAppender.cs" /> - <Compile Include="GoogleAddressBook.aspx.cs"> - <DependentUpon>GoogleAddressBook.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Twitter.aspx.designer.cs"> - <DependentUpon>Twitter.aspx</DependentUpon> - </Compile> <Compile Include="WindowsLive.aspx.cs"> <DependentUpon>WindowsLive.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -175,13 +141,6 @@ <Compile Include="WindowsLive.aspx.designer.cs"> <DependentUpon>WindowsLive.aspx</DependentUpon> </Compile> - <Compile Include="Yammer.aspx.cs"> - <DependentUpon>Yammer.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="Yammer.aspx.designer.cs"> - <DependentUpon>Yammer.aspx</DependentUpon> - </Compile> </ItemGroup> <ItemGroup> <Folder Include="App_Data\" /> diff --git a/samples/OAuthClient/SampleWcf2.aspx b/samples/OAuthClient/SampleWcf2.aspx index cfacaf1..457a409 100644 --- a/samples/OAuthClient/SampleWcf2.aspx +++ b/samples/OAuthClient/SampleWcf2.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="OAuth 2.0 client (web server flow)" Language="C#" MasterPageFile="~/MasterPage.master" +<%@ Page Title="OAuth 2.0 client (web server flow)" Language="C#" MasterPageFile="~/MasterPage.master" Async="true" AutoEventWireup="true" Inherits="OAuthClient.SampleWcf2" CodeBehind="SampleWcf2.aspx.cs" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> diff --git a/samples/OAuthClient/SampleWcf2.aspx.cs b/samples/OAuthClient/SampleWcf2.aspx.cs index 06bbe9b..e96a5c0 100644 --- a/samples/OAuthClient/SampleWcf2.aspx.cs +++ b/samples/OAuthClient/SampleWcf2.aspx.cs @@ -1,143 +1,170 @@ -namespace OAuthClient {
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Net;
- using System.ServiceModel;
- using System.ServiceModel.Channels;
- using System.ServiceModel.Security;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using DotNetOpenAuth.OAuth2;
-
- using SampleResourceServer;
-
- public partial class SampleWcf2 : System.Web.UI.Page {
- /// <summary>
- /// The OAuth 2.0 client object to use to obtain authorization and authorize outgoing HTTP requests.
- /// </summary>
- private static readonly WebServerClient Client;
-
- /// <summary>
- /// The details about the sample OAuth-enabled WCF service that this sample client calls into.
- /// </summary>
- private static AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription {
- TokenEndpoint = new Uri("http://localhost:50172/OAuth/Token"),
- AuthorizationEndpoint = new Uri("http://localhost:50172/OAuth/Authorize"),
- };
-
- /// <summary>
- /// Initializes static members of the <see cref="SampleWcf2"/> class.
- /// </summary>
- static SampleWcf2() {
- Client = new WebServerClient(authServerDescription, "sampleconsumer", "samplesecret");
- }
-
- /// <summary>
- /// Gets or sets the authorization details for the logged in user.
- /// </summary>
- /// <value>The authorization details.</value>
- /// <remarks>
- /// Because this is a sample, we simply store the authorization information in memory with the user session.
- /// A real web app should store at least the access and refresh tokens in this object in a database associated with the user.
- /// </remarks>
- private static IAuthorizationState Authorization {
- get { return (AuthorizationState)HttpContext.Current.Session["Authorization"]; }
- set { HttpContext.Current.Session["Authorization"] = value; }
- }
-
- protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- // Check to see if we're receiving a end user authorization response.
- var authorization = Client.ProcessUserAuthorization();
- if (authorization != null) {
- // We are receiving an authorization response. Store it and associate it with this user.
- Authorization = authorization;
- Response.Redirect(Request.Path); // get rid of the /?code= parameter
- }
- }
-
- if (Authorization != null) {
- // Indicate to the user that we have already obtained authorization on some of these.
- foreach (var li in this.scopeList.Items.OfType<ListItem>().Where(li => Authorization.Scope.Contains(li.Value))) {
- li.Selected = true;
- }
- this.authorizationLabel.Text = "Authorization received!";
- if (Authorization.AccessTokenExpirationUtc.HasValue) {
- TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
- this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " (access token expires in {0} minutes)", Math.Round(timeLeft.TotalMinutes, 1));
- }
- }
-
- this.getNameButton.Enabled = this.getAgeButton.Enabled = this.getFavoriteSites.Enabled = Authorization != null;
- }
-
- protected void getAuthorizationButton_Click(object sender, EventArgs e) {
- string[] scopes = (from item in this.scopeList.Items.OfType<ListItem>()
- where item.Selected
- select item.Value).ToArray();
-
- Client.RequestUserAuthorization(scopes);
- }
-
- protected void getNameButton_Click(object sender, EventArgs e) {
- try {
- this.nameLabel.Text = this.CallService(client => client.GetName());
- } catch (SecurityAccessDeniedException) {
- this.nameLabel.Text = "Access denied!";
- } catch (MessageSecurityException) {
- this.nameLabel.Text = "Access denied!";
- }
- }
-
- protected void getAgeButton_Click(object sender, EventArgs e) {
- try {
- int? age = this.CallService(client => client.GetAge());
- this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available";
- } catch (SecurityAccessDeniedException) {
- this.ageLabel.Text = "Access denied!";
- } catch (MessageSecurityException) {
- this.ageLabel.Text = "Access denied!";
- }
- }
-
- protected void getFavoriteSites_Click(object sender, EventArgs e) {
- try {
- string[] favoriteSites = this.CallService(client => client.GetFavoriteSites());
- this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites);
- } catch (SecurityAccessDeniedException) {
- this.favoriteSitesLabel.Text = "Access denied!";
- } catch (MessageSecurityException) {
- this.favoriteSitesLabel.Text = "Access denied!";
- }
- }
-
- private T CallService<T>(Func<DataApiClient, T> predicate) {
- if (Authorization == null) {
- throw new InvalidOperationException("No access token!");
- }
-
- var wcfClient = new DataApiClient();
-
- // Refresh the access token if it expires and if its lifetime is too short to be of use.
- if (Authorization.AccessTokenExpirationUtc.HasValue) {
- if (Client.RefreshAuthorization(Authorization, TimeSpan.FromSeconds(30))) {
- TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
- this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " - just renewed for {0} more minutes)", Math.Round(timeLeft.TotalMinutes, 1));
- }
- }
-
- var httpRequest = (HttpWebRequest)WebRequest.Create(wcfClient.Endpoint.Address.Uri);
- ClientBase.AuthorizeRequest(httpRequest, Authorization.AccessToken);
-
- var httpDetails = new HttpRequestMessageProperty();
- httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
- using (var scope = new OperationContextScope(wcfClient.InnerChannel)) {
- OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
- return predicate(wcfClient);
- }
- }
- }
+namespace OAuthClient { + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Net; + using System.ServiceModel; + using System.ServiceModel.Channels; + using System.ServiceModel.Security; + using System.Threading; + using System.Threading.Tasks; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2; + using SampleResourceServer; + + public partial class SampleWcf2 : System.Web.UI.Page { + /// <summary> + /// The OAuth 2.0 client object to use to obtain authorization and authorize outgoing HTTP requests. + /// </summary> + private static readonly WebServerClient Client; + + /// <summary> + /// The details about the sample OAuth-enabled WCF service that this sample client calls into. + /// </summary> + private static AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription { + TokenEndpoint = new Uri("http://localhost:50172/OAuth/Token"), + AuthorizationEndpoint = new Uri("http://localhost:50172/OAuth/Authorize"), + }; + + /// <summary> + /// Initializes static members of the <see cref="SampleWcf2"/> class. + /// </summary> + static SampleWcf2() { + Client = new WebServerClient(authServerDescription, "sampleconsumer", "samplesecret"); + } + + /// <summary> + /// Gets or sets the authorization details for the logged in user. + /// </summary> + /// <value>The authorization details.</value> + /// <remarks> + /// Because this is a sample, we simply store the authorization information in memory with the user session. + /// A real web app should store at least the access and refresh tokens in this object in a database associated with the user. + /// </remarks> + private static IAuthorizationState Authorization { + get { return (AuthorizationState)HttpContext.Current.Session["Authorization"]; } + set { HttpContext.Current.Session["Authorization"] = value; } + } + + protected void Page_Load(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!IsPostBack) { + // Check to see if we're receiving a end user authorization response. + var authorization = + await Client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (authorization != null) { + // We are receiving an authorization response. Store it and associate it with this user. + Authorization = authorization; + Response.Redirect(Request.Path); // get rid of the /?code= parameter + } + } + + if (Authorization != null) { + // Indicate to the user that we have already obtained authorization on some of these. + foreach (var li in this.scopeList.Items.OfType<ListItem>().Where(li => Authorization.Scope.Contains(li.Value))) { + li.Selected = true; + } + this.authorizationLabel.Text = "Authorization received!"; + if (Authorization.AccessTokenExpirationUtc.HasValue) { + TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow; + this.authorizationLabel.Text += string.Format( + CultureInfo.CurrentCulture, " (access token expires in {0} minutes)", Math.Round(timeLeft.TotalMinutes, 1)); + } + } + + this.getNameButton.Enabled = this.getAgeButton.Enabled = this.getFavoriteSites.Enabled = Authorization != null; + })); + } + + protected void getAuthorizationButton_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + string[] scopes = + (from item in this.scopeList.Items.OfType<ListItem>() where item.Selected select item.Value).ToArray(); + + var request = + await Client.PrepareRequestUserAuthorizationAsync(scopes, cancellationToken: Response.ClientDisconnectedToken); + await request.SendAsync(); + this.Context.Response.End(); + })); + } + + protected void getNameButton_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + this.nameLabel.Text = await this.CallServiceAsync(client => client.GetName(), Response.ClientDisconnectedToken); + } catch (SecurityAccessDeniedException) { + this.nameLabel.Text = "Access denied!"; + } catch (MessageSecurityException) { + this.nameLabel.Text = "Access denied!"; + } + })); + } + + protected void getAgeButton_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + int? age = await this.CallServiceAsync(client => client.GetAge(), Response.ClientDisconnectedToken); + this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available"; + } catch (SecurityAccessDeniedException) { + this.ageLabel.Text = "Access denied!"; + } catch (MessageSecurityException) { + this.ageLabel.Text = "Access denied!"; + } + })); + } + + protected void getFavoriteSites_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + string[] favoriteSites = + await this.CallServiceAsync(client => client.GetFavoriteSites(), Response.ClientDisconnectedToken); + this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites); + } catch (SecurityAccessDeniedException) { + this.favoriteSitesLabel.Text = "Access denied!"; + } catch (MessageSecurityException) { + this.favoriteSitesLabel.Text = "Access denied!"; + } + })); + } + + private async Task<T> CallServiceAsync<T>(Func<DataApiClient, T> predicate, CancellationToken cancellationToken) { + if (Authorization == null) { + throw new InvalidOperationException("No access token!"); + } + + var wcfClient = new DataApiClient(); + + // Refresh the access token if it expires and if its lifetime is too short to be of use. + if (Authorization.AccessTokenExpirationUtc.HasValue) { + if (await Client.RefreshAuthorizationAsync(Authorization, TimeSpan.FromSeconds(30))) { + TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow; + this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " - just renewed for {0} more minutes)", Math.Round(timeLeft.TotalMinutes, 1)); + } + } + + var httpRequest = (HttpWebRequest)WebRequest.Create(wcfClient.Endpoint.Address.Uri); + ClientBase.AuthorizeRequest(httpRequest, Authorization.AccessToken); + + var httpDetails = new HttpRequestMessageProperty(); + httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; + using (var scope = new OperationContextScope(wcfClient.InnerChannel)) { + OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails; + return predicate(wcfClient); + } + } + } }
\ No newline at end of file diff --git a/samples/OAuthClient/SignInWithTwitter.aspx b/samples/OAuthClient/SignInWithTwitter.aspx deleted file mode 100644 index 9fda5c1..0000000 --- a/samples/OAuthClient/SignInWithTwitter.aspx +++ /dev/null @@ -1,38 +0,0 @@ -<%@ Page Language="C#" AutoEventWireup="true" - Inherits="OAuthClient.SignInWithTwitter" Codebehind="SignInWithTwitter.aspx.cs" %> - -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head runat="server"> - <title>Sign-in with Twitter</title> -</head> -<body> - <form id="form1" runat="server"> - <div> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View ID="View1" runat="server"> - <h2> - Twitter setup</h2> - <p> - A Twitter client app must be endorsed by a Twitter user. - </p> - <ol> - <li><a target="_blank" href="https://twitter.com/oauth_clients">Visit Twitter and create - a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret.</li> - </ol> - </asp:View> - <asp:View ID="View2" runat="server"> - <asp:ImageButton ImageUrl="~/images/Sign-in-with-Twitter-darker.png" runat="server" - AlternateText="Sign In With Twitter" ID="signInButton" OnClick="signInButton_Click" /> - <asp:CheckBox Text="force re-login" runat="server" ID="forceLoginCheckbox" /> - <br /> - <asp:Panel runat="server" ID="loggedInPanel" Visible="false"> - Now logged in as - <asp:Label Text="[name]" runat="server" ID="loggedInName" /> - </asp:Panel> - </asp:View> - </asp:MultiView> - </form> -</body> -</html> diff --git a/samples/OAuthClient/SignInWithTwitter.aspx.cs b/samples/OAuthClient/SignInWithTwitter.aspx.cs deleted file mode 100644 index 04b302c..0000000 --- a/samples/OAuthClient/SignInWithTwitter.aspx.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace OAuthClient { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Web; - using System.Web.Security; - using System.Web.UI; - using System.Web.UI.WebControls; - using System.Xml.Linq; - using System.Xml.XPath; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.OAuth; - - public partial class SignInWithTwitter : System.Web.UI.Page { - protected void Page_Load(object sender, EventArgs e) { - if (TwitterConsumer.IsTwitterConsumerConfigured) { - this.MultiView1.ActiveViewIndex = 1; - - if (!IsPostBack) { - string screenName; - int userId; - if (TwitterConsumer.TryFinishSignInWithTwitter(out screenName, out userId)) { - this.loggedInPanel.Visible = true; - this.loggedInName.Text = screenName; - - // In a real app, the Twitter username would likely be used - // to log the user into the application. - ////FormsAuthentication.RedirectFromLoginPage(screenName, false); - } - } - } - } - - protected void signInButton_Click(object sender, ImageClickEventArgs e) { - TwitterConsumer.StartSignInWithTwitter(this.forceLoginCheckbox.Checked).Send(); - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/SignInWithTwitter.aspx.designer.cs b/samples/OAuthClient/SignInWithTwitter.aspx.designer.cs deleted file mode 100644 index 00126de..0000000 --- a/samples/OAuthClient/SignInWithTwitter.aspx.designer.cs +++ /dev/null @@ -1,87 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class SignInWithTwitter { - - /// <summary> - /// form1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.HtmlControls.HtmlForm form1; - - /// <summary> - /// MultiView1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.MultiView MultiView1; - - /// <summary> - /// View1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.View View1; - - /// <summary> - /// View2 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.View View2; - - /// <summary> - /// signInButton control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.ImageButton signInButton; - - /// <summary> - /// forceLoginCheckbox control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.CheckBox forceLoginCheckbox; - - /// <summary> - /// loggedInPanel control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Panel loggedInPanel; - - /// <summary> - /// loggedInName control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Label loggedInName; - } -} diff --git a/samples/OAuthClient/Twitter.aspx b/samples/OAuthClient/Twitter.aspx deleted file mode 100644 index cb60851..0000000 --- a/samples/OAuthClient/Twitter.aspx +++ /dev/null @@ -1,35 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthClient.Twitter" Codebehind="Twitter.aspx.cs" %> - -<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> -</asp:Content> -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View ID="View1" runat="server"> - <h2>Twitter setup</h2> - <p>A Twitter client app must be endorsed by a Twitter user. </p> - <ol> - <li><a target="_blank" href="https://twitter.com/oauth_clients">Visit Twitter and create - a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret.</li> - </ol> - </asp:View> - <asp:View runat="server"> - <h2>Updates</h2> - <p>Ok, Twitter has authorized us to download your feeds. Notice how we never asked - you for your Twitter username or password. </p> - <p> - Upload a new profile photo: - <asp:FileUpload ID="profilePhoto" runat="server" /> - <asp:Button ID="uploadProfilePhotoButton" runat="server" - onclick="uploadProfilePhotoButton_Click" Text="Upload photo" /> - <asp:Label ID="photoUploadedLabel" runat="server" EnableViewState="False" - Text="Done!" Visible="False"></asp:Label> - </p> - <p> - Click 'Get updates' to download updates to this sample. - </p> - <asp:Button ID="downloadUpdates" runat="server" Text="Get updates" OnClick="downloadUpdates_Click" /> - <asp:PlaceHolder runat="server" ID="resultsPlaceholder" /> - </asp:View> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/Twitter.aspx.cs b/samples/OAuthClient/Twitter.aspx.cs deleted file mode 100644 index 9c0cb9a..0000000 --- a/samples/OAuthClient/Twitter.aspx.cs +++ /dev/null @@ -1,96 +0,0 @@ -namespace OAuthClient { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Text; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using System.Xml.Linq; - using System.Xml.XPath; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.OAuth; - - public partial class Twitter : System.Web.UI.Page { - private string AccessToken { - get { return (string)Session["TwitterAccessToken"]; } - set { Session["TwitterAccessToken"] = value; } - } - - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["TwitterTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["TwitterTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.ActiveViewIndex = 1; - - if (!IsPostBack) { - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - - // Is Twitter calling back with authorization? - var accessTokenResponse = twitter.ProcessUserAuthorization(); - if (accessTokenResponse != null) { - this.AccessToken = accessTokenResponse.AccessToken; - } else if (this.AccessToken == null) { - // If we don't yet have access, immediately request it. - twitter.Channel.Send(twitter.PrepareRequestUserAuthorization()); - } - } - } - } - - protected void downloadUpdates_Click(object sender, EventArgs e) { - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - XPathDocument updates = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader()); - XPathNavigator nav = updates.CreateNavigator(); - var parsedUpdates = from status in nav.Select("/statuses/status").OfType<XPathNavigator>() - where !status.SelectSingleNode("user/protected").ValueAsBoolean - select new { - User = status.SelectSingleNode("user/name").InnerXml, - Status = status.SelectSingleNode("text").InnerXml, - }; - - StringBuilder tableBuilder = new StringBuilder(); - tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>"); - - foreach (var update in parsedUpdates) { - tableBuilder.AppendFormat( - "<tr><td>{0}</td><td>{1}</td></tr>", - HttpUtility.HtmlEncode(update.User), - HttpUtility.HtmlEncode(update.Status)); - } - tableBuilder.Append("</table>"); - this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); - } - - protected void uploadProfilePhotoButton_Click(object sender, EventArgs e) { - if (this.profilePhoto.PostedFile.ContentType == null) { - this.photoUploadedLabel.Visible = true; - this.photoUploadedLabel.Text = "Select a file first."; - return; - } - - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - XDocument imageResult = TwitterConsumer.UpdateProfileImage( - twitter, - this.AccessToken, - this.profilePhoto.PostedFile.InputStream, - this.profilePhoto.PostedFile.ContentType); - this.photoUploadedLabel.Visible = true; - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/Twitter.aspx.designer.cs b/samples/OAuthClient/Twitter.aspx.designer.cs deleted file mode 100644 index e82f477..0000000 --- a/samples/OAuthClient/Twitter.aspx.designer.cs +++ /dev/null @@ -1,78 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class Twitter { - - /// <summary> - /// MultiView1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.MultiView MultiView1; - - /// <summary> - /// View1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.View View1; - - /// <summary> - /// profilePhoto control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.FileUpload profilePhoto; - - /// <summary> - /// uploadProfilePhotoButton control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Button uploadProfilePhotoButton; - - /// <summary> - /// photoUploadedLabel control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Label photoUploadedLabel; - - /// <summary> - /// downloadUpdates control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Button downloadUpdates; - - /// <summary> - /// resultsPlaceholder control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/Web.config b/samples/OAuthClient/Web.config index b17ae43..5fbb439 100644 --- a/samples/OAuthClient/Web.config +++ b/samples/OAuthClient/Web.config @@ -55,21 +55,20 @@ <!-- Windows Live sign-up: http://go.microsoft.com/fwlink/p/?LinkId=193157 --> <add key="windowsLiveAppID" value="000000004408E558" /> <add key="windowsLiveAppSecret" value="od8NVdanEIWqmlKu9hOepBE3AfUu4jCw" /> + + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <connectionStrings/> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> - <compilation debug="true" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <compilation debug="true" targetFramework="4.0" /> <!-- The <authentication> section enables configuration of the security authentication mode used by diff --git a/samples/OAuthClient/WindowsLive.aspx b/samples/OAuthClient/WindowsLive.aspx index ef51223..efdc582 100644 --- a/samples/OAuthClient/WindowsLive.aspx +++ b/samples/OAuthClient/WindowsLive.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WindowsLive.aspx.cs" Inherits="OAuthClient.WindowsLive" %> +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WindowsLive.aspx.cs" Inherits="OAuthClient.WindowsLive" Async="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> diff --git a/samples/OAuthClient/WindowsLive.aspx.cs b/samples/OAuthClient/WindowsLive.aspx.cs index 05101a7..efe41ec 100644 --- a/samples/OAuthClient/WindowsLive.aspx.cs +++ b/samples/OAuthClient/WindowsLive.aspx.cs @@ -9,6 +9,7 @@ using System.Web.UI.WebControls; using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.ApplicationBlock.Facebook; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; public partial class WindowsLive : System.Web.UI.Page { @@ -18,28 +19,38 @@ }; protected void Page_Load(object sender, EventArgs e) { - if (string.Equals("localhost", this.Request.Headers["Host"].Split(':')[0], StringComparison.OrdinalIgnoreCase)) { - this.localhostDoesNotWorkPanel.Visible = true; - var builder = new UriBuilder(this.publicLink.NavigateUrl); - builder.Port = this.Request.Url.Port; - this.publicLink.NavigateUrl = builder.Uri.AbsoluteUri; - this.publicLink.Text = builder.Uri.AbsoluteUri; - } else { - IAuthorizationState authorization = client.ProcessUserAuthorization(); - if (authorization == null) { - // Kick off authorization request - client.RequestUserAuthorization(scope: new[] { WindowsLiveClient.Scopes.Basic }); // this scope isn't even required just to log in - } else { - var request = - WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); - using (var response = request.GetResponse()) { - using (var responseStream = response.GetResponseStream()) { - var graph = WindowsLiveGraph.Deserialize(responseStream); - this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (string.Equals("localhost", this.Request.Headers["Host"].Split(':')[0], StringComparison.OrdinalIgnoreCase)) { + this.localhostDoesNotWorkPanel.Visible = true; + var builder = new UriBuilder(this.publicLink.NavigateUrl); + builder.Port = this.Request.Url.Port; + this.publicLink.NavigateUrl = builder.Uri.AbsoluteUri; + this.publicLink.Text = builder.Uri.AbsoluteUri; + } else { + IAuthorizationState authorization = + await client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (authorization == null) { + // Kick off authorization request + var request = + await client.PrepareRequestUserAuthorizationAsync(scopes: new[] { WindowsLiveClient.Scopes.Basic }); + // this scope isn't even required just to log in + await request.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); + this.Context.Response.End(); + } else { + var request = + WebRequest.Create( + "https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); + using (var response = request.GetResponse()) { + using (var responseStream = response.GetResponseStream()) { + var graph = WindowsLiveGraph.Deserialize(responseStream); + this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); + } + } + } } - } - } - } + })); } } } diff --git a/samples/OAuthClient/Yammer.aspx b/samples/OAuthClient/Yammer.aspx deleted file mode 100644 index a900a2e..0000000 --- a/samples/OAuthClient/Yammer.aspx +++ /dev/null @@ -1,48 +0,0 @@ -<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master" - CodeBehind="Yammer.aspx.cs" Inherits="OAuthClient.Yammer" %> - -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View ID="ClientRegistrationRequiredView" runat="server"> - <h2> - Yammer setup</h2> - <p> - A Yammer client app must be registered. - </p> - <ol> - <li><a target="_blank" href="https://www.yammer.com/client_applications/new">Visit Yammer - and register a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret. - </li> - </ol> - </asp:View> - <asp:View ID="BeginAuthorizationView" runat="server"> - <asp:Label Text="An error occurred in authorization. You may try again." EnableViewState="false" Visible="false" ForeColor="Red" ID="authorizationErrorLabel" runat="server" /> - <asp:Button Text="Obtain authorization now" runat="server" ID="obtainAuthorizationButton" - OnClick="obtainAuthorizationButton_Click" /> - </asp:View> - <asp:View ID="CompleteAuthorizationView" runat="server"> - After you have authorized Yammer to share your information, please enter the code - Yammer gives you here: - <asp:TextBox runat="server" ID="yammerUserCode" EnableViewState="false" /> - <asp:RequiredFieldValidator ErrorMessage="*" ControlToValidate="yammerUserCode" runat="server" /> - <asp:Button Text="Finish" runat="server" ID="finishAuthorizationButton" OnClick="finishAuthorizationButton_Click" /> - </asp:View> - <asp:View ID="AuthorizationCompleteView" runat="server"> - <h2> - Updates - </h2> - <p>The access token we have obtained is: - <asp:Label ID="accessTokenLabel" runat="server" /> - </p> - <p> - Ok, Yammer has authorized us to download your messages. Click 'Get messages' - to download the latest few messages to this sample. Notice how we never asked you - for your Yammer username or password. - </p> - <asp:Button ID="getYammerMessagesButton" runat="server" OnClick="getYammerMessages_Click" - Text="Get address book" /> - <asp:PlaceHolder ID="resultsPlaceholder" runat="server" /> - </asp:View> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/Yammer.aspx.cs b/samples/OAuthClient/Yammer.aspx.cs deleted file mode 100644 index 2e87a62..0000000 --- a/samples/OAuthClient/Yammer.aspx.cs +++ /dev/null @@ -1,76 +0,0 @@ -namespace OAuthClient { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth; - - public partial class Yammer : System.Web.UI.Page { - private string RequestToken { - get { return (string)ViewState["YammerRequestToken"]; } - set { ViewState["YammerRequestToken"] = value; } - } - - private string AccessToken { - get { return (string)Session["YammerAccessToken"]; } - set { Session["YammerAccessToken"] = value; } - } - - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["YammerTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["YammerConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["YammerConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["YammerTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.SetActiveView(this.BeginAuthorizationView); - } - } - - protected void getYammerMessages_Click(object sender, EventArgs e) { - var yammer = new WebConsumer(YammerConsumer.ServiceDescription, this.TokenManager); - } - - protected void obtainAuthorizationButton_Click(object sender, EventArgs e) { - var yammer = YammerConsumer.CreateConsumer(this.TokenManager); - string requestToken; - Uri popupWindowLocation = YammerConsumer.PrepareRequestAuthorization(yammer, out requestToken); - this.RequestToken = requestToken; - string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');"; - this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true); - this.MultiView1.SetActiveView(this.CompleteAuthorizationView); - } - - protected void finishAuthorizationButton_Click(object sender, EventArgs e) { - if (!Page.IsValid) { - return; - } - - var yammer = YammerConsumer.CreateConsumer(this.TokenManager); - var authorizationResponse = YammerConsumer.CompleteAuthorization(yammer, this.RequestToken, this.yammerUserCode.Text); - if (authorizationResponse != null) { - this.accessTokenLabel.Text = HttpUtility.HtmlEncode(authorizationResponse.AccessToken); - this.MultiView1.SetActiveView(this.AuthorizationCompleteView); - } else { - this.MultiView1.SetActiveView(this.BeginAuthorizationView); - this.authorizationErrorLabel.Visible = true; - } - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/Yammer.aspx.designer.cs b/samples/OAuthClient/Yammer.aspx.designer.cs deleted file mode 100644 index 84d75b8..0000000 --- a/samples/OAuthClient/Yammer.aspx.designer.cs +++ /dev/null @@ -1,123 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class Yammer { - - /// <summary> - /// MultiView1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.MultiView MultiView1; - - /// <summary> - /// ClientRegistrationRequiredView control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.View ClientRegistrationRequiredView; - - /// <summary> - /// BeginAuthorizationView control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.View BeginAuthorizationView; - - /// <summary> - /// authorizationErrorLabel control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Label authorizationErrorLabel; - - /// <summary> - /// obtainAuthorizationButton control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Button obtainAuthorizationButton; - - /// <summary> - /// CompleteAuthorizationView control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.View CompleteAuthorizationView; - - /// <summary> - /// yammerUserCode control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.TextBox yammerUserCode; - - /// <summary> - /// finishAuthorizationButton control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Button finishAuthorizationButton; - - /// <summary> - /// AuthorizationCompleteView control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.View AuthorizationCompleteView; - - /// <summary> - /// accessTokenLabel control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Label accessTokenLabel; - - /// <summary> - /// getYammerMessagesButton control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Button getYammerMessagesButton; - - /// <summary> - /// resultsPlaceholder control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/packages.config b/samples/OAuthClient/packages.config index 6562527..8e40260 100644 --- a/samples/OAuthClient/packages.config +++ b/samples/OAuthClient/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OAuthConsumer/GoogleAddressBook.aspx b/samples/OAuthConsumer/GoogleAddressBook.aspx index 19fb505..b4d6a01 100644 --- a/samples/OAuthConsumer/GoogleAddressBook.aspx +++ b/samples/OAuthConsumer/GoogleAddressBook.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="Gmail address book demo" Language="C#" MasterPageFile="~/MasterPage.master" +<%@ Page Title="Gmail address book demo" Language="C#" MasterPageFile="~/MasterPage.master" Async="true" AutoEventWireup="true" Inherits="OAuthConsumer.GoogleAddressBook" Codebehind="GoogleAddressBook.aspx.cs" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> diff --git a/samples/OAuthConsumer/GoogleAddressBook.aspx.cs b/samples/OAuthConsumer/GoogleAddressBook.aspx.cs index ddca7e4..591f658 100644 --- a/samples/OAuthConsumer/GoogleAddressBook.aspx.cs +++ b/samples/OAuthConsumer/GoogleAddressBook.aspx.cs @@ -2,6 +2,7 @@ using System; using System.Configuration; using System.Linq; + using System.Net; using System.Text; using System.Web; using System.Web.UI; @@ -14,62 +15,58 @@ /// A page to demonstrate downloading a Gmail address book using OAuth. /// </summary> public partial class GoogleAddressBook : System.Web.UI.Page { - private string AccessToken { - get { return (string)Session["GoogleAccessToken"]; } + private AccessToken AccessToken { + get { return (AccessToken)Session["GoogleAccessToken"]; } set { Session["GoogleAccessToken"] = value; } } - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["GoogleTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["GoogleTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.ActiveViewIndex = 1; - - if (!IsPostBack) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var google = new GoogleConsumer(); + if (google.ConsumerKey != null) { + this.MultiView1.ActiveViewIndex = 1; - // Is Google calling back with authorization? - var accessTokenResponse = google.ProcessUserAuthorization(); - if (accessTokenResponse != null) { - this.AccessToken = accessTokenResponse.AccessToken; - } else if (this.AccessToken == null) { - // If we don't yet have access, immediately request it. - GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Contacts); - } - } - } + if (!IsPostBack) { + // Is Google calling back with authorization? + var accessTokenResponse = await google.ProcessUserAuthorizationAsync(this.Request.Url); + if (accessTokenResponse != null) { + this.AccessToken = accessTokenResponse.AccessToken; + } else if (this.AccessToken.Token == null) { + // If we don't yet have access, immediately request it. + Uri redirectUri = await google.RequestUserAuthorizationAsync(GoogleConsumer.Applications.Contacts); + this.Response.Redirect(redirectUri.AbsoluteUri); + } + } + } + })); } protected void getAddressBookButton_Click(object sender, EventArgs e) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var google = new GoogleConsumer(); - XDocument contactsDocument = GoogleConsumer.GetContacts(google, this.AccessToken, 5, 1); - var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) - select new { Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value }; - StringBuilder tableBuilder = new StringBuilder(); - tableBuilder.Append("<table><tr><td>Name</td><td>Email</td></tr>"); - foreach (var contact in contacts) { - tableBuilder.AppendFormat( - "<tr><td>{0}</td><td>{1}</td></tr>", - HttpUtility.HtmlEncode(contact.Name), - HttpUtility.HtmlEncode(contact.Email)); - } - tableBuilder.Append("</table>"); - this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); + XDocument contactsDocument = + await google.GetContactsAsync(this.AccessToken, 5, 1, Response.ClientDisconnectedToken); + var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) + select + new { + Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, + Email = + entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value + }; + StringBuilder tableBuilder = new StringBuilder(); + tableBuilder.Append("<table><tr><td>Name</td><td>Email</td></tr>"); + foreach (var contact in contacts) { + tableBuilder.AppendFormat( + "<tr><td>{0}</td><td>{1}</td></tr>", HttpUtility.HtmlEncode(contact.Name), HttpUtility.HtmlEncode(contact.Email)); + } + tableBuilder.Append("</table>"); + this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); + })); } } }
\ No newline at end of file diff --git a/samples/OAuthConsumer/GoogleApps2Legged.aspx b/samples/OAuthConsumer/GoogleApps2Legged.aspx index cd9d9a1..44f0ce2 100644 --- a/samples/OAuthConsumer/GoogleApps2Legged.aspx +++ b/samples/OAuthConsumer/GoogleApps2Legged.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master"CodeBehind="GoogleApps2Legged.aspx.cs" Inherits="OAuthConsumer.GoogleApps2Legged" %> +<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master"CodeBehind="GoogleApps2Legged.aspx.cs" Inherits="OAuthConsumer.GoogleApps2Legged" Async="true" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> diff --git a/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs b/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs index afb156b..52cc885 100644 --- a/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs +++ b/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs @@ -12,28 +12,20 @@ using DotNetOpenAuth.OAuth.Messages; public partial class GoogleApps2Legged : System.Web.UI.Page { - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["GoogleTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["GoogleTokenManager"] = tokenManager; - } - } - - return tokenManager; - } + protected void Page_Load(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var google = new GoogleConsumer(); + var accessToken = await google.RequestNewClientAccountAsync(); + using (var httpClient = google.CreateHttpClient(accessToken.AccessToken)) { + await httpClient.GetAsync("http://someUri", Response.ClientDisconnectedToken); + } + })); } - protected void Page_Load(object sender, EventArgs e) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - string accessToken = google.RequestNewClientAccount(); - ////string tokenSecret = google.TokenManager.GetTokenSecret(accessToken); - MessageReceivingEndpoint ep = null; // set up your authorized call here. - google.PrepareAuthorizedRequestAndSend(ep, accessToken); + protected void getAddressBookButton_Click(object sender, EventArgs e) { + throw new NotImplementedException(); } } }
\ No newline at end of file diff --git a/samples/OAuthConsumer/OAuthConsumer.csproj b/samples/OAuthConsumer/OAuthConsumer.csproj index a42022a..94bed9c 100644 --- a/samples/OAuthConsumer/OAuthConsumer.csproj +++ b/samples/OAuthConsumer/OAuthConsumer.csproj @@ -26,7 +26,7 @@ <AssemblyName>OAuthConsumer</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkProfile /> - <UseIISExpress>false</UseIISExpress> + <UseIISExpress>true</UseIISExpress> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> @@ -53,9 +53,15 @@ <SpecificVersion>False</SpecificVersion> <HintPath>..\..\src\packages\log4net.2.0.0\lib\net40-full\log4net.dll</HintPath> </Reference> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="Newtonsoft.Json"> + <HintPath>..\..\src\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath> + </Reference> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.ServiceModel" /> <Reference Include="System.Drawing" /> @@ -101,9 +107,6 @@ </None> </ItemGroup> <ItemGroup> - <Compile Include="..\DotNetOpenAuth.ApplicationBlock\InMemoryTokenManager.cs"> - <Link>Code\InMemoryTokenManager.cs</Link> - </Compile> <Compile Include="Global.asax.cs"> <DependentUpon>Global.asax</DependentUpon> </Compile> @@ -215,12 +218,11 @@ <VisualStudio> <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"> <WebProjectProperties> - <UseIIS>False</UseIIS> + <UseIIS>True</UseIIS> <AutoAssignPort>False</AutoAssignPort> <DevelopmentServerPort>59721</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> - <IISUrl> - </IISUrl> + <IISUrl>http://localhost:59721/</IISUrl> <NTLMAuthentication>False</NTLMAuthentication> <UseCustomServer>False</UseCustomServer> <CustomServerUrl> diff --git a/samples/OAuthConsumer/SampleWcf.aspx b/samples/OAuthConsumer/SampleWcf.aspx index fb318ce..a44ffa4 100644 --- a/samples/OAuthConsumer/SampleWcf.aspx +++ b/samples/OAuthConsumer/SampleWcf.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthConsumer.SampleWcf" Codebehind="SampleWcf.aspx.cs" %> +<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthConsumer.SampleWcf" Codebehind="SampleWcf.aspx.cs" Async="true" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> <fieldset title="Authorization"> diff --git a/samples/OAuthConsumer/SampleWcf.aspx.cs b/samples/OAuthConsumer/SampleWcf.aspx.cs index d56a161..764b4d7 100644 --- a/samples/OAuthConsumer/SampleWcf.aspx.cs +++ b/samples/OAuthConsumer/SampleWcf.aspx.cs @@ -4,9 +4,13 @@ using System.Globalization; using System.Linq; using System.Net; + using System.Net.Http; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; + using System.Threading.Tasks; + using System.Web; + using System.Web.UI; using System.Web.UI.WebControls; using DotNetOpenAuth; using DotNetOpenAuth.ApplicationBlock; @@ -20,98 +24,109 @@ /// </summary> public partial class SampleWcf : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - if (!IsPostBack) { - if (Session["WcfTokenManager"] != null) { - WebConsumer consumer = this.CreateConsumer(); - var accessTokenMessage = consumer.ProcessUserAuthorization(); - if (accessTokenMessage != null) { - Session["WcfAccessToken"] = accessTokenMessage.AccessToken; - this.authorizationLabel.Text = "Authorized! Access token: " + accessTokenMessage.AccessToken; - } - } - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!IsPostBack) { + var consumer = this.CreateConsumer(); + if (consumer.ConsumerKey != null) { + var accessTokenMessage = await consumer.ProcessUserAuthorizationAsync(this.Request.Url); + if (accessTokenMessage != null) { + Session["WcfAccessToken"] = accessTokenMessage.AccessToken; + this.authorizationLabel.Text = "Authorized! Access token: " + accessTokenMessage.AccessToken; + } + } + } + })); } protected void getAuthorizationButton_Click(object sender, EventArgs e) { - WebConsumer consumer = this.CreateConsumer(); - UriBuilder callback = new UriBuilder(Request.Url); - callback.Query = null; - string[] scopes = (from item in this.scopeList.Items.OfType<ListItem>() - where item.Selected - select item.Value).ToArray(); - string scope = string.Join("|", scopes); - var requestParams = new Dictionary<string, string> { - { "scope", scope }, - }; - var response = consumer.PrepareRequestUserAuthorization(callback.Uri, requestParams, null); - consumer.Channel.Send(response); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var consumer = this.CreateConsumer(); + UriBuilder callback = new UriBuilder(Request.Url); + callback.Query = null; + string[] scopes = + (from item in this.scopeList.Items.OfType<ListItem>() where item.Selected select item.Value).ToArray(); + string scope = string.Join("|", scopes); + var requestParams = new Dictionary<string, string> { { "scope", scope }, }; + Uri redirectUri = await consumer.RequestUserAuthorizationAsync(callback.Uri, requestParams); + this.Response.Redirect(redirectUri.AbsoluteUri); + })); } protected void getNameButton_Click(object sender, EventArgs e) { - try { - this.nameLabel.Text = this.CallService(client => client.GetName()); - } catch (SecurityAccessDeniedException) { - this.nameLabel.Text = "Access denied!"; - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + this.nameLabel.Text = await this.CallServiceAsync(client => client.GetName()); + } catch (SecurityAccessDeniedException) { + this.nameLabel.Text = "Access denied!"; + } + })); } protected void getAgeButton_Click(object sender, EventArgs e) { - try { - int? age = this.CallService(client => client.GetAge()); - this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available"; - } catch (SecurityAccessDeniedException) { - this.ageLabel.Text = "Access denied!"; - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + int? age = await this.CallServiceAsync(client => client.GetAge()); + this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available"; + } catch (SecurityAccessDeniedException) { + this.ageLabel.Text = "Access denied!"; + } + })); } protected void getFavoriteSites_Click(object sender, EventArgs e) { - try { - string[] favoriteSites = this.CallService(client => client.GetFavoriteSites()); - this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites); - } catch (SecurityAccessDeniedException) { - this.favoriteSitesLabel.Text = "Access denied!"; - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + string[] favoriteSites = await this.CallServiceAsync(client => client.GetFavoriteSites()); + this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites); + } catch (SecurityAccessDeniedException) { + this.favoriteSitesLabel.Text = "Access denied!"; + } + })); } - private T CallService<T>(Func<DataApiClient, T> predicate) { + private async Task<T> CallServiceAsync<T>(Func<DataApiClient, T> predicate) { DataApiClient client = new DataApiClient(); var serviceEndpoint = new MessageReceivingEndpoint(client.Endpoint.Address.Uri, HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest); - var accessToken = Session["WcfAccessToken"] as string; - if (accessToken == null) { + var accessToken = (AccessToken)(Session["WcfAccessToken"] ?? default(AccessToken)); + if (accessToken.Token == null) { throw new InvalidOperationException("No access token!"); } - WebConsumer consumer = this.CreateConsumer(); - WebRequest httpRequest = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken); + + var httpRequest = new HttpRequestMessage(HttpMethod.Post, client.Endpoint.Address.Uri); + var consumer = this.CreateConsumer(); + using (var handler = consumer.CreateMessageHandler(accessToken)) { + handler.ApplyAuthorization(httpRequest); + } HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty(); - httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; + httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers.Authorization.ToString(); using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) { OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails; return predicate(client); } } - private WebConsumer CreateConsumer() { + private Consumer CreateConsumer() { string consumerKey = "sampleconsumer"; string consumerSecret = "samplesecret"; - var tokenManager = Session["WcfTokenManager"] as InMemoryTokenManager; - if (tokenManager == null) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Session["WcfTokenManager"] = tokenManager; - } MessageReceivingEndpoint oauthEndpoint = new MessageReceivingEndpoint( new Uri("http://localhost:65169/OAuth.ashx"), HttpDeliveryMethods.PostRequest); - WebConsumer consumer = new WebConsumer( - new ServiceProviderDescription { - RequestTokenEndpoint = oauthEndpoint, - UserAuthorizationEndpoint = oauthEndpoint, - AccessTokenEndpoint = oauthEndpoint, - TamperProtectionElements = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[] { - new HmacSha1SigningBindingElement(), - }, - }, - tokenManager); + var consumer = new Consumer( + consumerKey, + consumerSecret, + new ServiceProviderDescription(oauthEndpoint.Location.AbsoluteUri, oauthEndpoint.Location.AbsoluteUri, oauthEndpoint.Location.AbsoluteUri), + new CookieTemporaryCredentialStorage()); return consumer; } diff --git a/samples/OAuthConsumer/SignInWithTwitter.aspx b/samples/OAuthConsumer/SignInWithTwitter.aspx index 86d29a4..b5c6ad6 100644 --- a/samples/OAuthConsumer/SignInWithTwitter.aspx +++ b/samples/OAuthConsumer/SignInWithTwitter.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" +<%@ Page Language="C#" AutoEventWireup="true" Async="true" Inherits="OAuthConsumer.SignInWithTwitter" Codebehind="SignInWithTwitter.aspx.cs" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> @@ -33,6 +33,7 @@ </asp:Panel> </asp:View> </asp:MultiView> + </div> </form> </body> </html> diff --git a/samples/OAuthConsumer/SignInWithTwitter.aspx.cs b/samples/OAuthConsumer/SignInWithTwitter.aspx.cs index e104f3a..9e422e6 100644 --- a/samples/OAuthConsumer/SignInWithTwitter.aspx.cs +++ b/samples/OAuthConsumer/SignInWithTwitter.aspx.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Configuration; using System.Linq; + using System.Net; using System.Web; using System.Web.Security; using System.Web.UI; @@ -10,30 +11,43 @@ using System.Xml.Linq; using System.Xml.XPath; using DotNetOpenAuth.ApplicationBlock; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; public partial class SignInWithTwitter : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - if (TwitterConsumer.IsTwitterConsumerConfigured) { - this.MultiView1.ActiveViewIndex = 1; + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (TwitterConsumer.IsTwitterConsumerConfigured) { + this.MultiView1.ActiveViewIndex = 1; - if (!IsPostBack) { - string screenName; - int userId; - if (TwitterConsumer.TryFinishSignInWithTwitter(out screenName, out userId)) { - this.loggedInPanel.Visible = true; - this.loggedInName.Text = screenName; + if (!IsPostBack) { + var tuple = await TwitterConsumer.TryFinishSignInWithTwitterAsync(); + if (tuple != null) { + string screenName = tuple.Item1; + int userId = tuple.Item2; + this.loggedInPanel.Visible = true; + this.loggedInName.Text = screenName; - // In a real app, the Twitter username would likely be used - // to log the user into the application. - ////FormsAuthentication.RedirectFromLoginPage(screenName, false); - } - } - } + // In a real app, the Twitter username would likely be used + // to log the user into the application. + ////FormsAuthentication.RedirectFromLoginPage(screenName, false); + } + } + } + })); } protected void signInButton_Click(object sender, ImageClickEventArgs e) { - TwitterConsumer.StartSignInWithTwitter(this.forceLoginCheckbox.Checked).Send(); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + Uri redirectUri = + await + TwitterConsumer.StartSignInWithTwitterAsync(this.forceLoginCheckbox.Checked, Response.ClientDisconnectedToken); + this.Response.Redirect(redirectUri.AbsoluteUri); + })); } } }
\ No newline at end of file diff --git a/samples/OAuthConsumer/Twitter.aspx b/samples/OAuthConsumer/Twitter.aspx index a24c7bd..cf81a12 100644 --- a/samples/OAuthConsumer/Twitter.aspx +++ b/samples/OAuthConsumer/Twitter.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthConsumer.Twitter" Codebehind="Twitter.aspx.cs" %> +<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthConsumer.Twitter" Codebehind="Twitter.aspx.cs" Async="true" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> </asp:Content> diff --git a/samples/OAuthConsumer/Twitter.aspx.cs b/samples/OAuthConsumer/Twitter.aspx.cs index 8288ed0..42ffa6e 100644 --- a/samples/OAuthConsumer/Twitter.aspx.cs +++ b/samples/OAuthConsumer/Twitter.aspx.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Configuration; using System.Linq; + using System.Net; using System.Text; using System.Web; using System.Web.UI; @@ -10,87 +11,79 @@ using System.Xml.Linq; using System.Xml.XPath; using DotNetOpenAuth.ApplicationBlock; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; public partial class Twitter : System.Web.UI.Page { - private string AccessToken { - get { return (string)Session["TwitterAccessToken"]; } + private AccessToken AccessToken { + get { return (AccessToken)(Session["TwitterAccessToken"] ?? new AccessToken()); } set { Session["TwitterAccessToken"] = value; } } - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["TwitterTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["TwitterTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.ActiveViewIndex = 1; + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var twitter = new TwitterConsumer(); + if (twitter.ConsumerKey != null) { + this.MultiView1.ActiveViewIndex = 1; - if (!IsPostBack) { - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - - // Is Twitter calling back with authorization? - var accessTokenResponse = twitter.ProcessUserAuthorization(); - if (accessTokenResponse != null) { - this.AccessToken = accessTokenResponse.AccessToken; - } else if (this.AccessToken == null) { - // If we don't yet have access, immediately request it. - twitter.Channel.Send(twitter.PrepareRequestUserAuthorization()); - } - } - } + if (!IsPostBack) { + // Is Twitter calling back with authorization? + var accessTokenResponse = await twitter.ProcessUserAuthorizationAsync(this.Request.Url); + if (accessTokenResponse != null) { + this.AccessToken = accessTokenResponse.AccessToken; + } else { + // If we don't yet have access, immediately request it. + Uri redirectUri = await twitter.RequestUserAuthorizationAsync(MessagingUtilities.GetPublicFacingUrl()); + this.Response.Redirect(redirectUri.AbsoluteUri); + } + } + } + })); } protected void downloadUpdates_Click(object sender, EventArgs e) { - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - XPathDocument updates = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader()); - XPathNavigator nav = updates.CreateNavigator(); - var parsedUpdates = from status in nav.Select("/statuses/status").OfType<XPathNavigator>() - where !status.SelectSingleNode("user/protected").ValueAsBoolean - select new { - User = status.SelectSingleNode("user/name").InnerXml, - Status = status.SelectSingleNode("text").InnerXml, - }; + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var twitter = new TwitterConsumer(); + var statusesJson = await twitter.GetUpdatesAsync(this.AccessToken); + + StringBuilder tableBuilder = new StringBuilder(); + tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>"); - StringBuilder tableBuilder = new StringBuilder(); - tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>"); + foreach (dynamic update in statusesJson) { + if (!update.user.@protected.Value) { + tableBuilder.AppendFormat( + "<tr><td>{0}</td><td>{1}</td></tr>", + HttpUtility.HtmlEncode(update.user.screen_name), + HttpUtility.HtmlEncode(update.text)); + } + } - foreach (var update in parsedUpdates) { - tableBuilder.AppendFormat( - "<tr><td>{0}</td><td>{1}</td></tr>", - HttpUtility.HtmlEncode(update.User), - HttpUtility.HtmlEncode(update.Status)); - } - tableBuilder.Append("</table>"); - this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); + tableBuilder.Append("</table>"); + this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); + })); } protected void uploadProfilePhotoButton_Click(object sender, EventArgs e) { - if (this.profilePhoto.PostedFile.ContentType == null) { - this.photoUploadedLabel.Visible = true; - this.photoUploadedLabel.Text = "Select a file first."; - return; - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (this.profilePhoto.PostedFile.ContentType == null) { + this.photoUploadedLabel.Visible = true; + this.photoUploadedLabel.Text = "Select a file first."; + return; + } - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - XDocument imageResult = TwitterConsumer.UpdateProfileImage( - twitter, - this.AccessToken, - this.profilePhoto.PostedFile.InputStream, - this.profilePhoto.PostedFile.ContentType); - this.photoUploadedLabel.Visible = true; + var twitter = new TwitterConsumer(); + XDocument imageResult = + await + twitter.UpdateProfileImageAsync( + this.AccessToken, this.profilePhoto.PostedFile.InputStream, this.profilePhoto.PostedFile.ContentType); + this.photoUploadedLabel.Visible = true; + })); } } }
\ No newline at end of file diff --git a/samples/OAuthConsumer/Web.config b/samples/OAuthConsumer/Web.config index 3330335..69dab78 100644 --- a/samples/OAuthConsumer/Web.config +++ b/samples/OAuthConsumer/Web.config @@ -37,29 +37,28 @@ <!-- Fill in your various consumer keys and secrets here to make the sample work. --> <!-- You must get these values by signing up with each individual service provider. --> <!-- Twitter sign-up: https://twitter.com/oauth_clients --> - <add key="twitterConsumerKey" value="" /> - <add key="twitterConsumerSecret" value="" /> + <add key="twitterConsumerKey" value="5ZxhT5fqIodtU8fa7mA0w" /> + <add key="twitterConsumerSecret" value="pZxtR63tLeMc8sd4rOqnZQqQjmfLiUMEWMokYFIjKq4" /> <!-- Google sign-up: https://www.google.com/accounts/ManageDomains --> <add key="googleConsumerKey" value="anonymous"/> <add key="googleConsumerSecret" value="anonymous"/> <!-- Yammer sign-up: https://www.yammer.com/client_applications/new --> <add key="yammerConsumerKey" value=""/> <add key="yammerConsumerSecret" value=""/> + + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <connectionStrings/> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> - <compilation debug="true" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <compilation debug="true" targetFramework="4.0" /> <!-- The <authentication> section enables configuration of the security authentication mode used by diff --git a/samples/OAuthConsumer/Yammer.aspx.cs b/samples/OAuthConsumer/Yammer.aspx.cs index d8993fe..d139e4f 100644 --- a/samples/OAuthConsumer/Yammer.aspx.cs +++ b/samples/OAuthConsumer/Yammer.aspx.cs @@ -11,66 +11,54 @@ using DotNetOpenAuth.OAuth; public partial class Yammer : System.Web.UI.Page { - private string RequestToken { - get { return (string)ViewState["YammerRequestToken"]; } - set { ViewState["YammerRequestToken"] = value; } - } - - private string AccessToken { - get { return (string)Session["YammerAccessToken"]; } + private AccessToken AccessToken { + get { return (AccessToken)Session["YammerAccessToken"]; } set { Session["YammerAccessToken"] = value; } } - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["YammerTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["YammerConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["YammerConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["YammerTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { + var yammer = new YammerConsumer(); + if (yammer.ConsumerKey != null) { this.MultiView1.SetActiveView(this.BeginAuthorizationView); } } protected void getYammerMessages_Click(object sender, EventArgs e) { - var yammer = new WebConsumer(YammerConsumer.ServiceDescription, this.TokenManager); + var yammer = new YammerConsumer(); + + // TODO: code here } protected void obtainAuthorizationButton_Click(object sender, EventArgs e) { - var yammer = YammerConsumer.CreateConsumer(this.TokenManager); - string requestToken; - Uri popupWindowLocation = YammerConsumer.PrepareRequestAuthorization(yammer, out requestToken); - this.RequestToken = requestToken; - string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');"; - this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true); - this.MultiView1.SetActiveView(this.CompleteAuthorizationView); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var yammer = new YammerConsumer(); + Uri popupWindowLocation = await yammer.RequestUserAuthorizationAsync(MessagingUtilities.GetPublicFacingUrl()); + string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');"; + this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true); + this.MultiView1.SetActiveView(this.CompleteAuthorizationView); + })); } protected void finishAuthorizationButton_Click(object sender, EventArgs e) { - if (!Page.IsValid) { - return; - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!Page.IsValid) { + return; + } - var yammer = YammerConsumer.CreateConsumer(this.TokenManager); - var authorizationResponse = YammerConsumer.CompleteAuthorization(yammer, this.RequestToken, this.yammerUserCode.Text); - if (authorizationResponse != null) { - this.accessTokenLabel.Text = HttpUtility.HtmlEncode(authorizationResponse.AccessToken); - this.MultiView1.SetActiveView(this.AuthorizationCompleteView); - } else { - this.MultiView1.SetActiveView(this.BeginAuthorizationView); - this.authorizationErrorLabel.Visible = true; - } + var yammer = new YammerConsumer(); + var authorizationResponse = await yammer.ProcessUserAuthorizationAsync(this.yammerUserCode.Text); + if (authorizationResponse != null) { + this.accessTokenLabel.Text = HttpUtility.HtmlEncode(authorizationResponse.AccessToken); + this.MultiView1.SetActiveView(this.AuthorizationCompleteView); + } else { + this.MultiView1.SetActiveView(this.BeginAuthorizationView); + this.authorizationErrorLabel.Visible = true; + } + })); } } }
\ No newline at end of file diff --git a/samples/OAuthConsumer/packages.config b/samples/OAuthConsumer/packages.config index 6562527..cf38da4 100644 --- a/samples/OAuthConsumer/packages.config +++ b/samples/OAuthConsumer/packages.config @@ -1,4 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OAuthConsumerWpf/Authorize.xaml.cs b/samples/OAuthConsumerWpf/Authorize.xaml.cs index 4ed1932..78c9c70 100644 --- a/samples/OAuthConsumerWpf/Authorize.xaml.cs +++ b/samples/OAuthConsumerWpf/Authorize.xaml.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading; + using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; @@ -20,31 +21,28 @@ /// Interaction logic for Authorize.xaml /// </summary> public partial class Authorize : Window { - private DesktopConsumer consumer; - private string requestToken; + private Consumer consumer; - internal Authorize(DesktopConsumer consumer, FetchUri fetchUriCallback) { + internal Authorize(Consumer consumer, Func<Consumer, Task<Uri>> fetchUriCallback) { this.InitializeComponent(); this.consumer = consumer; Cursor original = this.Cursor; this.Cursor = Cursors.Wait; - ThreadPool.QueueUserWorkItem(delegate(object state) { - Uri browserAuthorizationLocation = fetchUriCallback(this.consumer, out this.requestToken); + Task.Run(async delegate { + Uri browserAuthorizationLocation = await fetchUriCallback(this.consumer); System.Diagnostics.Process.Start(browserAuthorizationLocation.AbsoluteUri); - this.Dispatcher.BeginInvoke(new Action(() => { + await this.Dispatcher.BeginInvoke(new Action(() => { this.Cursor = original; finishButton.IsEnabled = true; })); }); } - internal delegate Uri FetchUri(DesktopConsumer consumer, out string requestToken); + internal AccessToken AccessToken { get; set; } - internal string AccessToken { get; set; } - - private void finishButton_Click(object sender, RoutedEventArgs e) { - var grantedAccess = this.consumer.ProcessUserAuthorization(this.requestToken, this.verifierBox.Text); + private async void finishButton_Click(object sender, RoutedEventArgs e) { + var grantedAccess = await this.consumer.ProcessUserAuthorizationAsync(this.verifierBox.Text); this.AccessToken = grantedAccess.AccessToken; DialogResult = true; Close(); diff --git a/samples/OAuthConsumerWpf/Authorize2.xaml.cs b/samples/OAuthConsumerWpf/Authorize2.xaml.cs index f45af5c..71d76a8 100644 --- a/samples/OAuthConsumerWpf/Authorize2.xaml.cs +++ b/samples/OAuthConsumerWpf/Authorize2.xaml.cs @@ -31,8 +31,12 @@ get { return this.clientAuthorizationView.Authorization; } } + public ClientAuthorizationView ClientAuthorizationView { + get { return this.clientAuthorizationView; } + } + private void clientAuthorizationView_Completed(object sender, ClientAuthorizationCompleteEventArgs e) { - this.DialogResult = e.Authorization != null; + this.DialogResult = e.Authorization != null && e.Authorization.AccessToken != null; this.Close(); } } diff --git a/samples/OAuthConsumerWpf/InMemoryTokenManager.cs b/samples/OAuthConsumerWpf/InMemoryTokenManager.cs deleted file mode 100644 index 5266404..0000000 --- a/samples/OAuthConsumerWpf/InMemoryTokenManager.cs +++ /dev/null @@ -1,58 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="InMemoryTokenManager.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Samples.OAuthConsumerWpf { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - - internal class InMemoryTokenManager : IConsumerTokenManager { - private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); - - internal InMemoryTokenManager() { - } - - public string ConsumerKey { get; internal set; } - - public string ConsumerSecret { get; internal set; } - - #region ITokenManager Members - - public string GetConsumerSecret(string consumerKey) { - if (consumerKey == this.ConsumerKey) { - return this.ConsumerSecret; - } else { - throw new ArgumentException("Unrecognized consumer key.", "consumerKey"); - } - } - - public string GetTokenSecret(string token) { - return this.tokensAndSecrets[token]; - } - - public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { - this.tokensAndSecrets[response.Token] = response.TokenSecret; - } - - public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { - this.tokensAndSecrets.Remove(requestToken); - this.tokensAndSecrets[accessToken] = accessTokenSecret; - } - - /// <summary> - /// Classifies a token as a request token or an access token. - /// </summary> - /// <param name="token">The token to classify.</param> - /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> - public TokenType GetTokenType(string token) { - throw new NotImplementedException(); - } - - #endregion - } -} diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml b/samples/OAuthConsumerWpf/MainWindow.xaml index 48eb0c4..979bc7e 100644 --- a/samples/OAuthConsumerWpf/MainWindow.xaml +++ b/samples/OAuthConsumerWpf/MainWindow.xaml @@ -92,30 +92,20 @@ </Grid.ColumnDefinitions> <Label Grid.Row="0">Request Token URL</Label> <TextBox Grid.Column="1" x:Name="requestTokenUrlBox" /> - <ComboBox Grid.Column="2" x:Name="requestTokenHttpMethod" SelectedIndex="1"> - <ComboBox.Items> - <ComboBoxItem>GET</ComboBoxItem> - <ComboBoxItem>POST</ComboBoxItem> - </ComboBox.Items> - </ComboBox> + <Label Grid.Column="2">POST</Label> <Label Grid.Row="1">Authorize URL</Label> <TextBox Grid.Row="1" Grid.Column="1" x:Name="authorizeUrlBox" /> <Label Grid.Row="1" Grid.Column="2">GET</Label> <Label Grid.Row="2">Access Token URL</Label> <TextBox Grid.Row="2" Grid.Column="1" x:Name="accessTokenUrlBox" /> - <ComboBox Grid.Row="2" Grid.Column="2" x:Name="accessTokenHttpMethod" SelectedIndex="1"> - <ComboBox.Items> - <ComboBoxItem>GET</ComboBoxItem> - <ComboBoxItem>POST</ComboBoxItem> - </ComboBox.Items> - </ComboBox> + <Label Grid.Row="2" Grid.Column="2">POST</Label> <Label Grid.Row="3">Resource URL</Label> <TextBox Grid.Row="3" Grid.Column="1" x:Name="resourceUrlBox" /> <ComboBox Grid.Row="3" Grid.Column="2" x:Name="resourceHttpMethodList" SelectedIndex="0"> <ComboBox.Items> - <ComboBoxItem>GET w/ header</ComboBoxItem> - <ComboBoxItem>GET w/ querystring</ComboBoxItem> - <ComboBoxItem>POST</ComboBoxItem> + <ComboBoxItem>GET w/ header</ComboBoxItem> + <ComboBoxItem>GET w/ querystring</ComboBoxItem> + <ComboBoxItem>POST</ComboBoxItem> </ComboBox.Items> </ComboBox> <Label Grid.Row="4">Consumer key</Label> @@ -123,10 +113,9 @@ <Label Grid.Row="5">Consumer secret</Label> <TextBox Grid.Row="5" Grid.Column="1" x:Name="consumerSecretBox" Grid.ColumnSpan="2"/> <Label Grid.Row="6">OAuth version</Label> - <ComboBox Grid.Row="6" Grid.Column="1" SelectedIndex="1" x:Name="oauthVersion"> + <ComboBox Grid.Row="6" Grid.Column="1" SelectedIndex="0" x:Name="oauthVersion"> <ComboBox.Items> - <ComboBoxItem>1.0</ComboBoxItem> - <ComboBoxItem>1.0a</ComboBoxItem> + <ComboBoxItem>RFC 5849</ComboBoxItem> </ComboBox.Items> </ComboBox> <Button Grid.Row="7" Grid.Column="1" x:Name="beginButton" Click="beginButton_Click">Begin</Button> @@ -153,27 +142,26 @@ <ColumnDefinition Width="auto" /> </Grid.ColumnDefinitions> <Label Grid.Row="1" TabIndex="202">Token Endpoint URL</Label> - <TextBox Grid.Row="1" Grid.Column="1" x:Name="oauth2TokenEndpointBox" Text="http://localhost:18916/OAuthTokenEndpoint.ashx" TabIndex="203" /> + <TextBox Grid.Row="1" Grid.Column="1" x:Name="oauth2TokenEndpointBox" Text="http://localhost:23603/api/token" TabIndex="203" /> <Label Grid.Row="1" Grid.Column="2" TabIndex="204">POST</Label> <Label Grid.Row="2" TabIndex="205">User Authorization URL</Label> - <TextBox Grid.Row="2" Grid.Column="1" x:Name="oauth2AuthorizationUrlBox" Text="http://localhost:18916/Account/Authorize" TabIndex="206" /> + <TextBox Grid.Row="2" Grid.Column="1" x:Name="oauth2AuthorizationUrlBox" Text="http://localhost:23603/user/Authorize" TabIndex="206" /> <Label Grid.Row="2" Grid.Column="2" TabIndex="207">GET</Label> <Label Grid.Row="0" TabIndex="200">Grant Type</Label> <ComboBox Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" x:Name="flowBox" SelectedIndex="0" TabIndex="201"> <ComboBox.Items> <ComboBoxItem>Authorization Code</ComboBoxItem> <ComboBoxItem>Implicit Grant</ComboBoxItem> - <ComboBoxItem>Resource Owner Password Credentials</ComboBoxItem> + <!--<ComboBoxItem>Resource Owner Password Credentials</ComboBoxItem>--> </ComboBox.Items> </ComboBox> <Label Grid.Row="3" TabIndex="207">Resource URL</Label> - <TextBox Grid.Row="3" Grid.Column="1" x:Name="oauth2ResourceUrlBox" Text="http://localhost:18916/" TabIndex="208" /> + <TextBox Grid.Row="3" Grid.Column="1" x:Name="oauth2ResourceUrlBox" Text="http://localhost:23603/api/values" TabIndex="208" /> <ComboBox Grid.Row="3" Grid.Column="2" x:Name="oauth2ResourceHttpMethodList" SelectedIndex="0" TabIndex="209"> <ComboBox.Items> - <ComboBoxItem>GET w/ header</ComboBoxItem> - <ComboBoxItem>GET w/ querystring</ComboBoxItem> - <ComboBoxItem>POST</ComboBoxItem> - </ComboBox.Items> + <ComboBoxItem>GET</ComboBoxItem> + <ComboBoxItem>POST</ComboBoxItem> + </ComboBox.Items> </ComboBox> <Label Grid.Row="4" TabIndex="210">Client Identifier</Label> <TextBox Grid.Row="4" Grid.Column="1" x:Name="oauth2ClientIdentifierBox" Grid.ColumnSpan="2" Text="a" TabIndex="211" /> @@ -184,7 +172,7 @@ <Label Grid.Row="7" TabIndex="216">OAuth 2.0 version</Label> <ComboBox Grid.Row="7" Grid.Column="1" SelectedIndex="0" x:Name="oauth2Version" TabIndex="217"> <ComboBox.Items> - <ComboBoxItem>2.0 DRAFT 16</ComboBoxItem> + <ComboBoxItem>RFC 6749</ComboBoxItem> </ComboBox.Items> </ComboBox> <Button Grid.Row="8" Grid.Column="1" x:Name="oauth2BeginButton" Click="oauth2BeginButton_Click" TabIndex="218">Begin</Button> diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml.cs b/samples/OAuthConsumerWpf/MainWindow.xaml.cs index 310c2c6..d58df8c 100644 --- a/samples/OAuthConsumerWpf/MainWindow.xaml.cs +++ b/samples/OAuthConsumerWpf/MainWindow.xaml.cs @@ -6,21 +6,21 @@ using System.IO; using System.Linq; using System.Net; + using System.Net.Http; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Channels; + using System.Threading; + using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Xml.Linq; - using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.Samples.OAuthConsumerWpf.WcfSampleService; - using OAuth2; - using OAuth2 = DotNetOpenAuth.OAuth2; using ProtocolVersion = DotNetOpenAuth.OAuth.ProtocolVersion; @@ -28,9 +28,8 @@ /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { - private InMemoryTokenManager googleTokenManager = new InMemoryTokenManager(); - private DesktopConsumer google; - private string googleAccessToken; + private GoogleConsumer google; + private DotNetOpenAuth.OAuth.AccessToken googleAccessToken; private UserAgentClient wcf; private IAuthorizationState wcfAccessToken; @@ -42,17 +41,12 @@ } private void InitializeGoogleConsumer() { - this.googleTokenManager.ConsumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - this.googleTokenManager.ConsumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - string pfxFile = ConfigurationManager.AppSettings["googleConsumerCertificateFile"]; - if (string.IsNullOrEmpty(pfxFile)) { - this.google = new DesktopConsumer(GoogleConsumer.ServiceDescription, this.googleTokenManager); - } else { + this.google = new GoogleConsumer(); + if (!string.IsNullOrEmpty(pfxFile)) { string pfxPassword = ConfigurationManager.AppSettings["googleConsumerCertificatePassword"]; var signingCertificate = new X509Certificate2(pfxFile, pfxPassword); - var service = GoogleConsumer.CreateRsaSha1ServiceDescription(signingCertificate); - this.google = new DesktopConsumer(service, this.googleTokenManager); + this.google.ConsumerCertificate = signingCertificate; } } @@ -64,25 +58,22 @@ this.wcf = new UserAgentClient(authServer, "sampleconsumer", "samplesecret"); } - private void beginAuthorizationButton_Click(object sender, RoutedEventArgs e) { - if (string.IsNullOrEmpty(this.googleTokenManager.ConsumerKey)) { + private async void beginAuthorizationButton_Click(object sender, RoutedEventArgs e) { + if (string.IsNullOrEmpty(this.google.ConsumerKey)) { MessageBox.Show(this, "You must modify the App.config or OAuthConsumerWpf.exe.config file for this application to include your Google OAuth consumer key first.", "Configuration required", MessageBoxButton.OK, MessageBoxImage.Stop); return; } var auth = new Authorize( this.google, - (DesktopConsumer consumer, out string requestToken) => - GoogleConsumer.RequestAuthorization( - consumer, - GoogleConsumer.Applications.Contacts | GoogleConsumer.Applications.Blogger, - out requestToken)); + consumer => + ((GoogleConsumer)consumer).RequestUserAuthorizationAsync(GoogleConsumer.Applications.Contacts | GoogleConsumer.Applications.Blogger)); bool? result = auth.ShowDialog(); if (result.HasValue && result.Value) { this.googleAccessToken = auth.AccessToken; this.postButton.IsEnabled = true; - XDocument contactsDocument = GoogleConsumer.GetContacts(this.google, this.googleAccessToken, 25, 1); + XDocument contactsDocument = await this.google.GetContactsAsync(this.googleAccessToken); var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) select new { Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value }; this.contactsGrid.Children.Clear(); @@ -99,12 +90,12 @@ } } - private void postButton_Click(object sender, RoutedEventArgs e) { + private async void postButton_Click(object sender, RoutedEventArgs e) { XElement postBodyXml = XElement.Parse(this.postBodyBox.Text); - GoogleConsumer.PostBlogEntry(this.google, this.googleAccessToken, this.blogUrlBox.Text, this.postTitleBox.Text, postBodyXml); + await this.google.PostBlogEntryAsync(this.googleAccessToken, this.blogUrlBox.Text, this.postTitleBox.Text, postBodyXml); } - private void beginWcfAuthorizationButton_Click(object sender, RoutedEventArgs e) { + private async void beginWcfAuthorizationButton_Click(object sender, RoutedEventArgs e) { var auth = new Authorize2(this.wcf); auth.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes("http://tempuri.org/IDataApi/GetName http://tempuri.org/IDataApi/GetAge http://tempuri.org/IDataApi/GetFavoriteSites")); auth.Authorization.Callback = new Uri("http://localhost:59721/"); @@ -112,20 +103,20 @@ bool? result = auth.ShowDialog(); if (result.HasValue && result.Value) { this.wcfAccessToken = auth.Authorization; - this.wcfName.Content = this.CallService(client => client.GetName()); - this.wcfAge.Content = this.CallService(client => client.GetAge()); - this.wcfFavoriteSites.Content = this.CallService(client => string.Join(", ", client.GetFavoriteSites())); + this.wcfName.Content = await this.CallServiceAsync(client => client.GetName()); + this.wcfAge.Content = await this.CallServiceAsync(client => client.GetAge()); + this.wcfFavoriteSites.Content = await this.CallServiceAsync(client => string.Join(", ", client.GetFavoriteSites())); } } - private T CallService<T>(Func<DataApiClient, T> predicate) { + private async Task<T> CallServiceAsync<T>(Func<DataApiClient, T> predicate) { DataApiClient client = new DataApiClient(); if (this.wcfAccessToken == null) { throw new InvalidOperationException("No access token!"); } var httpRequest = (HttpWebRequest)WebRequest.Create(client.Endpoint.Address.Uri); - this.wcf.AuthorizeRequest(httpRequest, this.wcfAccessToken); + await this.wcf.AuthorizeRequestAsync(httpRequest, this.wcfAccessToken, CancellationToken.None); HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty(); httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; @@ -135,54 +126,42 @@ } } - private void beginButton_Click(object sender, RoutedEventArgs e) { + private async void beginButton_Click(object sender, RoutedEventArgs e) { try { - var service = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint(this.requestTokenUrlBox.Text, this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint(this.authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint(this.accessTokenUrlBox.Text, this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - ProtocolVersion = this.oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a, - }; - var tokenManager = new InMemoryTokenManager(); - tokenManager.ConsumerKey = this.consumerKeyBox.Text; - tokenManager.ConsumerSecret = this.consumerSecretBox.Text; - - var consumer = new DesktopConsumer(service, tokenManager); - string accessToken; - if (service.ProtocolVersion == ProtocolVersion.V10) { - string requestToken; - Uri authorizeUrl = consumer.RequestUserAuthorization(null, null, out requestToken); - Process.Start(authorizeUrl.AbsoluteUri); - MessageBox.Show(this, "Click OK when you've authorized the app."); - var authorizationResponse = consumer.ProcessUserAuthorization(requestToken, null); - accessToken = authorizationResponse.AccessToken; + var service = new ServiceProviderDescription( + this.requestTokenUrlBox.Text, + this.authorizeUrlBox.Text, + this.accessTokenUrlBox.Text); + + var consumer = new Consumer(this.consumerKeyBox.Text, this.consumerSecretBox.Text, service, new MemoryTemporaryCredentialStorage()); + DotNetOpenAuth.OAuth.AccessToken accessToken; + var authorizePopup = new Authorize(consumer, c => c.RequestUserAuthorizationAsync(null, null)); + authorizePopup.Owner = this; + bool? result = authorizePopup.ShowDialog(); + if (result.HasValue && result.Value) { + accessToken = authorizePopup.AccessToken; } else { - var authorizePopup = new Authorize( - consumer, - (DesktopConsumer c, out string requestToken) => c.RequestUserAuthorization(null, null, out requestToken)); - authorizePopup.Owner = this; - bool? result = authorizePopup.ShowDialog(); - if (result.HasValue && result.Value) { - accessToken = authorizePopup.AccessToken; - } else { - return; - } - } - HttpDeliveryMethods resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest; - if (this.resourceHttpMethodList.SelectedIndex == 1) { - resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest; + return; } - var resourceEndpoint = new MessageReceivingEndpoint(this.resourceUrlBox.Text, resourceHttpMethod); - using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken)) { - this.resultsBox.Text = resourceResponse.GetResponseReader().ReadToEnd(); + + HttpMethod resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpMethod.Get : HttpMethod.Post; + using (var handler = consumer.CreateMessageHandler(accessToken)) { + handler.Location = this.resourceHttpMethodList.SelectedIndex == 1 + ? OAuth1HttpMessageHandlerBase.OAuthParametersLocation.AuthorizationHttpHeader + : OAuth1HttpMessageHandlerBase.OAuthParametersLocation.QueryString; + using (var httpClient = consumer.CreateHttpClient(handler)) { + var request = new HttpRequestMessage(resourceHttpMethod, this.resourceUrlBox.Text); + using (var resourceResponse = await httpClient.SendAsync(request)) { + this.resultsBox.Text = await resourceResponse.Content.ReadAsStringAsync(); + } + } } } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { MessageBox.Show(this, ex.Message); } } - private void oauth2BeginButton_Click(object sender, RoutedEventArgs e) { + private async void oauth2BeginButton_Click(object sender, RoutedEventArgs e) { var authServer = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription { AuthorizationEndpoint = new Uri(this.oauth2AuthorizationUrlBox.Text), }; @@ -195,27 +174,19 @@ var authorizePopup = new Authorize2(client); authorizePopup.Authorization.Scope.AddRange(OAuthUtilities.SplitScopes(this.oauth2ScopeBox.Text)); + authorizePopup.Authorization.Callback = new Uri("http://www.microsoft.com/en-us/default.aspx"); authorizePopup.Owner = this; + authorizePopup.ClientAuthorizationView.RequestImplicitGrant = flowBox.SelectedIndex == 1; bool? result = authorizePopup.ShowDialog(); if (result.HasValue && result.Value) { - var requestUri = new UriBuilder(this.oauth2ResourceUrlBox.Text); - if (this.oauth2ResourceHttpMethodList.SelectedIndex > 0) { - requestUri.AppendQueryArgument("access_token", authorizePopup.Authorization.AccessToken); - } - - var request = (HttpWebRequest)WebRequest.Create(requestUri.Uri); - request.Method = this.oauth2ResourceHttpMethodList.SelectedIndex < 2 ? "GET" : "POST"; - if (this.oauth2ResourceHttpMethodList.SelectedIndex == 0) { - client.AuthorizeRequest(request, authorizePopup.Authorization); - } - - using (var resourceResponse = request.GetResponse()) { - using (var responseStream = new StreamReader(resourceResponse.GetResponseStream())) { - this.oauth2ResultsBox.Text = responseStream.ReadToEnd(); + var request = new HttpRequestMessage( + new HttpMethod(((ComboBoxItem)this.oauth2ResourceHttpMethodList.SelectedValue).Content.ToString()), + this.oauth2ResourceUrlBox.Text); + using (var httpClient = new HttpClient(client.CreateAuthorizingHandler(authorizePopup.Authorization))) { + using (var resourceResponse = await httpClient.SendAsync(request)) { + this.oauth2ResultsBox.Text = await resourceResponse.Content.ReadAsStringAsync(); } } - } else { - return; } } catch (Messaging.ProtocolException ex) { MessageBox.Show(this, ex.Message); diff --git a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj index 03dbc50..ee06daa 100644 --- a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj +++ b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj @@ -76,6 +76,8 @@ <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> @@ -92,8 +94,7 @@ <Reference Include="System.Data" /> <Reference Include="System.Xml" /> <Reference Include="Validation"> - <HintPath>..\..\src\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <HintPath>..\..\src\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> <Reference Include="WindowsFormsIntegration" /> <Reference Include="System.Windows.Forms" /> @@ -152,7 +153,6 @@ <Compile Include="Authorize.xaml.cs"> <DependentUpon>Authorize.xaml</DependentUpon> </Compile> - <Compile Include="InMemoryTokenManager.cs" /> <Compile Include="Properties\AssemblyInfo.cs"> <SubType>Code</SubType> </Compile> diff --git a/samples/OAuthConsumerWpf/packages.config b/samples/OAuthConsumerWpf/packages.config index 1b0250a..2f4e283 100644 --- a/samples/OAuthConsumerWpf/packages.config +++ b/samples/OAuthConsumerWpf/packages.config @@ -1,5 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OAuthResourceServer/Code/OAuthAuthorizationManager.cs b/samples/OAuthResourceServer/Code/OAuthAuthorizationManager.cs index 31371db..091c9bb 100644 --- a/samples/OAuthResourceServer/Code/OAuthAuthorizationManager.cs +++ b/samples/OAuthResourceServer/Code/OAuthAuthorizationManager.cs @@ -3,11 +3,14 @@ using System.Collections.Generic; using System.IdentityModel.Policy; using System.Linq; + using System.Net.Http; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; using System.ServiceModel.Web; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using ProtocolException = System.ServiceModel.ProtocolException; @@ -27,53 +30,71 @@ var httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; var requestUri = operationContext.RequestContext.RequestMessage.Properties.Via; - try { - var principal = VerifyOAuth2(httpDetails, requestUri, operationContext.IncomingMessageHeaders.Action ?? operationContext.IncomingMessageHeaders.To.AbsolutePath); - if (principal != null) { - var policy = new OAuthPrincipalAuthorizationPolicy(principal); - var policies = new List<IAuthorizationPolicy> { - policy, - }; + return Task.Run(async delegate { + ProtocolFaultResponseException exception = null; + try { + var principal = await VerifyOAuth2Async( + httpDetails, + requestUri, + operationContext.IncomingMessageHeaders.Action ?? operationContext.IncomingMessageHeaders.To.AbsolutePath); + if (principal != null) { + var policy = new OAuthPrincipalAuthorizationPolicy(principal); + var policies = new List<IAuthorizationPolicy> { policy, }; - var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); - if (operationContext.IncomingMessageProperties.Security != null) { - operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; - } else { - operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { - ServiceSecurityContext = securityContext, - }; - } + var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); + if (operationContext.IncomingMessageProperties.Security != null) { + operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; + } else { + operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { + ServiceSecurityContext = securityContext, + }; + } - securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { - principal.Identity, - }; + securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, }; - return true; - } else { - return false; + return true; + } else { + return false; + } + } catch (ProtocolFaultResponseException ex) { + Global.Logger.Error("Error processing OAuth messages.", ex); + exception = ex; + } catch (ProtocolException ex) { + Global.Logger.Error("Error processing OAuth messages.", ex); } - } catch (ProtocolFaultResponseException ex) { - Global.Logger.Error("Error processing OAuth messages.", ex); - // Return the appropriate unauthorized response to the client. - var outgoingResponse = ex.CreateErrorResponse(); - outgoingResponse.Respond(WebOperationContext.Current.OutgoingResponse); - } catch (ProtocolException ex) { - Global.Logger.Error("Error processing OAuth messages.", ex); - } + if (exception != null) { + // Return the appropriate unauthorized response to the client. + var outgoingResponse = await exception.CreateErrorResponseAsync(CancellationToken.None); + this.Respond(WebOperationContext.Current.OutgoingResponse, outgoingResponse); + } - return false; + return false; + }).GetAwaiter().GetResult(); } - private static IPrincipal VerifyOAuth2(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes) { + private static async Task<IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes) { // for this sample where the auth server and resource server are the same site, // we use the same public/private key. using (var signing = Global.CreateAuthorizationServerSigningServiceProvider()) { using (var encrypting = Global.CreateResourceServerEncryptionServiceProvider()) { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting)); - return resourceServer.GetPrincipal(httpDetails, requestUri, requiredScopes); + return await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes: requiredScopes); } } } + + /// <summary> + /// Submits this response to a WCF response context. Only available when no response body is included. + /// </summary> + /// <param name="responseContext">The response context to apply the response to.</param> + /// <param name="responseMessage">The response message.</param> + private void Respond(OutgoingWebResponseContext responseContext, HttpResponseMessage responseMessage) { + responseContext.StatusCode = responseMessage.StatusCode; + responseContext.SuppressEntityBody = true; + foreach (var header in responseMessage.Headers) { + responseContext.Headers[header.Key] = header.Value.First(); + } + } } } diff --git a/samples/OAuthResourceServer/OAuthResourceServer.csproj b/samples/OAuthResourceServer/OAuthResourceServer.csproj index db40ea3..4afe367 100644 --- a/samples/OAuthResourceServer/OAuthResourceServer.csproj +++ b/samples/OAuthResourceServer/OAuthResourceServer.csproj @@ -132,6 +132,18 @@ <Project>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</Project> <Name>DotNetOpenAuth.OAuth2</Name> </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OpenId.RelyingParty.UI\DotNetOpenAuth.OpenId.RelyingParty.UI.csproj"> + <Project>{1ed8d424-f8ab-4050-aceb-f27f4f909484}</Project> + <Name>DotNetOpenAuth.OpenId.RelyingParty.UI</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OpenId.RelyingParty\DotNetOpenAuth.OpenId.RelyingParty.csproj"> + <Project>{f458ab60-ba1c-43d9-8cef-ec01b50be87b}</Project> + <Name>DotNetOpenAuth.OpenId.RelyingParty</Name> + </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj"> + <Project>{3896a32a-e876-4c23-b9b8-78e17d134cd3}</Project> + <Name>DotNetOpenAuth.OpenId</Name> + </ProjectReference> </ItemGroup> <ItemGroup> <Content Include="packages.config" /> diff --git a/samples/OAuthResourceServer/Web.config b/samples/OAuthResourceServer/Web.config index 978c20b..d76a04a 100644 --- a/samples/OAuthResourceServer/Web.config +++ b/samples/OAuthResourceServer/Web.config @@ -37,13 +37,16 @@ <messaging relaxSslRequirements="true" /> </dotNetOpenAuth> - <appSettings/> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> <connectionStrings> <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this @@ -52,7 +55,6 @@ --> <compilation debug="true" targetFramework="4.0"> <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> </assemblies> </compilation> diff --git a/samples/OAuthServiceProvider/Code/Constants.cs b/samples/OAuthServiceProvider/Code/Constants.cs index 3e629f0..9115f1c 100644 --- a/samples/OAuthServiceProvider/Code/Constants.cs +++ b/samples/OAuthServiceProvider/Code/Constants.cs @@ -10,9 +10,9 @@ public static class Constants { public static Uri WebRootUrl { get; set; } - public static ServiceProviderDescription SelfDescription { + public static ServiceProviderHostDescription SelfDescription { get { - ServiceProviderDescription description = new ServiceProviderDescription { + var description = new ServiceProviderHostDescription { AccessTokenEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest), RequestTokenEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest), UserAuthorizationEndpoint = new MessageReceivingEndpoint(new Uri(WebRootUrl, "/OAuth.ashx"), HttpDeliveryMethods.PostRequest), diff --git a/samples/OAuthServiceProvider/Code/DatabaseTokenManager.cs b/samples/OAuthServiceProvider/Code/DatabaseTokenManager.cs index 49da45d..7c80275 100644 --- a/samples/OAuthServiceProvider/Code/DatabaseTokenManager.cs +++ b/samples/OAuthServiceProvider/Code/DatabaseTokenManager.cs @@ -9,13 +9,18 @@ namespace OAuthServiceProvider.Code { using System.Collections.Generic; using System.Diagnostics; using System.Linq; + using System.ServiceModel; + using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; public class DatabaseTokenManager : IServiceProviderTokenManager { + internal OperationContext OperationContext { get; set; } + #region IServiceProviderTokenManager public IConsumerDescription GetConsumer(string consumerKey) { + this.ApplyOperationContext(); var consumerRow = Global.DataContext.OAuthConsumers.SingleOrDefault( consumerCandidate => consumerCandidate.ConsumerKey == consumerKey); if (consumerRow == null) { @@ -27,6 +32,7 @@ namespace OAuthServiceProvider.Code { public IServiceProviderRequestToken GetRequestToken(string token) { try { + this.ApplyOperationContext(); return Global.DataContext.OAuthTokens.First(t => t.Token == token && t.State != TokenAuthorizationState.AccessToken); } catch (InvalidOperationException ex) { throw new KeyNotFoundException("Unrecognized token", ex); @@ -34,6 +40,7 @@ namespace OAuthServiceProvider.Code { } public IServiceProviderAccessToken GetAccessToken(string token) { + this.ApplyOperationContext(); try { return Global.DataContext.OAuthTokens.First(t => t.Token == token && t.State == TokenAuthorizationState.AccessToken); } catch (InvalidOperationException ex) { @@ -54,6 +61,7 @@ namespace OAuthServiceProvider.Code { #region ITokenManager Members public string GetTokenSecret(string token) { + this.ApplyOperationContext(); var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault( tokenCandidate => tokenCandidate.Token == token); if (tokenRow == null) { @@ -64,6 +72,7 @@ namespace OAuthServiceProvider.Code { } public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { + this.ApplyOperationContext(); RequestScopedTokenMessage scopedRequest = (RequestScopedTokenMessage)request; var consumer = Global.DataContext.OAuthConsumers.Single(consumerRow => consumerRow.ConsumerKey == request.ConsumerKey); string scope = scopedRequest.Scope; @@ -90,6 +99,7 @@ namespace OAuthServiceProvider.Code { /// been authorized, has expired or does not exist. /// </returns> public bool IsRequestTokenAuthorized(string requestToken) { + this.ApplyOperationContext(); var tokenFound = Global.DataContext.OAuthTokens.SingleOrDefault( token => token.Token == requestToken && token.State == TokenAuthorizationState.AuthorizedRequestToken); @@ -97,6 +107,8 @@ namespace OAuthServiceProvider.Code { } public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { + this.ApplyOperationContext(); + var data = Global.DataContext; var consumerRow = data.OAuthConsumers.Single(consumer => consumer.ConsumerKey == consumerKey); var tokenRow = data.OAuthTokens.Single(token => token.Token == requestToken && token.OAuthConsumer == consumerRow); @@ -115,6 +127,7 @@ namespace OAuthServiceProvider.Code { /// <param name="token">The token to classify.</param> /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> public TokenType GetTokenType(string token) { + this.ApplyOperationContext(); var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault(tokenCandidate => tokenCandidate.Token == token); if (tokenRow == null) { return TokenType.InvalidToken; @@ -135,6 +148,7 @@ namespace OAuthServiceProvider.Code { throw new ArgumentNullException("user"); } + this.ApplyOperationContext(); var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault( tokenCandidate => tokenCandidate.Token == requestToken && tokenCandidate.State == TokenAuthorizationState.UnauthorizedRequestToken); @@ -151,6 +165,7 @@ namespace OAuthServiceProvider.Code { throw new ArgumentNullException("requestToken"); } + this.ApplyOperationContext(); var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault( tokenCandidate => tokenCandidate.Token == token); if (tokenRow == null) { @@ -159,5 +174,11 @@ namespace OAuthServiceProvider.Code { return tokenRow.OAuthConsumer; } + + private void ApplyOperationContext() { + if (this.OperationContext != null && OperationContext.Current == null) { + OperationContext.Current = this.OperationContext; + } + } } }
\ No newline at end of file diff --git a/samples/OAuthServiceProvider/Code/Global.cs b/samples/OAuthServiceProvider/Code/Global.cs index 60fed9f..37206ab 100644 --- a/samples/OAuthServiceProvider/Code/Global.cs +++ b/samples/OAuthServiceProvider/Code/Global.cs @@ -10,6 +10,10 @@ /// The web application global events and properties. /// </summary> public class Global : HttpApplication { + private readonly object syncObject = new object(); + + private volatile bool initialized; + /// <summary> /// An application memory cache of recent log messages. /// </summary> @@ -95,17 +99,6 @@ private void Application_Start(object sender, EventArgs e) { log4net.Config.XmlConfigurator.Configure(); Logger.Info("Sample starting..."); - string appPath = HttpContext.Current.Request.ApplicationPath; - if (!appPath.EndsWith("/")) { - appPath += "/"; - } - - // This will break in IIS Integrated Pipeline mode, since applications - // start before the first incoming request context is available. - // TODO: fix this. - Constants.WebRootUrl = new Uri(HttpContext.Current.Request.Url, appPath); - Global.TokenManager = new DatabaseTokenManager(); - Global.NonceStore = new DatabaseNonceStore(); } private void Application_End(object sender, EventArgs e) { @@ -128,8 +121,30 @@ } } + private void Application_BeginRequest(object sender, EventArgs e) { + this.EnsureInitialized(); + } + private void Application_EndRequest(object sender, EventArgs e) { CommitAndCloseDatabaseIfNecessary(); } + + private void EnsureInitialized() { + if (!this.initialized) { + lock (this.syncObject) { + if (!this.initialized) { + string appPath = HttpContext.Current.Request.ApplicationPath; + if (!appPath.EndsWith("/")) { + appPath += "/"; + } + + Constants.WebRootUrl = new Uri(HttpContext.Current.Request.Url, appPath); + Global.TokenManager = new DatabaseTokenManager(); + Global.NonceStore = new DatabaseNonceStore(); + this.initialized = true; + } + } + } + } } }
\ No newline at end of file diff --git a/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs b/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs index 917a252..2d942b5 100644 --- a/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs +++ b/samples/OAuthServiceProvider/Code/OAuthAuthorizationManager.cs @@ -7,6 +7,7 @@ using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; + using System.Threading.Tasks; using DotNetOpenAuth; using DotNetOpenAuth.OAuth; @@ -25,41 +26,41 @@ HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; Uri requestUri = operationContext.RequestContext.RequestMessage.Properties.Via; ServiceProvider sp = Constants.CreateServiceProvider(); - try { - var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri); - if (auth != null) { - var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken); + ((DatabaseTokenManager)sp.TokenManager).OperationContext = operationContext; // artificially preserve this across thread changes. + return Task.Run( + async delegate { + try { + var auth = await sp.ReadProtectedResourceAuthorizationAsync(httpDetails, requestUri); + if (auth != null) { + var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken); - var principal = sp.CreatePrincipal(auth); - var policy = new OAuthPrincipalAuthorizationPolicy(principal); - var policies = new List<IAuthorizationPolicy> { - policy, - }; + var principal = sp.CreatePrincipal(auth); + var policy = new OAuthPrincipalAuthorizationPolicy(principal); + var policies = new List<IAuthorizationPolicy> { policy, }; - var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); - if (operationContext.IncomingMessageProperties.Security != null) { - operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; - } else { - operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { - ServiceSecurityContext = securityContext, - }; - } + var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); + if (operationContext.IncomingMessageProperties.Security != null) { + operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; + } else { + operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { + ServiceSecurityContext = securityContext, + }; + } - securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { - principal.Identity, - }; + securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { principal.Identity, }; - // Only allow this method call if the access token scope permits it. - string[] scopes = accessToken.Scope.Split('|'); - if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) { - return true; + // Only allow this method call if the access token scope permits it. + string[] scopes = accessToken.Scope.Split('|'); + if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) { + return true; + } + } + } catch (ProtocolException ex) { + Global.Logger.Error("Error processing OAuth messages.", ex); } - } - } catch (ProtocolException ex) { - Global.Logger.Error("Error processing OAuth messages.", ex); - } - return false; + return false; + }).GetAwaiter().GetResult(); } } }
\ No newline at end of file diff --git a/samples/OAuthServiceProvider/Code/OAuthPrincipalAuthorizationPolicy.cs b/samples/OAuthServiceProvider/Code/OAuthPrincipalAuthorizationPolicy.cs index a25f4c5..4ce60bb 100644 --- a/samples/OAuthServiceProvider/Code/OAuthPrincipalAuthorizationPolicy.cs +++ b/samples/OAuthServiceProvider/Code/OAuthPrincipalAuthorizationPolicy.cs @@ -4,18 +4,19 @@ using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.Linq; + using System.Security.Principal; using System.Web; using DotNetOpenAuth.OAuth.ChannelElements; public class OAuthPrincipalAuthorizationPolicy : IAuthorizationPolicy { private readonly Guid uniqueId = Guid.NewGuid(); - private readonly OAuthPrincipal principal; + private readonly IPrincipal principal; /// <summary> /// Initializes a new instance of the <see cref="OAuthPrincipalAuthorizationPolicy"/> class. /// </summary> /// <param name="principal">The principal.</param> - public OAuthPrincipalAuthorizationPolicy(OAuthPrincipal principal) { + public OAuthPrincipalAuthorizationPolicy(IPrincipal principal) { this.principal = principal; } diff --git a/samples/OAuthServiceProvider/Login.aspx b/samples/OAuthServiceProvider/Login.aspx index 4498ee0..0b84ab9 100644 --- a/samples/OAuthServiceProvider/Login.aspx +++ b/samples/OAuthServiceProvider/Login.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="Login" Language="C#" MasterPageFile="~/MasterPage.master" %> +<%@ Page Title="Login" Language="C#" MasterPageFile="~/MasterPage.master" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="rp" %> diff --git a/samples/OAuthServiceProvider/Members/Authorize.aspx b/samples/OAuthServiceProvider/Members/Authorize.aspx index b3e2c6a..e7be651 100644 --- a/samples/OAuthServiceProvider/Members/Authorize.aspx +++ b/samples/OAuthServiceProvider/Members/Authorize.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthServiceProvider.Authorize" Codebehind="Authorize.aspx.cs" %> +<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthServiceProvider.Authorize" Codebehind="Authorize.aspx.cs" Async="true" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> <asp:MultiView runat="server" ActiveViewIndex="0" ID="multiView"> diff --git a/samples/OAuthServiceProvider/Members/Authorize.aspx.cs b/samples/OAuthServiceProvider/Members/Authorize.aspx.cs index faa2147..073231b 100644 --- a/samples/OAuthServiceProvider/Members/Authorize.aspx.cs +++ b/samples/OAuthServiceProvider/Members/Authorize.aspx.cs @@ -7,6 +7,7 @@ using System.Web.UI; using System.Web.UI.WebControls; using DotNetOpenAuth; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.Messages; using OAuthServiceProvider.Code; @@ -46,30 +47,36 @@ } protected void allowAccessButton_Click(object sender, EventArgs e) { - if (this.AuthorizationSecret != this.OAuthAuthorizationSecToken.Value) { - throw new ArgumentException(); // probably someone trying to hack in. - } - this.AuthorizationSecret = null; // clear one time use secret - var pending = Global.PendingOAuthAuthorization; - Global.AuthorizePendingRequestToken(); - this.multiView.ActiveViewIndex = 1; + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (this.AuthorizationSecret != this.OAuthAuthorizationSecToken.Value) { + throw new ArgumentException(); // probably someone trying to hack in. + } + this.AuthorizationSecret = null; // clear one time use secret + var pending = Global.PendingOAuthAuthorization; + Global.AuthorizePendingRequestToken(); + this.multiView.ActiveViewIndex = 1; - ServiceProvider sp = new ServiceProvider(Constants.SelfDescription, Global.TokenManager); - var response = sp.PrepareAuthorizationResponse(pending); - if (response != null) { - sp.Channel.Send(response); - } else { - if (pending.IsUnsafeRequest) { - this.verifierMultiView.ActiveViewIndex = 1; - } else { - string verifier = ServiceProvider.CreateVerificationCode(VerificationCodeFormat.AlphaNumericNoLookAlikes, 10); - this.verificationCodeLabel.Text = verifier; - ITokenContainingMessage requestTokenMessage = pending; - var requestToken = Global.TokenManager.GetRequestToken(requestTokenMessage.Token); - requestToken.VerificationCode = verifier; - Global.TokenManager.UpdateToken(requestToken); - } - } + ServiceProvider sp = new ServiceProvider(Constants.SelfDescription, Global.TokenManager); + var response = sp.PrepareAuthorizationResponse(pending); + if (response != null) { + var responseMessage = await sp.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken); + await responseMessage.SendAsync(); + this.Context.Response.End(); + } else { + if (pending.IsUnsafeRequest) { + this.verifierMultiView.ActiveViewIndex = 1; + } else { + string verifier = ServiceProvider.CreateVerificationCode(VerificationCodeFormat.AlphaNumericNoLookAlikes, 10); + this.verificationCodeLabel.Text = verifier; + ITokenContainingMessage requestTokenMessage = pending; + var requestToken = Global.TokenManager.GetRequestToken(requestTokenMessage.Token); + requestToken.VerificationCode = verifier; + Global.TokenManager.UpdateToken(requestToken); + } + } + })); } protected void denyAccessButton_Click(object sender, EventArgs e) { diff --git a/samples/OAuthServiceProvider/OAuth.ashx b/samples/OAuthServiceProvider/OAuth.ashx index 8a74926..003735c 100644 --- a/samples/OAuthServiceProvider/OAuth.ashx +++ b/samples/OAuthServiceProvider/OAuth.ashx @@ -2,41 +2,45 @@ using System; using System.Linq; +using System.Threading.Tasks; using System.Web; using System.Web.SessionState; +using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; using DotNetOpenAuth.Messaging; using OAuthServiceProvider.Code; -public class OAuth : IHttpHandler, IRequiresSessionState { +public class OAuth : HttpAsyncHandlerBase, IRequiresSessionState { ServiceProvider sp; public OAuth() { sp = new ServiceProvider(Constants.SelfDescription, Global.TokenManager, new CustomOAuthMessageFactory(Global.TokenManager)); } - public void ProcessRequest(HttpContext context) { - IProtocolMessage request = sp.ReadRequest(); + public override bool IsReusable { + get { return true; } + } + + protected override async Task ProcessRequestAsync(HttpContext context) { + IProtocolMessage request = await sp.ReadRequestAsync(); RequestScopedTokenMessage requestToken; UserAuthorizationRequest requestAuth; AuthorizedTokenRequest requestAccessToken; if ((requestToken = request as RequestScopedTokenMessage) != null) { var response = sp.PrepareUnauthorizedTokenMessage(requestToken); - sp.Channel.Send(response); + var responseMessage = await sp.Channel.PrepareResponseAsync(response); + await responseMessage.SendAsync(new HttpContextWrapper(context)); } else if ((requestAuth = request as UserAuthorizationRequest) != null) { Global.PendingOAuthAuthorization = requestAuth; HttpContext.Current.Response.Redirect("~/Members/Authorize.aspx"); } else if ((requestAccessToken = request as AuthorizedTokenRequest) != null) { var response = sp.PrepareAccessTokenMessage(requestAccessToken); - sp.Channel.Send(response); + var responseMessage = await sp.Channel.PrepareResponseAsync(response); + await responseMessage.SendAsync(new HttpContextWrapper(context)); } else { throw new InvalidOperationException(); } } - - public bool IsReusable { - get { return true; } - } } diff --git a/samples/OAuthServiceProvider/OAuthServiceProvider.csproj b/samples/OAuthServiceProvider/OAuthServiceProvider.csproj index 5419347..65d5a1f 100644 --- a/samples/OAuthServiceProvider/OAuthServiceProvider.csproj +++ b/samples/OAuthServiceProvider/OAuthServiceProvider.csproj @@ -26,7 +26,7 @@ <RootNamespace>OAuthServiceProvider</RootNamespace> <AssemblyName>OAuthServiceProvider</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> - <UseIISExpress>false</UseIISExpress> + <UseIISExpress>true</UseIISExpress> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> @@ -54,6 +54,8 @@ <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.Linq" /> <Reference Include="System.IdentityModel" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.ServiceModel" /> <Reference Include="System.Web.ApplicationServices" /> <Reference Include="System.Web.DynamicData" /> @@ -188,6 +190,10 @@ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project> <Name>DotNetOpenAuth.OpenId</Name> </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.ApplicationBlock\DotNetOpenAuth.ApplicationBlock.csproj"> + <Project>{aa78d112-d889-414b-a7d4-467b34c7b663}</Project> + <Name>DotNetOpenAuth.ApplicationBlock</Name> + </ProjectReference> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> @@ -196,12 +202,11 @@ <VisualStudio> <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"> <WebProjectProperties> - <UseIIS>False</UseIIS> + <UseIIS>True</UseIIS> <AutoAssignPort>False</AutoAssignPort> <DevelopmentServerPort>65169</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> - <IISUrl> - </IISUrl> + <IISUrl>http://localhost:65169/</IISUrl> <NTLMAuthentication>False</NTLMAuthentication> <UseCustomServer>False</UseCustomServer> <CustomServerUrl> diff --git a/samples/OAuthServiceProvider/Web.config b/samples/OAuthServiceProvider/Web.config index 21fe388..84aea1e 100644 --- a/samples/OAuthServiceProvider/Web.config +++ b/samples/OAuthServiceProvider/Web.config @@ -40,13 +40,16 @@ </messaging> </dotNetOpenAuth> - <appSettings/> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> <connectionStrings> <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this @@ -55,8 +58,8 @@ --> <compilation debug="true" targetFramework="4.0"> <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> + <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </assemblies> </compilation> <authentication mode="Forms"> diff --git a/samples/OAuthServiceProvider/packages.config b/samples/OAuthServiceProvider/packages.config index 6562527..8e40260 100644 --- a/samples/OAuthServiceProvider/packages.config +++ b/samples/OAuthServiceProvider/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OpenIdOfflineProvider/CheckIdWindow.xaml.cs b/samples/OpenIdOfflineProvider/CheckIdWindow.xaml.cs index 27bb802..9394bd9 100644 --- a/samples/OpenIdOfflineProvider/CheckIdWindow.xaml.cs +++ b/samples/OpenIdOfflineProvider/CheckIdWindow.xaml.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; @@ -18,6 +20,7 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { using System.Windows.Media.Imaging; using System.Windows.Shapes; using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Provider; using Validation; @@ -28,9 +31,9 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { /// <summary> /// Initializes a new instance of the <see cref="CheckIdWindow"/> class. /// </summary> - /// <param name="provider">The OpenID Provider host.</param> + /// <param name="userIdentityPageBase">The base URI upon which user identity pages are created.</param> /// <param name="request">The incoming authentication request.</param> - private CheckIdWindow(HostedProvider provider, IAuthenticationRequest request) { + private CheckIdWindow(Uri userIdentityPageBase, IAuthenticationRequest request) { Requires.NotNull(request, "request"); this.InitializeComponent(); @@ -40,13 +43,9 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { this.immediateModeLabel.Visibility = request.Immediate ? Visibility.Visible : Visibility.Collapsed; this.setupModeLabel.Visibility = request.Immediate ? Visibility.Collapsed : Visibility.Visible; - bool isRPDiscoverable = request.IsReturnUrlDiscoverable(provider.Provider.Channel.WebRequestHandler) == RelyingPartyDiscoveryResult.Success; - this.discoverableYesLabel.Visibility = isRPDiscoverable ? Visibility.Visible : Visibility.Collapsed; - this.discoverableNoLabel.Visibility = isRPDiscoverable ? Visibility.Collapsed : Visibility.Visible; - if (request.IsDirectedIdentity) { - this.claimedIdentifierBox.Text = provider.UserIdentityPageBase.AbsoluteUri; - this.localIdentifierBox.Text = provider.UserIdentityPageBase.AbsoluteUri; + this.claimedIdentifierBox.Text = userIdentityPageBase.AbsoluteUri; + this.localIdentifierBox.Text = userIdentityPageBase.AbsoluteUri; } else { this.claimedIdentifierBox.Text = request.ClaimedIdentifier; this.localIdentifierBox.Text = request.LocalIdentifier; @@ -56,13 +55,22 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { /// <summary> /// Processes an authentication request by a popup window. /// </summary> - /// <param name="provider">The OpenID Provider host.</param> + /// <param name="userIdentityPageBase">The base URI upon which user identity pages are created.</param> /// <param name="request">The incoming authentication request.</param> - internal static void ProcessAuthentication(HostedProvider provider, IAuthenticationRequest request) { - Requires.NotNull(provider, "provider"); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + internal static async Task ProcessAuthenticationAsync(Uri userIdentityPageBase, IAuthenticationRequest request, CancellationToken cancellationToken) { + Requires.NotNull(userIdentityPageBase, "userIdentityPageBase"); Requires.NotNull(request, "request"); - var window = new CheckIdWindow(provider, request); + var window = new CheckIdWindow(userIdentityPageBase, request); + + bool isRPDiscoverable = await request.IsReturnUrlDiscoverableAsync(cancellationToken: cancellationToken) == RelyingPartyDiscoveryResult.Success; + window.discoverableYesLabel.Visibility = isRPDiscoverable ? Visibility.Visible : Visibility.Collapsed; + window.discoverableNoLabel.Visibility = isRPDiscoverable ? Visibility.Collapsed : Visibility.Visible; + bool? result = window.ShowDialog(); // If the user pressed Esc or cancel, just send a negative assertion. diff --git a/samples/OpenIdOfflineProvider/Controllers/HomeController.cs b/samples/OpenIdOfflineProvider/Controllers/HomeController.cs new file mode 100644 index 0000000..f5a8763 --- /dev/null +++ b/samples/OpenIdOfflineProvider/Controllers/HomeController.cs @@ -0,0 +1,54 @@ +namespace DotNetOpenAuth.OpenIdOfflineProvider.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + using System.Web.Http; + + using Validation; + + public class HomeController : ApiController { + public HttpResponseMessage Get() { + App.Logger.Info("Discovery on OP Identifier detected."); + var opEndpoint = this.Url.Link("default", new { controller = "provider" }); + var opEndpointUri = new Uri(opEndpoint); + return new HttpResponseMessage() { + Content = new StringContent(GenerateXrdsOPIdentifierDocument(opEndpointUri, Enumerable.Empty<string>()), Encoding.UTF8, "application/xrds+xml"), + }; + } + + /// <summary> + /// Generates the OP Identifier XRDS document. + /// </summary> + /// <param name="providerEndpoint">The provider endpoint.</param> + /// <param name="supportedExtensions">The supported extensions.</param> + /// <returns>The content of the XRDS document.</returns> + private static string GenerateXrdsOPIdentifierDocument(Uri providerEndpoint, IEnumerable<string> supportedExtensions) { + Requires.NotNull(providerEndpoint, "providerEndpoint"); + Requires.NotNull(supportedExtensions, "supportedExtensions"); + + const string OPIdentifierDiscoveryFormat = @"<xrds:XRDS + xmlns:xrds='xri://$xrds' + xmlns:openid='http://openid.net/xmlns/1.0' + xmlns='xri://$xrd*($v*2.0)'> + <XRD> + <Service priority='10'> + <Type>http://specs.openid.net/auth/2.0/server</Type> + {1} + <URI>{0}</URI> + </Service> + </XRD> +</xrds:XRDS>"; + + string extensions = string.Join( + "\n\t\t\t", + supportedExtensions.Select(ext => "<Type>" + ext + "</Type>").ToArray()); + return string.Format( + OPIdentifierDiscoveryFormat, + providerEndpoint.AbsoluteUri, + extensions); + } + } +} diff --git a/samples/OpenIdOfflineProvider/Controllers/ProviderController.cs b/samples/OpenIdOfflineProvider/Controllers/ProviderController.cs new file mode 100644 index 0000000..b0d243b --- /dev/null +++ b/samples/OpenIdOfflineProvider/Controllers/ProviderController.cs @@ -0,0 +1,81 @@ +namespace DotNetOpenAuth.OpenIdOfflineProvider.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using System.Web.Http; + + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Provider; + + public class ProviderController : ApiController { + private static readonly IOpenIdApplicationStore store = new StandardProviderApplicationStore(); + + private MainWindow MainWindow { + get { return MainWindow.Instance; } + } + + public Task<HttpResponseMessage> Get() { + return this.HandleAsync(); + } + + public Task<HttpResponseMessage> Post() { + return this.HandleAsync(); + } + + private async Task<HttpResponseMessage> HandleAsync() { + var provider = new OpenIdProvider(store); + IRequest request = await provider.GetRequestAsync(this.Request); + if (request == null) { + App.Logger.Error("A request came in that did not carry an OpenID message."); + return new HttpResponseMessage(HttpStatusCode.BadRequest) { + Content = new StringContent("<html><body>This is an OpenID Provider endpoint.</body></html>", Encoding.UTF8, "text/html"), + }; + } + + return await await this.MainWindow.Dispatcher.InvokeAsync(async delegate { + if (!request.IsResponseReady) { + var authRequest = request as IAuthenticationRequest; + if (authRequest != null) { + string userIdentityPageBase = this.Url.Link("default", new { controller = "user" }) + "/"; + var userIdentityPageBaseUri = new Uri(userIdentityPageBase); + switch (this.MainWindow.checkidRequestList.SelectedIndex) { + case 0: + if (authRequest.IsDirectedIdentity) { + if (this.MainWindow.capitalizedHostName.IsChecked.Value) { + userIdentityPageBase = (userIdentityPageBaseUri.Scheme + Uri.SchemeDelimiter + userIdentityPageBaseUri.Authority).ToUpperInvariant() + userIdentityPageBaseUri.PathAndQuery; + } + string leafPath = "directedidentity"; + if (this.MainWindow.directedIdentityTrailingPeriodsCheckbox.IsChecked.Value) { + leafPath += "."; + } + authRequest.ClaimedIdentifier = Identifier.Parse(userIdentityPageBase + leafPath, true); + authRequest.LocalIdentifier = authRequest.ClaimedIdentifier; + } + authRequest.IsAuthenticated = true; + break; + case 1: + authRequest.IsAuthenticated = false; + break; + case 2: + IntPtr oldForegroundWindow = NativeMethods.GetForegroundWindow(); + bool stoleFocus = NativeMethods.SetForegroundWindow(this.MainWindow); + await CheckIdWindow.ProcessAuthenticationAsync(userIdentityPageBaseUri, authRequest, CancellationToken.None); + if (stoleFocus) { + NativeMethods.SetForegroundWindow(oldForegroundWindow); + } + break; + } + } + } + + var responseMessage = await provider.PrepareResponseAsync(request); + return responseMessage; + }); + } + } +} diff --git a/samples/OpenIdOfflineProvider/Controllers/UserController.cs b/samples/OpenIdOfflineProvider/Controllers/UserController.cs new file mode 100644 index 0000000..9385b7f --- /dev/null +++ b/samples/OpenIdOfflineProvider/Controllers/UserController.cs @@ -0,0 +1,49 @@ +namespace DotNetOpenAuth.OpenIdOfflineProvider.Controllers { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + using System.Web.Http; + + using Validation; + + public class UserController : ApiController { + public HttpResponseMessage Get(string id) { + string localId = null; // string.Format("http://localhost:{0}/user", context.Request.Url.Port); + var opEndpoint = this.Url.Link("default", new { controller = "provider" }); + var opEndpointUri = new Uri(opEndpoint); + return new HttpResponseMessage() { + Content = new StringContent(GenerateHtmlDiscoveryDocument(opEndpointUri, localId), Encoding.UTF8, "text/html"), + }; + } + + /// <summary> + /// Generates HTML for an identity page. + /// </summary> + /// <param name="providerEndpoint">The provider endpoint.</param> + /// <param name="localId">The local id.</param> + /// <returns>The HTML document to return to the RP.</returns> + private static string GenerateHtmlDiscoveryDocument(Uri providerEndpoint, string localId) { + Requires.NotNull(providerEndpoint, "providerEndpoint"); + + const string DelegatedHtmlDiscoveryFormat = @"<html><head> + <link rel=""openid.server"" href=""{0}"" /> + <link rel=""openid.delegate"" href=""{1}"" /> + <link rel=""openid2.provider"" href=""{0}"" /> + <link rel=""openid2.local_id"" href=""{1}"" /> + </head><body></body></html>"; + + const string NonDelegatedHtmlDiscoveryFormat = @"<html><head> + <link rel=""openid.server"" href=""{0}"" /> + <link rel=""openid2.provider"" href=""{0}"" /> + </head><body></body></html>"; + + return string.Format( + localId != null ? DelegatedHtmlDiscoveryFormat : NonDelegatedHtmlDiscoveryFormat, + providerEndpoint.AbsoluteUri, + localId); + } + } +} diff --git a/samples/OpenIdOfflineProvider/HostedProvider.cs b/samples/OpenIdOfflineProvider/HostedProvider.cs deleted file mode 100644 index 3c7692d..0000000 --- a/samples/OpenIdOfflineProvider/HostedProvider.cs +++ /dev/null @@ -1,254 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="HostedProvider.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OpenIdOfflineProvider { - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Web; - - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OpenId.Provider; - using log4net; - using Validation; - - /// <summary> - /// The OpenID Provider host. - /// </summary> - internal class HostedProvider : IDisposable { - /// <summary> - /// The path to the Provider Endpoint. - /// </summary> - private const string ProviderPath = "/provider"; - - /// <summary> - /// The path to the OP Identifier. - /// </summary> - private const string OPIdentifierPath = "/"; - - /// <summary> - /// The URL path with which all user identities must start. - /// </summary> - private const string UserIdentifierPath = "/user/"; - - /// <summary> - /// The <see cref="OpenIdProvider"/> instance that processes incoming requests. - /// </summary> - private OpenIdProvider provider = new OpenIdProvider(new StandardProviderApplicationStore()); - - /// <summary> - /// The HTTP listener that acts as the OpenID Provider socket. - /// </summary> - private HttpHost httpHost; - - /// <summary> - /// Initializes a new instance of the <see cref="HostedProvider"/> class. - /// </summary> - internal HostedProvider() { - } - - /// <summary> - /// Gets a value indicating whether this instance is running. - /// </summary> - /// <value> - /// <c>true</c> if this instance is running; otherwise, <c>false</c>. - /// </value> - internal bool IsRunning { - get { return this.httpHost != null; } - } - - /// <summary> - /// Gets the <see cref="OpenIdProvider"/> instance that processes incoming requests. - /// </summary> - internal OpenIdProvider Provider { - get { return this.provider; } - } - - /// <summary> - /// Gets or sets the delegate that handles authentication requests. - /// </summary> - internal Action<HttpRequestBase, HttpListenerResponse> ProcessRequest { get; set; } - - /// <summary> - /// Gets the provider endpoint. - /// </summary> - internal Uri ProviderEndpoint { - get { - Assumes.True(this.IsRunning); - return new Uri(this.httpHost.BaseUri, ProviderPath); - } - } - - /// <summary> - /// Gets the base URI that all user identities must start with. - /// </summary> - internal Uri UserIdentityPageBase { - get { - Assumes.True(this.IsRunning); - return new Uri(this.httpHost.BaseUri, UserIdentifierPath); - } - } - - /// <summary> - /// Gets the OP identifier. - /// </summary> - internal Uri OPIdentifier { - get { - Assumes.True(this.IsRunning); - return new Uri(this.httpHost.BaseUri, OPIdentifierPath); - } - } - - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() { - this.Dispose(true); - } - - /// <summary> - /// Starts the provider. - /// </summary> - internal void StartProvider() { - this.httpHost = HttpHost.CreateHost(this.RequestHandler); - } - - /// <summary> - /// Stops the provider. - /// </summary> - internal void StopProvider() { - if (this.httpHost != null) { - this.httpHost.Dispose(); - this.httpHost = null; - } - } - - #region IDisposable Members - - /// <summary> - /// Releases unmanaged and - optionally - managed resources - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool disposing) { - if (disposing) { - var host = this.httpHost as IDisposable; - if (host != null) { - host.Dispose(); - } - - this.httpHost = null; - } - } - - #endregion - - /// <summary> - /// Generates HTML for an identity page. - /// </summary> - /// <param name="providerEndpoint">The provider endpoint.</param> - /// <param name="localId">The local id.</param> - /// <returns>The HTML document to return to the RP.</returns> - private static string GenerateHtmlDiscoveryDocument(Uri providerEndpoint, string localId) { - Requires.NotNull(providerEndpoint, "providerEndpoint"); - - const string DelegatedHtmlDiscoveryFormat = @"<html><head> - <link rel=""openid.server"" href=""{0}"" /> - <link rel=""openid.delegate"" href=""{1}"" /> - <link rel=""openid2.provider"" href=""{0}"" /> - <link rel=""openid2.local_id"" href=""{1}"" /> - </head><body></body></html>"; - - const string NonDelegatedHtmlDiscoveryFormat = @"<html><head> - <link rel=""openid.server"" href=""{0}"" /> - <link rel=""openid2.provider"" href=""{0}"" /> - </head><body></body></html>"; - - return string.Format( - localId != null ? DelegatedHtmlDiscoveryFormat : NonDelegatedHtmlDiscoveryFormat, - providerEndpoint.AbsoluteUri, - localId); - } - - /// <summary> - /// Generates the OP Identifier XRDS document. - /// </summary> - /// <param name="providerEndpoint">The provider endpoint.</param> - /// <param name="supportedExtensions">The supported extensions.</param> - /// <returns>The content of the XRDS document.</returns> - private static string GenerateXrdsOPIdentifierDocument(Uri providerEndpoint, IEnumerable<string> supportedExtensions) { - Requires.NotNull(providerEndpoint, "providerEndpoint"); - Requires.NotNull(supportedExtensions, "supportedExtensions"); - - const string OPIdentifierDiscoveryFormat = @"<xrds:XRDS - xmlns:xrds='xri://$xrds' - xmlns:openid='http://openid.net/xmlns/1.0' - xmlns='xri://$xrd*($v*2.0)'> - <XRD> - <Service priority='10'> - <Type>http://specs.openid.net/auth/2.0/server</Type> - {1} - <URI>{0}</URI> - </Service> - </XRD> -</xrds:XRDS>"; - - string extensions = string.Join( - "\n\t\t\t", - supportedExtensions.Select(ext => "<Type>" + ext + "</Type>").ToArray()); - return string.Format( - OPIdentifierDiscoveryFormat, - providerEndpoint.AbsoluteUri, - extensions); - } - - /// <summary> - /// Handles incoming HTTP requests. - /// </summary> - /// <param name="context">The HttpListener context.</param> - private void RequestHandler(HttpListenerContext context) { - Requires.NotNull(context, "context"); - Requires.NotNull(context.Response.OutputStream, "context.Response.OutputStream"); - Requires.NotNull(this.ProcessRequest, "this.ProcessRequest"); - - Stream outputStream = context.Response.OutputStream; - Assumes.True(outputStream != null); // CC static verification shortcoming. - - UriBuilder providerEndpointBuilder = new UriBuilder(); - providerEndpointBuilder.Scheme = Uri.UriSchemeHttp; - providerEndpointBuilder.Host = "localhost"; - providerEndpointBuilder.Port = context.Request.Url.Port; - providerEndpointBuilder.Path = ProviderPath; - Uri providerEndpoint = providerEndpointBuilder.Uri; - - if (context.Request.Url.AbsolutePath == ProviderPath) { - HttpRequestBase requestInfo = HttpRequestInfo.Create(context.Request); - this.ProcessRequest(requestInfo, context.Response); - } else if (context.Request.Url.AbsolutePath.StartsWith(UserIdentifierPath, StringComparison.Ordinal)) { - using (StreamWriter sw = new StreamWriter(outputStream)) { - context.Response.StatusCode = (int)HttpStatusCode.OK; - - string localId = null; // string.Format("http://localhost:{0}/user", context.Request.Url.Port); - string html = GenerateHtmlDiscoveryDocument(providerEndpoint, localId); - sw.WriteLine(html); - } - context.Response.OutputStream.Close(); - } else if (context.Request.Url == this.OPIdentifier) { - context.Response.ContentType = "application/xrds+xml"; - context.Response.StatusCode = (int)HttpStatusCode.OK; - App.Logger.Info("Discovery on OP Identifier detected."); - using (StreamWriter sw = new StreamWriter(outputStream)) { - sw.Write(GenerateXrdsOPIdentifierDocument(providerEndpoint, Enumerable.Empty<string>())); - } - context.Response.OutputStream.Close(); - } else { - context.Response.StatusCode = (int)HttpStatusCode.NotFound; - context.Response.OutputStream.Close(); - } - } - } -} diff --git a/samples/OpenIdOfflineProvider/HttpHost.cs b/samples/OpenIdOfflineProvider/HttpHost.cs deleted file mode 100644 index 3eb0884..0000000 --- a/samples/OpenIdOfflineProvider/HttpHost.cs +++ /dev/null @@ -1,139 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="HttpHost.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OpenIdOfflineProvider { - using System; - using System.Globalization; - using System.IO; - using System.Net; - using System.Threading; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OpenId.Provider; - using Validation; - - /// <summary> - /// An HTTP Listener that dispatches incoming requests for handling. - /// </summary> - internal class HttpHost : IDisposable { - /// <summary> - /// The HttpListener that waits for incoming requests. - /// </summary> - private readonly HttpListener listener; - - /// <summary> - /// The thread that listens for incoming HTTP requests and dispatches them - /// to the <see cref="handler"/>. - /// </summary> - private Thread listenerThread; - - /// <summary> - /// The handler for incoming HTTP requests. - /// </summary> - private RequestHandler handler; - - /// <summary> - /// Initializes a new instance of the <see cref="HttpHost"/> class. - /// </summary> - /// <param name="handler">The handler for incoming HTTP requests.</param> - private HttpHost(RequestHandler handler) { - Requires.NotNull(handler, "handler"); - - this.Port = 45235; - this.handler = handler; - Random r = new Random(); - tryAgain: - try { - this.listener = new HttpListener(); - this.listener.Prefixes.Add(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/", this.Port)); - this.listener.Start(); - } catch (HttpListenerException ex) { - if (ex.Message.Contains("conflicts")) { - this.Port += r.Next(1, 20); - goto tryAgain; - } - throw; - } - - this.listenerThread = new Thread(this.ProcessRequests); - this.listenerThread.Start(); - } - - /// <summary> - /// The request handler delegate. - /// </summary> - /// <param name="context">Information on the incoming HTTP request.</param> - internal delegate void RequestHandler(HttpListenerContext context); - - /// <summary> - /// Gets the port that HTTP requests are being listened for on. - /// </summary> - public int Port { get; private set; } - - /// <summary> - /// Gets the base URI for all incoming web requests that will be received. - /// </summary> - public Uri BaseUri { - get { return new Uri("http://localhost:" + this.Port.ToString() + "/"); } - } - - /// <summary> - /// Creates the HTTP host. - /// </summary> - /// <param name="handler">The handler for incoming HTTP requests.</param> - /// <returns>The instantiated host.</returns> - public static HttpHost CreateHost(RequestHandler handler) { - Requires.NotNull(handler, "handler"); - - return new HttpHost(handler); - } - - #region IDisposable Members - - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// <summary> - /// Releases unmanaged and - optionally - managed resources - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool disposing) { - if (disposing) { - this.listener.Close(); - this.listenerThread.Join(1000); - this.listenerThread.Abort(); - } - } - - #endregion - - /// <summary> - /// The HTTP listener thread body. - /// </summary> - private void ProcessRequests() { - Assumes.True(this.listener != null); - - while (true) { - try { - HttpListenerContext context = this.listener.GetContext(); - this.handler(context); - } catch (HttpListenerException ex) { - if (this.listener.IsListening) { - App.Logger.Error("Unexpected exception.", ex); - } else { - // the listener is probably being shut down - App.Logger.Warn("HTTP listener is closing down.", ex); - break; - } - } - } - } - } -} diff --git a/samples/OpenIdOfflineProvider/MainWindow.xaml.cs b/samples/OpenIdOfflineProvider/MainWindow.xaml.cs index 30847d0..2297a2a 100644 --- a/samples/OpenIdOfflineProvider/MainWindow.xaml.cs +++ b/samples/OpenIdOfflineProvider/MainWindow.xaml.cs @@ -12,9 +12,16 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { using System.IO; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Runtime.InteropServices; + using System.ServiceModel; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; + using System.Web.Http.Routing; + using System.Web.Http.SelfHost; using System.Windows; using System.Windows.Controls; using System.Windows.Data; @@ -30,35 +37,40 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { using log4net; using log4net.Appender; using log4net.Core; + using Validation; + + using System.Web.Http; /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, IDisposable { /// <summary> - /// The OpenID Provider host object. + /// The logger the application may use. /// </summary> - private HostedProvider hostedProvider = new HostedProvider(); + private ILog logger = log4net.LogManager.GetLogger(typeof(MainWindow)); /// <summary> - /// The logger the application may use. + /// The HTTP listener that acts as the OpenID Provider socket. /// </summary> - private ILog logger = log4net.LogManager.GetLogger(typeof(MainWindow)); + private HttpSelfHostServer hostServer; /// <summary> /// Initializes a new instance of the <see cref="MainWindow"/> class. /// </summary> public MainWindow() { this.InitializeComponent(); - this.hostedProvider.ProcessRequest = this.ProcessRequest; TextWriterAppender boxLogger = log4net.LogManager.GetRepository().GetAppenders().OfType<TextWriterAppender>().FirstOrDefault(a => a.Name == "TextBoxAppender"); if (boxLogger != null) { boxLogger.Writer = new TextBoxTextWriter(this.logBox); } - this.startProvider(); + Instance = this; + this.StartProviderAsync(); } + internal static MainWindow Instance; + #region IDisposable Members /// <summary> @@ -74,12 +86,11 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { - var host = this.hostedProvider as IDisposable; - if (host != null) { - host.Dispose(); + if (this.hostServer != null) { + this.hostServer.Dispose(); } - this.hostedProvider = null; + this.hostServer = null; } } @@ -90,80 +101,33 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { /// </summary> /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param> protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { - this.stopProvider(); + this.StopProviderAsync(); base.OnClosing(e); } /// <summary> - /// Processes an incoming request at the OpenID Provider endpoint. + /// Adds a set of HTTP headers to an <see cref="HttpResponse"/> instance, + /// taking care to set some headers to the appropriate properties of + /// <see cref="HttpResponse" /> /// </summary> - /// <param name="requestInfo">The request info.</param> - /// <param name="response">The response.</param> - private void ProcessRequest(HttpRequestBase requestInfo, HttpListenerResponse response) { - IRequest request = this.hostedProvider.Provider.GetRequest(requestInfo); - if (request == null) { - App.Logger.Error("A request came in that did not carry an OpenID message."); - response.ContentType = "text/html"; - response.StatusCode = (int)HttpStatusCode.BadRequest; - using (StreamWriter sw = new StreamWriter(response.OutputStream)) { - sw.WriteLine("<html><body>This is an OpenID Provider endpoint.</body></html>"); + /// <param name="headers">The headers to add.</param> + /// <param name="response">The <see cref="HttpListenerResponse"/> instance to set the appropriate values to.</param> + private static void ApplyHeadersToResponse(HttpResponseHeaders headers, HttpListenerResponse response) { + Requires.NotNull(headers, "headers"); + Requires.NotNull(response, "response"); + + foreach (var header in headers) { + switch (header.Key) { + case "Content-Type": + response.ContentType = header.Value.First(); + break; + + // Add more special cases here as necessary. + default: + response.AddHeader(header.Key, header.Value.First()); + break; } - return; } - - this.Dispatcher.Invoke((Action)delegate { - if (!request.IsResponseReady) { - var authRequest = request as IAuthenticationRequest; - if (authRequest != null) { - switch (this.checkidRequestList.SelectedIndex) { - case 0: - if (authRequest.IsDirectedIdentity) { - string userIdentityPageBase = this.hostedProvider.UserIdentityPageBase.AbsoluteUri; - if (this.capitalizedHostName.IsChecked.Value) { - userIdentityPageBase = (this.hostedProvider.UserIdentityPageBase.Scheme + Uri.SchemeDelimiter + this.hostedProvider.UserIdentityPageBase.Authority).ToUpperInvariant() + this.hostedProvider.UserIdentityPageBase.PathAndQuery; - } - string leafPath = "directedidentity"; - if (this.directedIdentityTrailingPeriodsCheckbox.IsChecked.Value) { - leafPath += "."; - } - authRequest.ClaimedIdentifier = Identifier.Parse(userIdentityPageBase + leafPath, true); - authRequest.LocalIdentifier = authRequest.ClaimedIdentifier; - } - authRequest.IsAuthenticated = true; - break; - case 1: - authRequest.IsAuthenticated = false; - break; - case 2: - IntPtr oldForegroundWindow = NativeMethods.GetForegroundWindow(); - bool stoleFocus = NativeMethods.SetForegroundWindow(this); - CheckIdWindow.ProcessAuthentication(this.hostedProvider, authRequest); - if (stoleFocus) { - NativeMethods.SetForegroundWindow(oldForegroundWindow); - } - break; - } - } - } - }); - - this.hostedProvider.Provider.PrepareResponse(request).Send(response); - } - - /// <summary> - /// Starts the provider. - /// </summary> - private void startProvider() { - this.hostedProvider.StartProvider(); - this.opIdentifierLabel.Content = this.hostedProvider.OPIdentifier; - } - - /// <summary> - /// Stops the provider. - /// </summary> - private void stopProvider() { - this.hostedProvider.StopProvider(); - this.opIdentifierLabel.Content = string.Empty; } /// <summary> @@ -187,5 +151,62 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { private void ClearLogButton_Click(object sender, RoutedEventArgs e) { this.logBox.Clear(); } + + /// <summary> + /// Starts the provider. + /// </summary> + private async Task StartProviderAsync() { + Exception exception = null; + try { + Verify.Operation(this.hostServer == null, "Server already started."); + + int port = 45235; + var baseUri = new UriBuilder("http", "localhost", port); + var configuration = new HttpSelfHostConfiguration(baseUri.Uri); + configuration.Routes.MapHttpRoute("default", "{controller}/{id}", new { controller = "Home", id = RouteParameter.Optional }); + try { + var hostServer = new HttpSelfHostServer(configuration); + await hostServer.OpenAsync(); + this.hostServer = hostServer; + } catch (AddressAccessDeniedException ex) { + // If this throws an exception, use an elevated command prompt and execute: + // netsh http add urlacl url=http://+:45235/ user=YOUR_USERNAME_HERE + string message = string.Format( + CultureInfo.CurrentCulture, + "Use an elevated command prompt and execute: \nnetsh http add urlacl url=http://+:{0}/ user={1}\\{2}", + port, + Environment.UserDomainName, + Environment.UserName); + throw new InvalidOperationException(message, ex); + } + + this.opIdentifierLabel.Content = baseUri.Uri.AbsoluteUri; + } catch (InvalidOperationException ex) { + exception = ex; + } + + if (exception != null) { + if (MessageBox.Show(exception.Message, "Configuration error", MessageBoxButton.OKCancel, MessageBoxImage.Error) + == MessageBoxResult.OK) { + await this.StartProviderAsync(); + return; + } else { + this.Close(); + } + } + } + + /// <summary> + /// Stops the provider. + /// </summary> + private async Task StopProviderAsync() { + if (this.hostServer != null) { + await this.hostServer.CloseAsync(); + this.hostServer.Dispose(); + this.hostServer = null; + } + + this.opIdentifierLabel.Content = string.Empty; + } } } diff --git a/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj b/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj index 56bc5b6..4f79942 100644 --- a/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj +++ b/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj @@ -42,6 +42,7 @@ <ApplicationVersion>1.0.0.%2a</ApplicationVersion> <UseApplicationTrust>false</UseApplicationTrust> <BootstrapperEnabled>true</BootstrapperEnabled> + <UltimateResourceFallbackLocation>UltimateResourceFallbackLocation.Satellite</UltimateResourceFallbackLocation> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> @@ -60,15 +61,30 @@ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <ItemGroup> - <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> + <Reference Include="log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> - <HintPath>..\..\lib\log4net.dll</HintPath> + <HintPath>..\..\src\packages\log4net.2.0.0\lib\net40-full\log4net.dll</HintPath> + </Reference> + <Reference Include="Newtonsoft.Json"> + <HintPath>..\..\src\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebApi.Client.4.0.20710.0\lib\net40\System.Net.Http.Formatting.dll</HintPath> + </Reference> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="System.ServiceModel" /> <Reference Include="System.Web" /> + <Reference Include="System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebApi.Core.4.0.20710.0\lib\net40\System.Web.Http.dll</HintPath> + </Reference> + <Reference Include="System.Web.Http.SelfHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebApi.SelfHost.4.0.20918.0\lib\net40\System.Web.Http.SelfHost.dll</HintPath> + </Reference> <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> @@ -80,9 +96,9 @@ <Reference Include="UIAutomationProvider"> <RequiredTargetFramework>3.0</RequiredTargetFramework> </Reference> - <Reference Include="Validation"> - <HintPath>..\..\src\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\src\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> <Reference Include="WindowsBase"> <RequiredTargetFramework>3.0</RequiredTargetFramework> @@ -101,20 +117,17 @@ <ApplicationDefinition Include="App.xaml"> <Generator>MSBuild:Compile</Generator> <SubType>Designer</SubType> - <Generator>MSBuild:Compile</Generator> - <SubType>Designer</SubType> </ApplicationDefinition> + <Compile Include="Controllers\HomeController.cs" /> + <Compile Include="Controllers\ProviderController.cs" /> + <Compile Include="Controllers\UserController.cs" /> <Page Include="CheckIdWindow.xaml"> <SubType>Designer</SubType> <Generator>MSBuild:Compile</Generator> - <Generator>MSBuild:Compile</Generator> - <SubType>Designer</SubType> </Page> <Page Include="MainWindow.xaml"> <Generator>MSBuild:Compile</Generator> <SubType>Designer</SubType> - <Generator>MSBuild:Compile</Generator> - <SubType>Designer</SubType> </Page> <Compile Include="App.xaml.cs"> <DependentUpon>App.xaml</DependentUpon> @@ -129,8 +142,6 @@ <Compile Include="CheckIdWindow.xaml.cs"> <DependentUpon>CheckIdWindow.xaml</DependentUpon> </Compile> - <Compile Include="HostedProvider.cs" /> - <Compile Include="HttpHost.cs" /> <Compile Include="NativeMethods.cs" /> <Compile Include="Properties\AssemblyInfo.cs"> <SubType>Code</SubType> diff --git a/samples/OpenIdOfflineProvider/packages.config b/samples/OpenIdOfflineProvider/packages.config index 58890d8..fd2ff83 100644 --- a/samples/OpenIdOfflineProvider/packages.config +++ b/samples/OpenIdOfflineProvider/packages.config @@ -1,4 +1,11 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="AspNetWebApi.SelfHost" version="4.0.20710.0" targetFramework="net45" /> + <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebApi.Client" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebApi.Core" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebApi.SelfHost" version="4.0.20918.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OpenIdProviderMvc/Controllers/OpenIdController.cs b/samples/OpenIdProviderMvc/Controllers/OpenIdController.cs index bd6de1b..7828b5c 100644 --- a/samples/OpenIdProviderMvc/Controllers/OpenIdController.cs +++ b/samples/OpenIdProviderMvc/Controllers/OpenIdController.cs @@ -3,6 +3,7 @@ namespace OpenIdProviderMvc.Controllers { using System.Collections.Generic; using System.Linq; using System.Net; + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; @@ -29,12 +30,13 @@ namespace OpenIdProviderMvc.Controllers { public IFormsAuthentication FormsAuth { get; private set; } [ValidateInput(false)] - public ActionResult Provider() { - IRequest request = OpenIdProvider.GetRequest(); + public async Task<ActionResult> Provider() { + IRequest request = await OpenIdProvider.GetRequestAsync(this.Request, this.Response.ClientDisconnectedToken); if (request != null) { // Some requests are automatically handled by DotNetOpenAuth. If this is one, go ahead and let it go. if (request.IsResponseReady) { - return OpenIdProvider.PrepareResponse(request).AsActionResult(); + var response = await OpenIdProvider.PrepareResponseAsync(request, this.Response.ClientDisconnectedToken); + return response.AsActionResult(); } // This is apparently one that the host (the web site itself) has to respond to. @@ -51,28 +53,28 @@ namespace OpenIdProviderMvc.Controllers { } } - return this.ProcessAuthRequest(); + return await this.ProcessAuthRequest(); } else { // No OpenID request was recognized. This may be a user that stumbled on the OP Endpoint. return this.View(); } } - public ActionResult ProcessAuthRequest() { + public async Task<ActionResult> ProcessAuthRequest() { if (ProviderEndpoint.PendingRequest == null) { return this.RedirectToAction("Index", "Home"); } // Try responding immediately if possible. - ActionResult response; - if (this.AutoRespondIfPossible(out response)) { + ActionResult response = await this.AutoRespondIfPossibleAsync(); + if (response != null) { return response; } // We can't respond immediately with a positive result. But if we still have to respond immediately... if (ProviderEndpoint.PendingRequest.Immediate) { // We can't stop to prompt the user -- we must just return a negative response. - return this.SendAssertion(); + return await this.SendAssertion(); } return this.RedirectToAction("AskUser"); @@ -83,15 +85,15 @@ namespace OpenIdProviderMvc.Controllers { /// </summary> /// <returns>The response for the user agent.</returns> [Authorize] - public ActionResult AskUser() { + public async Task<ActionResult> AskUser() { if (ProviderEndpoint.PendingRequest == null) { // Oops... precious little we can confirm without a pending OpenID request. return this.RedirectToAction("Index", "Home"); } // The user MAY have just logged in. Try again to respond automatically to the RP if appropriate. - ActionResult response; - if (this.AutoRespondIfPossible(out response)) { + ActionResult response = await this.AutoRespondIfPossibleAsync(); + if (response != null) { return response; } @@ -106,10 +108,9 @@ namespace OpenIdProviderMvc.Controllers { } [HttpPost, Authorize, ValidateAntiForgeryToken] - public ActionResult AskUserResponse(bool confirmed) { + public async Task<ActionResult> AskUserResponse(bool confirmed) { if (!ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity && - !this.UserControlsIdentifier(ProviderEndpoint.PendingAuthenticationRequest)) - { + !this.UserControlsIdentifier(ProviderEndpoint.PendingAuthenticationRequest)) { // The user shouldn't have gotten this far without controlling the identifier we'd send an assertion for. return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest); } @@ -122,14 +123,14 @@ namespace OpenIdProviderMvc.Controllers { throw new InvalidOperationException("There's no pending authentication request!"); } - return this.SendAssertion(); + return await this.SendAssertion(); } /// <summary> /// Sends a positive or a negative assertion, based on how the pending request is currently marked. /// </summary> /// <returns>An MVC redirect result.</returns> - public ActionResult SendAssertion() { + public async Task<ActionResult> SendAssertion() { var pendingRequest = ProviderEndpoint.PendingRequest; var authReq = pendingRequest as IAuthenticationRequest; var anonReq = pendingRequest as IAnonymousRequest; @@ -188,17 +189,17 @@ namespace OpenIdProviderMvc.Controllers { } } - return OpenIdProvider.PrepareResponse(pendingRequest).AsActionResult(); + var response = await OpenIdProvider.PrepareResponseAsync(pendingRequest, this.Response.ClientDisconnectedToken); + return response.AsActionResult(); } /// <summary> /// Attempts to formulate an automatic response to the RP if the user's profile allows it. /// </summary> - /// <param name="response">Receives the ActionResult for the caller to return, or <c>null</c> if no automatic response can be made.</param> - /// <returns>A value indicating whether an automatic response is possible.</returns> - private bool AutoRespondIfPossible(out ActionResult response) { + /// <returns>The ActionResult for the caller to return, or <c>null</c> if no automatic response can be made.</returns> + private async Task<ActionResult> AutoRespondIfPossibleAsync() { // If the odds are good we can respond to this one immediately (without prompting the user)... - if (ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverable(OpenIdProvider.Channel.WebRequestHandler) == RelyingPartyDiscoveryResult.Success + if (await ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverableAsync(OpenIdProvider.Channel.HostFactories, this.Response.ClientDisconnectedToken) == RelyingPartyDiscoveryResult.Success && User.Identity.IsAuthenticated && this.HasUserAuthorizedAutoLogin(ProviderEndpoint.PendingRequest)) { // Is this is an identity authentication request? (as opposed to an anonymous request)... @@ -207,21 +208,18 @@ namespace OpenIdProviderMvc.Controllers { if (ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity || this.UserControlsIdentifier(ProviderEndpoint.PendingAuthenticationRequest)) { ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true; - response = this.SendAssertion(); - return true; + return await this.SendAssertion(); } } // If this is an anonymous request, we can respond to that too. if (ProviderEndpoint.PendingAnonymousRequest != null) { ProviderEndpoint.PendingAnonymousRequest.IsApproved = true; - response = this.SendAssertion(); - return true; + return await this.SendAssertion(); } } - response = null; - return false; + return null; } /// <summary> diff --git a/samples/OpenIdProviderMvc/OpenIdProviderMvc.csproj b/samples/OpenIdProviderMvc/OpenIdProviderMvc.csproj index 45686cd..2f64980 100644 --- a/samples/OpenIdProviderMvc/OpenIdProviderMvc.csproj +++ b/samples/OpenIdProviderMvc/OpenIdProviderMvc.csproj @@ -9,6 +9,7 @@ <IISExpressAnonymousAuthentication /> <IISExpressWindowsAuthentication /> <IISExpressUseClassicPipelineMode /> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\src\</SolutionDir> </PropertyGroup> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> @@ -45,23 +46,52 @@ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <ItemGroup> + <Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath> + </Reference> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Drawing" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web.DynamicData" /> <Reference Include="System.Web.Entity" /> <Reference Include="System.ComponentModel.DataAnnotations"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Web.Extensions" /> - <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> + <Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.Helpers.dll</HintPath> + </Reference> <Reference Include="System.Web" /> <Reference Include="System.Web.ApplicationServices" Condition=" '$(TargetFrameworkVersion)' != 'v3.5' "> <RequiredTargetFramework>v4.0</RequiredTargetFramework> </Reference> <Reference Include="System.Web.Abstractions" /> + <Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Mvc.4.0.20710.0\lib\net40\System.Web.Mvc.dll</HintPath> + </Reference> + <Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Razor.2.0.20715.0\lib\net40\System.Web.Razor.dll</HintPath> + </Reference> <Reference Include="System.Web.Routing" /> + <Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath> + </Reference> <Reference Include="System.Xml" /> <Reference Include="System.Configuration" /> <Reference Include="System.Web.Services" /> @@ -143,6 +173,9 @@ <Name>DotNetOpenAuth.ApplicationBlock</Name> </ProjectReference> </ItemGroup> + <ItemGroup> + <Content Include="packages.config" /> + </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /> @@ -172,4 +205,5 @@ </VisualStudio> </ProjectExtensions> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " /> + <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> </Project>
\ No newline at end of file diff --git a/samples/OpenIdProviderMvc/Web.config b/samples/OpenIdProviderMvc/Web.config index fd8f45d..b689b41 100644 --- a/samples/OpenIdProviderMvc/Web.config +++ b/samples/OpenIdProviderMvc/Web.config @@ -56,9 +56,12 @@ <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> <reporting enabled="true" /> </dotNetOpenAuth> - <appSettings/> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this @@ -67,8 +70,7 @@ --> <compilation debug="true" targetFramework="4.0"> <assemblies> - <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> - <remove assembly="DotNetOpenAuth.Contracts"/> + <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> @@ -125,7 +127,7 @@ </namespaces> </pages> <httpHandlers> - <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpHandlers> </system.web> <system.web.extensions/> @@ -139,17 +141,15 @@ <handlers> <remove name="MvcHttpHandler"/> <remove name="UrlRoutingHandler"/> - <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </handlers> </system.webServer> <runtime> <legacyHMACWarning enabled="0"/> - <!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink - to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it. --> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/> - <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/> + <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> diff --git a/samples/OpenIdProviderMvc/packages.config b/samples/OpenIdProviderMvc/packages.config new file mode 100644 index 0000000..c527bd3 --- /dev/null +++ b/samples/OpenIdProviderMvc/packages.config @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Razor" version="2.0.20715.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/samples/OpenIdProviderWebForms/Code/OAuthHybrid.cs b/samples/OpenIdProviderWebForms/Code/OAuthHybrid.cs index 8e64bfb..f96e87e 100644 --- a/samples/OpenIdProviderWebForms/Code/OAuthHybrid.cs +++ b/samples/OpenIdProviderWebForms/Code/OAuthHybrid.cs @@ -37,8 +37,8 @@ namespace OpenIdProviderWebForms.Code { internal static ServiceProviderOpenIdProvider ServiceProvider { get; private set; } - internal static ServiceProviderDescription GetServiceDescription() { - return new ServiceProviderDescription { + internal static ServiceProviderHostDescription GetServiceDescription() { + return new ServiceProviderHostDescription { TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, }; } diff --git a/samples/OpenIdProviderWebForms/Code/Util.cs b/samples/OpenIdProviderWebForms/Code/Util.cs index deff447..5333124 100644 --- a/samples/OpenIdProviderWebForms/Code/Util.cs +++ b/samples/OpenIdProviderWebForms/Code/Util.cs @@ -6,11 +6,13 @@ namespace OpenIdProviderWebForms.Code { using System; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Provider; - public class Util { + public static class Util { public static string ExtractUserName(Uri url) { return url.Segments[url.Segments.Length - 1]; } @@ -52,7 +54,7 @@ namespace OpenIdProviderWebForms.Code { // add extension responses here. } } else { - HttpContext.Current.Response.Redirect("~/decide.aspx", true); + HttpContext.Current.Response.Redirect("~/decide.aspx", false); } } @@ -68,8 +70,35 @@ namespace OpenIdProviderWebForms.Code { // These would typically be filled in from a user database } } else { - HttpContext.Current.Response.Redirect("~/decide.aspx", true); + HttpContext.Current.Response.Redirect("~/decide.aspx", false); } } + + internal static Task ToApm(this Task task, AsyncCallback callback, object state) { + if (task == null) { + throw new ArgumentNullException("task"); + } + + var tcs = new TaskCompletionSource<object>(state); + task.ContinueWith( + t => { + if (t.IsFaulted) { + tcs.TrySetException(t.Exception.InnerExceptions); + } else if (t.IsCanceled) { + tcs.TrySetCanceled(); + } else { + tcs.TrySetResult(null); + } + + if (callback != null) { + callback(tcs.Task); + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + + return tcs.Task; + } } }
\ No newline at end of file diff --git a/samples/OpenIdProviderWebForms/Default.aspx b/samples/OpenIdProviderWebForms/Default.aspx index 4f9e4bc..dfa056c 100644 --- a/samples/OpenIdProviderWebForms/Default.aspx +++ b/samples/OpenIdProviderWebForms/Default.aspx @@ -1,5 +1,5 @@ <%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="Default.aspx.cs" - Inherits="OpenIdProviderWebForms._default" %> + Inherits="OpenIdProviderWebForms._default" Async="true" %> <%@ Import Namespace="OpenIdProviderWebForms.Code" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.UI" Namespace="DotNetOpenAuth.OpenId" TagPrefix="openid" %> diff --git a/samples/OpenIdProviderWebForms/Default.aspx.cs b/samples/OpenIdProviderWebForms/Default.aspx.cs index 4843639..5d27251 100644 --- a/samples/OpenIdProviderWebForms/Default.aspx.cs +++ b/samples/OpenIdProviderWebForms/Default.aspx.cs @@ -1,6 +1,8 @@ namespace OpenIdProviderWebForms { using System; + using System.Threading.Tasks; using System.Web.Security; + using System.Web.UI; using System.Web.UI.WebControls; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; @@ -12,32 +14,42 @@ /// </summary> public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - if (Request.QueryString["rp"] != null) { - if (Page.User.Identity.IsAuthenticated) { - this.SendAssertion(Request.QueryString["rp"]); - } else { - FormsAuthentication.RedirectToLoginPage(); - } - } else { - TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite"); - if (relyingPartySite != null) { - relyingPartySite.Focus(); - } - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (Request.QueryString["rp"] != null) { + if (Page.User.Identity.IsAuthenticated) { + await this.SendAssertionAsync(Request.QueryString["rp"]); + } else { + FormsAuthentication.RedirectToLoginPage(); + } + } else { + TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite"); + if (relyingPartySite != null) { + relyingPartySite.Focus(); + } + } + })); } - protected void sendAssertionButton_Click(object sender, EventArgs e) { - TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite"); - this.SendAssertion(relyingPartySite.Text); + protected async void sendAssertionButton_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite"); + await this.SendAssertionAsync(relyingPartySite.Text); + })); } - private void SendAssertion(string relyingPartyRealm) { + private async Task SendAssertionAsync(string relyingPartyRealm) { Uri providerEndpoint = new Uri(Request.Url, Page.ResolveUrl("~/server.aspx")); OpenIdProvider op = new OpenIdProvider(); try { // Send user input through identifier parser so we accept more free-form input. string rpSite = Identifier.Parse(relyingPartyRealm); - op.PrepareUnsolicitedAssertion(providerEndpoint, rpSite, Util.BuildIdentityUrl(), Util.BuildIdentityUrl()).Send(); + var response = await op.PrepareUnsolicitedAssertionAsync(providerEndpoint, rpSite, Util.BuildIdentityUrl(), Util.BuildIdentityUrl()); + await response.SendAsync(); + this.Context.Response.End(); } catch (ProtocolException ex) { Label errorLabel = (Label)this.loginView.FindControl("errorLabel"); errorLabel.Visible = true; diff --git a/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj b/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj index 23d73d9..1ff3f44 100644 --- a/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj +++ b/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj @@ -69,6 +69,8 @@ <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Drawing" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web" /> <Reference Include="System.Web.DynamicData" /> <Reference Include="System.Web.Entity" /> @@ -249,7 +251,7 @@ <VisualStudio> <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"> <WebProjectProperties> - <UseIIS>True</UseIIS> + <UseIIS>False</UseIIS> <AutoAssignPort>False</AutoAssignPort> <DevelopmentServerPort>4860</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> diff --git a/samples/OpenIdProviderWebForms/ProfileFields.ascx.cs b/samples/OpenIdProviderWebForms/ProfileFields.ascx.cs index 6954aa6..e27f794 100644 --- a/samples/OpenIdProviderWebForms/ProfileFields.ascx.cs +++ b/samples/OpenIdProviderWebForms/ProfileFields.ascx.cs @@ -25,15 +25,15 @@ namespace OpenIdProviderWebForms { public DateTime? DateOfBirth { get { - try { - int day = Convert.ToInt32(this.dobDayDropdownlist.SelectedValue); - int month = Convert.ToInt32(this.dobMonthDropdownlist.SelectedValue); - int year = Convert.ToInt32(this.dobYearDropdownlist.SelectedValue); - DateTime newDate = new DateTime(year, month, day); + int day, month, year; + if (int.TryParse(this.dobDayDropdownlist.SelectedValue, out day) + && int.TryParse(this.dobMonthDropdownlist.SelectedValue, out month) + && int.TryParse(this.dobYearDropdownlist.SelectedValue, out year)) { + var newDate = new DateTime(year, month, day); return newDate; - } catch (Exception) { - return null; } + + return null; } set { diff --git a/samples/OpenIdProviderWebForms/Provider.ashx.cs b/samples/OpenIdProviderWebForms/Provider.ashx.cs index f8fa4a3..7022d80 100644 --- a/samples/OpenIdProviderWebForms/Provider.ashx.cs +++ b/samples/OpenIdProviderWebForms/Provider.ashx.cs @@ -1,7 +1,13 @@ namespace OpenIdProviderWebForms { + using System; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.SessionState; + using DotNetOpenAuth.ApplicationBlock; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Provider; + using OpenIdProviderWebForms.Code; /// <summary> /// A fast OpenID message handler that responds to OpenID messages @@ -12,13 +18,14 @@ /// control to reduce the amount of source code in the web site. A typical Provider /// site will have EITHER this .ashx handler OR the .aspx page -- NOT both. /// </remarks> - public class Provider : IHttpHandler, IRequiresSessionState { - public bool IsReusable { + public class Provider : HttpAsyncHandlerBase, IRequiresSessionState { + public override bool IsReusable { get { return true; } } - public void ProcessRequest(HttpContext context) { - IRequest request = ProviderEndpoint.Provider.GetRequest(); + protected override async Task ProcessRequestAsync(HttpContext context) { + var providerEndpoint = new ProviderEndpoint(); + IRequest request = await providerEndpoint.Provider.GetRequestAsync(new HttpRequestWrapper(context.Request), context.Response.ClientDisconnectedToken); if (request != null) { // Some OpenID requests are automatable and can be responded to immediately. // But authentication requests cannot be responded to until something on @@ -51,10 +58,12 @@ // We DON'T use ProviderEndpoint.SendResponse because // that only sends responses to requests in PendingAuthenticationRequest, // but we don't set that for associate and other non-checkid requests. - ProviderEndpoint.Provider.Respond(request); + var response = await providerEndpoint.Provider.PrepareResponseAsync(request, context.Response.ClientDisconnectedToken); // Make sure that any PendingAuthenticationRequest that MAY be set is cleared. ProviderEndpoint.PendingRequest = null; + + await response.SendAsync(new HttpContextWrapper(context)); } } } diff --git a/samples/OpenIdProviderWebForms/Web.config b/samples/OpenIdProviderWebForms/Web.config index efed107..c028df1 100644 --- a/samples/OpenIdProviderWebForms/Web.config +++ b/samples/OpenIdProviderWebForms/Web.config @@ -58,20 +58,19 @@ <appSettings> <!-- Get your own Yubico API key here: https://upgrade.yubico.com/getapikey/ --> <add key="YubicoAPIKey" value="3961"/> + + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> - <compilation debug="true" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <compilation debug="true" targetFramework="4.0" /> <sessionState mode="InProc" cookieless="false"/> <membership defaultProvider="AspNetReadOnlyXmlMembershipProvider"> <providers> @@ -90,7 +89,7 @@ Medium: doesn't work unless originUrl=".*" or WebPermission.Connect is extended, and Google Apps doesn't work. Low: doesn't work because WebPermission.Connect is denied. --> - <trust level="Medium" originUrl=".*"/> + <trust level="Full" originUrl=".*"/> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/> </system.web> <location path="decide.aspx"> diff --git a/samples/OpenIdProviderWebForms/access_token.ashx.cs b/samples/OpenIdProviderWebForms/access_token.ashx.cs index 1e3d27c..8dccc3f 100644 --- a/samples/OpenIdProviderWebForms/access_token.ashx.cs +++ b/samples/OpenIdProviderWebForms/access_token.ashx.cs @@ -2,22 +2,31 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Services; + using DotNetOpenAuth.ApplicationBlock; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using OpenIdProviderWebForms.Code; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] - public class access_token : IHttpHandler { - public bool IsReusable { + public class access_token : HttpAsyncHandlerBase { + public override bool IsReusable { get { return true; } } - public void ProcessRequest(HttpContext context) { - var request = OAuthHybrid.ServiceProvider.ReadAccessTokenRequest(); + protected override async Task ProcessRequestAsync(HttpContext context) { + var request = await OAuthHybrid.ServiceProvider.ReadAccessTokenRequestAsync( + new HttpRequestWrapper(context.Request), + context.Response.ClientDisconnectedToken); var response = OAuthHybrid.ServiceProvider.PrepareAccessTokenMessage(request); - OAuthHybrid.ServiceProvider.Channel.Respond(response); + var httpResponseMessage = await OAuthHybrid.ServiceProvider.Channel.PrepareResponseAsync( + response, + context.Response.ClientDisconnectedToken); + await httpResponseMessage.SendAsync(); } } } diff --git a/samples/OpenIdProviderWebForms/decide.aspx b/samples/OpenIdProviderWebForms/decide.aspx index d63364e..ddae8e7 100644 --- a/samples/OpenIdProviderWebForms/decide.aspx +++ b/samples/OpenIdProviderWebForms/decide.aspx @@ -1,5 +1,5 @@ <%@ Page Language="C#" AutoEventWireup="true" Inherits="OpenIdProviderWebForms.decide" - CodeBehind="decide.aspx.cs" MasterPageFile="~/Site.Master" %> + CodeBehind="decide.aspx.cs" MasterPageFile="~/Site.Master" Async="true" EnableSessionState="true" %> <%@ Register Src="ProfileFields.ascx" TagName="ProfileFields" TagPrefix="uc1" %> <asp:Content runat="server" ContentPlaceHolderID="Main"> diff --git a/samples/OpenIdProviderWebForms/decide.aspx.cs b/samples/OpenIdProviderWebForms/decide.aspx.cs index 8c8f927..00bdb6d 100644 --- a/samples/OpenIdProviderWebForms/decide.aspx.cs +++ b/samples/OpenIdProviderWebForms/decide.aspx.cs @@ -1,8 +1,10 @@ namespace OpenIdProviderWebForms { using System; using System.Diagnostics; + using System.Net; using System.Web.Security; using System.Web.UI; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Provider; @@ -13,102 +15,127 @@ namespace OpenIdProviderWebForms { /// </summary> public partial class decide : Page { protected void Page_Load(object src, EventArgs e) { - if (ProviderEndpoint.PendingRequest == null) { - Response.Redirect("~/"); - } - - this.relyingPartyVerificationResultLabel.Text = - ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverable(ProviderEndpoint.Provider.Channel.WebRequestHandler) == RelyingPartyDiscoveryResult.Success ? "passed" : "failed"; + this.RegisterAsyncTask(new PageAsyncTask(async ct => { + if (ProviderEndpoint.PendingRequest == null) { + // Response.Redirect(string) throws ThreadInterruptedException, and "async void Page_Load" doesn't properly catch it. + this.Response.RedirectLocation = "/"; + this.Response.StatusCode = (int)HttpStatusCode.Redirect; + this.Context.ApplicationInstance.CompleteRequest(); + return; + } - this.realmLabel.Text = ProviderEndpoint.PendingRequest.Realm.ToString(); + this.relyingPartyVerificationResultLabel.Text = + await ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverableAsync() == RelyingPartyDiscoveryResult.Success ? "passed" : "failed"; - var oauthRequest = OAuthHybrid.ServiceProvider.ReadAuthorizationRequest(ProviderEndpoint.PendingRequest); - if (oauthRequest != null) { - this.OAuthPanel.Visible = true; - } + this.realmLabel.Text = ProviderEndpoint.PendingRequest.Realm.ToString(); - if (ProviderEndpoint.PendingAuthenticationRequest != null) { - if (ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity) { - ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier = Code.Util.BuildIdentityUrl(); + var oauthRequest = OAuthHybrid.ServiceProvider.ReadAuthorizationRequest(ProviderEndpoint.PendingRequest); + if (oauthRequest != null) { + this.OAuthPanel.Visible = true; } - this.identityUrlLabel.Text = ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier.ToString(); - // check that the logged in user is the same as the user requesting authentication to the consumer. If not, then log them out. - if (!string.Equals(User.Identity.Name, Code.Util.ExtractUserName(ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier), StringComparison.OrdinalIgnoreCase)) { - FormsAuthentication.SignOut(); - Response.Redirect(Request.Url.AbsoluteUri); + if (ProviderEndpoint.PendingAuthenticationRequest != null) { + if (ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity) { + ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier = Code.Util.BuildIdentityUrl(); + } + this.identityUrlLabel.Text = ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier.ToString(); + + // check that the logged in user is the same as the user requesting authentication to the consumer. If not, then log them out. + if (!string.Equals(User.Identity.Name, Code.Util.ExtractUserName(ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier), StringComparison.OrdinalIgnoreCase)) { + FormsAuthentication.SignOut(); + Response.Redirect(Request.Url.AbsoluteUri); + } + } else { + this.identityUrlLabel.Text = "(not applicable)"; + this.siteRequestLabel.Text = "A site has asked for information about you."; } - } else { - this.identityUrlLabel.Text = "(not applicable)"; - this.siteRequestLabel.Text = "A site has asked for information about you."; - } - - // if simple registration fields were used, then prompt the user for them - var requestedFields = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>(); - if (requestedFields != null) { - this.profileFields.Visible = true; - this.profileFields.SetRequiredFieldsFromRequest(requestedFields); - if (!IsPostBack) { - var sregResponse = requestedFields.CreateResponse(); - - // We MAY not have an entry for this user if they used Yubikey to log in. - MembershipUser user = Membership.GetUser(); - if (user != null) { - sregResponse.Email = Membership.GetUser().Email; + + // if simple registration fields were used, then prompt the user for them + var requestedFields = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>(); + if (requestedFields != null) { + this.profileFields.Visible = true; + this.profileFields.SetRequiredFieldsFromRequest(requestedFields); + if (!IsPostBack) { + var sregResponse = requestedFields.CreateResponse(); + + // We MAY not have an entry for this user if they used Yubikey to log in. + MembershipUser user = Membership.GetUser(); + if (user != null) { + sregResponse.Email = Membership.GetUser().Email; + } + this.profileFields.SetOpenIdProfileFields(sregResponse); } - this.profileFields.SetOpenIdProfileFields(sregResponse); } - } + })); } protected void Yes_Click(object sender, EventArgs e) { - if (!Page.IsValid) { - return; - } - - if (this.OAuthPanel.Visible) { - string grantedScope = null; - if (this.oauthPermission.Checked) { - // This SIMPLE sample merely uses the realm as the consumerKey, - // but in a real app this will probably involve a database lookup to translate - // the realm to a known consumerKey. - grantedScope = string.Empty; // we don't scope individual access rights on this sample - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!Page.IsValid || ProviderEndpoint.PendingRequest == null) { + return; + } + + if (this.OAuthPanel.Visible) { + string grantedScope = null; + if (this.oauthPermission.Checked) { + // This SIMPLE sample merely uses the realm as the consumerKey, + // but in a real app this will probably involve a database lookup to translate + // the realm to a known consumerKey. + grantedScope = string.Empty; // we don't scope individual access rights on this sample + } + + OAuthHybrid.ServiceProvider.AttachAuthorizationResponse(ProviderEndpoint.PendingRequest, grantedScope); + } - OAuthHybrid.ServiceProvider.AttachAuthorizationResponse(ProviderEndpoint.PendingRequest, grantedScope); - } - - var sregRequest = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>(); - ClaimsResponse sregResponse = null; - if (sregRequest != null) { - sregResponse = this.profileFields.GetOpenIdProfileFields(sregRequest); - ProviderEndpoint.PendingRequest.AddResponseExtension(sregResponse); - } - var papeRequest = ProviderEndpoint.PendingRequest.GetExtension<PolicyRequest>(); - PolicyResponse papeResponse = null; - if (papeRequest != null) { - papeResponse = new PolicyResponse(); - papeResponse.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1; - ProviderEndpoint.PendingRequest.AddResponseExtension(papeResponse); - } - - if (ProviderEndpoint.PendingAuthenticationRequest != null) { - ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true; - } else { - ProviderEndpoint.PendingAnonymousRequest.IsApproved = true; - } - Debug.Assert(ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary."); - ProviderEndpoint.SendResponse(); + var sregRequest = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>(); + ClaimsResponse sregResponse = null; + if (sregRequest != null) { + sregResponse = this.profileFields.GetOpenIdProfileFields(sregRequest); + ProviderEndpoint.PendingRequest.AddResponseExtension(sregResponse); + } + var papeRequest = ProviderEndpoint.PendingRequest.GetExtension<PolicyRequest>(); + PolicyResponse papeResponse = null; + if (papeRequest != null) { + papeResponse = new PolicyResponse(); + papeResponse.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1; + ProviderEndpoint.PendingRequest.AddResponseExtension(papeResponse); + } + + if (ProviderEndpoint.PendingAuthenticationRequest != null) { + ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true; + } else { + ProviderEndpoint.PendingAnonymousRequest.IsApproved = true; + } + Debug.Assert( + ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary."); + + var provider = new ProviderEndpoint(); + var response = await provider.PrepareResponseAsync(); + await response.SendAsync(); + })); } protected void No_Click(object sender, EventArgs e) { - if (ProviderEndpoint.PendingAuthenticationRequest != null) { - ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = false; - } else { - ProviderEndpoint.PendingAnonymousRequest.IsApproved = false; - } - Debug.Assert(ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary."); - ProviderEndpoint.SendResponse(); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (ProviderEndpoint.PendingRequest == null) { + return; + } + + if (ProviderEndpoint.PendingAuthenticationRequest != null) { + ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = false; + } else { + ProviderEndpoint.PendingAnonymousRequest.IsApproved = false; + } + Debug.Assert( + ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary."); + var provider = new ProviderEndpoint(); + var response = await provider.PrepareResponseAsync(); + await response.SendAsync(); + })); } } }
\ No newline at end of file diff --git a/samples/OpenIdProviderWebForms/decide.aspx.designer.cs b/samples/OpenIdProviderWebForms/decide.aspx.designer.cs index 3aa6271..f40323c 100644 --- a/samples/OpenIdProviderWebForms/decide.aspx.designer.cs +++ b/samples/OpenIdProviderWebForms/decide.aspx.designer.cs @@ -1,10 +1,9 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:2.0.50727.4918 // // Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ diff --git a/samples/OpenIdProviderWebForms/packages.config b/samples/OpenIdProviderWebForms/packages.config index 6562527..8e40260 100644 --- a/samples/OpenIdProviderWebForms/packages.config +++ b/samples/OpenIdProviderWebForms/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OpenIdProviderWebForms/server.aspx b/samples/OpenIdProviderWebForms/server.aspx index 101aeee..946f044 100644 --- a/samples/OpenIdProviderWebForms/server.aspx +++ b/samples/OpenIdProviderWebForms/server.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" Inherits="OpenIdProviderWebForms.server" CodeBehind="server.aspx.cs" ValidateRequest="false" %> +<%@ Page Language="C#" AutoEventWireup="true" Inherits="OpenIdProviderWebForms.server" CodeBehind="server.aspx.cs" ValidateRequest="false" Async="true" EnableSessionState="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.Provider.UI" Namespace="DotNetOpenAuth.OpenId.Provider" TagPrefix="openid" %> <html> diff --git a/samples/OpenIdProviderWebForms/server.aspx.cs b/samples/OpenIdProviderWebForms/server.aspx.cs index 89e14f4..e613192 100644 --- a/samples/OpenIdProviderWebForms/server.aspx.cs +++ b/samples/OpenIdProviderWebForms/server.aspx.cs @@ -7,15 +7,27 @@ namespace OpenIdProviderWebForms { /// This page is responsible for handling all open-id compliant requests. /// </summary> public partial class server : System.Web.UI.Page { - protected void Page_Load(object src, System.EventArgs evt) { + protected void Page_Load(object src, EventArgs evt) { this.serverEndpointUrl.Text = Request.Url.ToString(); } protected void provider_AuthenticationChallenge(object sender, AuthenticationChallengeEventArgs e) { + // We store the request in the user's session so that + // redirects and user prompts can appear and eventually some page can decide + // to respond to the OpenID authentication request either affirmatively or + // negatively. + ProviderEndpoint.PendingRequest = e.Request; + Code.Util.ProcessAuthenticationChallenge(e.Request); } protected void provider_AnonymousRequest(object sender, AnonymousRequestEventArgs e) { + // We store the request in the user's session so that + // redirects and user prompts can appear and eventually some page can decide + // to respond to the OpenID authentication request either affirmatively or + // negatively. + ProviderEndpoint.PendingRequest = e.Request; + Code.Util.ProcessAnonymousRequest(e.Request); } } diff --git a/samples/OpenIdRelyingPartyMvc/Controllers/UserController.cs b/samples/OpenIdRelyingPartyMvc/Controllers/UserController.cs index 3ff405f..41a090f 100644 --- a/samples/OpenIdRelyingPartyMvc/Controllers/UserController.cs +++ b/samples/OpenIdRelyingPartyMvc/Controllers/UserController.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Security; @@ -31,14 +32,16 @@ } [ValidateInput(false)] - public ActionResult Authenticate(string returnUrl) { - var response = openid.GetResponse(); + public async Task<ActionResult> Authenticate(string returnUrl) { + var response = await openid.GetResponseAsync(this.Request, this.Response.ClientDisconnectedToken); if (response == null) { // Stage 2: user submitting Identifier Identifier id; if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) { try { - return openid.CreateRequest(Request.Form["openid_identifier"]).RedirectingResponse.AsActionResult(); + var request = await openid.CreateRequestAsync(Request.Form["openid_identifier"]); + var redirectingResponse = await request.GetRedirectingResponseAsync(this.Response.ClientDisconnectedToken); + return redirectingResponse.AsActionResult(); } catch (ProtocolException ex) { ViewData["Message"] = ex.Message; return View("Login"); @@ -52,7 +55,8 @@ switch (response.Status) { case AuthenticationStatus.Authenticated: Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay; - FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false); + var cookie = FormsAuthentication.GetAuthCookie(response.ClaimedIdentifier, false); + Response.SetCookie(cookie); if (!string.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } else { diff --git a/samples/OpenIdRelyingPartyMvc/OpenIdRelyingPartyMvc.csproj b/samples/OpenIdRelyingPartyMvc/OpenIdRelyingPartyMvc.csproj index e2ff559..8e3fb26 100644 --- a/samples/OpenIdRelyingPartyMvc/OpenIdRelyingPartyMvc.csproj +++ b/samples/OpenIdRelyingPartyMvc/OpenIdRelyingPartyMvc.csproj @@ -9,6 +9,7 @@ <IISExpressAnonymousAuthentication /> <IISExpressWindowsAuthentication /> <IISExpressUseClassicPipelineMode /> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\src\</SolutionDir> </PropertyGroup> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> @@ -45,10 +46,16 @@ <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> </PropertyGroup> <ItemGroup> + <Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath> + </Reference> <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Drawing" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web.ApplicationServices" /> <Reference Include="System.Web.DynamicData" /> <Reference Include="System.Web.Entity" /> @@ -56,10 +63,33 @@ <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Web.Extensions" /> - <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> <Reference Include="System.Web" /> <Reference Include="System.Web.Abstractions" /> + <Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.Helpers.dll</HintPath> + </Reference> + <Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Mvc.4.0.20710.0\lib\net40\System.Web.Mvc.dll</HintPath> + </Reference> + <Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.Razor.2.0.20715.0\lib\net40\System.Web.Razor.dll</HintPath> + </Reference> <Reference Include="System.Web.Routing" /> + <Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> + </Reference> + <Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Private>True</Private> + <HintPath>..\..\src\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath> + </Reference> <Reference Include="System.Xml" /> <Reference Include="System.Configuration" /> <Reference Include="System.Web.Services" /> @@ -156,6 +186,9 @@ <Name>DotNetOpenAuth.OpenId</Name> </ProjectReference> </ItemGroup> + <ItemGroup> + <Content Include="packages.config" /> + </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /> @@ -185,4 +218,5 @@ </VisualStudio> </ProjectExtensions> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " /> + <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> </Project>
\ No newline at end of file diff --git a/samples/OpenIdRelyingPartyMvc/Web.config b/samples/OpenIdRelyingPartyMvc/Web.config index 67c1dd4..8e432b0 100644 --- a/samples/OpenIdRelyingPartyMvc/Web.config +++ b/samples/OpenIdRelyingPartyMvc/Web.config @@ -56,9 +56,12 @@ <reporting enabled="true" /> </dotNetOpenAuth> - <appSettings/> + <appSettings> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> + </appSettings> <connectionStrings/> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this @@ -67,8 +70,7 @@ --> <compilation debug="true" targetFramework="4.0"> <assemblies> - <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> - <remove assembly="DotNetOpenAuth.Contracts"/> + <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> @@ -110,7 +112,7 @@ </namespaces> </pages> <httpHandlers> - <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpHandlers> </system.web> <system.web.extensions/> @@ -124,19 +126,19 @@ <handlers> <remove name="MvcHttpHandler"/> <remove name="UrlRoutingHandler"/> - <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </handlers> </system.webServer> <runtime> <legacyHMACWarning enabled="0" /> - <!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink + <!-- When targeting ASP.NET MVC 4, this assemblyBinding makes MVC 1 and 2 references relink to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it. --> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> - <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> + <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> diff --git a/samples/OpenIdRelyingPartyMvc/packages.config b/samples/OpenIdRelyingPartyMvc/packages.config new file mode 100644 index 0000000..c527bd3 --- /dev/null +++ b/samples/OpenIdRelyingPartyMvc/packages.config @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Razor" version="2.0.20715.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/samples/OpenIdRelyingPartyWebForms/Code/State.cs b/samples/OpenIdRelyingPartyWebForms/Code/State.cs index c8147e5..c8cef80 100644 --- a/samples/OpenIdRelyingPartyWebForms/Code/State.cs +++ b/samples/OpenIdRelyingPartyWebForms/Code/State.cs @@ -1,5 +1,6 @@ namespace OpenIdRelyingPartyWebForms { using System.Web; + using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; @@ -28,8 +29,8 @@ namespace OpenIdRelyingPartyWebForms { set { HttpContext.Current.Session["PapePolicies"] = value; } } - public static string GoogleAccessToken { - get { return HttpContext.Current.Session["GoogleAccessToken"] as string; } + public static AccessToken GoogleAccessToken { + get { return (AccessToken)(HttpContext.Current.Session["GoogleAccessToken"] ?? new AccessToken()); } set { HttpContext.Current.Session["GoogleAccessToken"] = value; } } @@ -38,7 +39,7 @@ namespace OpenIdRelyingPartyWebForms { FetchResponse = null; FriendlyLoginName = null; PapePolicies = null; - GoogleAccessToken = null; + GoogleAccessToken = new AccessToken(); } } }
\ No newline at end of file diff --git a/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx b/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx index 8c99efe..21b6a12 100644 --- a/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx +++ b/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx @@ -1,6 +1,6 @@ <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DetectGoogleSession.aspx.cs" Inherits="OpenIdRelyingPartyWebForms.DetectGoogleSession" ValidateRequest="false" - MasterPageFile="~/Site.Master" %> + MasterPageFile="~/Site.Master" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="rp" %> diff --git a/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs b/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs index d6cf2ac..909c4bc 100644 --- a/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs @@ -1,5 +1,8 @@ namespace OpenIdRelyingPartyWebForms { using System; + using System.Web; + using System.Web.UI; + using DotNetOpenAuth.ApplicationBlock.CustomExtensions; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.UI; @@ -11,37 +14,44 @@ private const string UIModeDetectSession = "x-has-session"; protected void Page_Load(object sender, EventArgs e) { - using (var openid = new OpenIdRelyingParty()) { - // In order to receive the UIRequest as a response, we must register a custom extension factory. - openid.ExtensionFactories.Add(new UIRequestAtRelyingPartyFactory()); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + using (var openid = new OpenIdRelyingParty()) { + // In order to receive the UIRequest as a response, we must register a custom extension factory. + openid.ExtensionFactories.Add(new UIRequestAtRelyingPartyFactory()); - var response = openid.GetResponse(); - if (response == null) { - // Submit an OpenID request which Google must reply to immediately. - // If the user hasn't established a trust relationship with this site yet, - // Google will not give us the user identity, but they will tell us whether the user - // at least has an active login session with them so we know whether to promote the - // "Log in with Google" button. - IAuthenticationRequest request = openid.CreateRequest("https://www.google.com/accounts/o8/id"); - request.AddExtension(new UIRequest { Mode = UIModeDetectSession }); - request.Mode = AuthenticationRequestMode.Immediate; - request.RedirectToProvider(); - } else { - if (response.Status == AuthenticationStatus.Authenticated) { - this.YouTrustUsLabel.Visible = true; - } else if (response.Status == AuthenticationStatus.SetupRequired) { - // Google refused to authenticate the user without user interaction. - // This is either because Google doesn't know who the user is yet, - // or because the user hasn't indicated to Google to trust this site. - // Google uniquely offers the RP a tip as to which of the above situations is true. - // Figure out which it is. In a real app, you might use this value to promote a - // Google login button on your site if you detect that a Google session exists. - var ext = response.GetUntrustedExtension<UIRequest>(); - this.YouAreLoggedInLabel.Visible = ext != null && ext.Mode == UIModeDetectSession; - this.YouAreNotLoggedInLabel.Visible = !this.YouAreLoggedInLabel.Visible; - } - } - } + var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (response == null) { + // Submit an OpenID request which Google must reply to immediately. + // If the user hasn't established a trust relationship with this site yet, + // Google will not give us the user identity, but they will tell us whether the user + // at least has an active login session with them so we know whether to promote the + // "Log in with Google" button. + IAuthenticationRequest request = + await + openid.CreateRequestAsync( + "https://www.google.com/accounts/o8/id", new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + request.AddExtension(new UIRequest { Mode = UIModeDetectSession }); + request.Mode = AuthenticationRequestMode.Immediate; + await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); + } else { + if (response.Status == AuthenticationStatus.Authenticated) { + this.YouTrustUsLabel.Visible = true; + } else if (response.Status == AuthenticationStatus.SetupRequired) { + // Google refused to authenticate the user without user interaction. + // This is either because Google doesn't know who the user is yet, + // or because the user hasn't indicated to Google to trust this site. + // Google uniquely offers the RP a tip as to which of the above situations is true. + // Figure out which it is. In a real app, you might use this value to promote a + // Google login button on your site if you detect that a Google session exists. + var ext = response.GetUntrustedExtension<UIRequest>(); + this.YouAreLoggedInLabel.Visible = ext != null && ext.Mode == UIModeDetectSession; + this.YouAreNotLoggedInLabel.Visible = !this.YouAreLoggedInLabel.Visible; + } + } + } + })); } } }
\ No newline at end of file diff --git a/samples/OpenIdRelyingPartyWebForms/Global.asax.cs b/samples/OpenIdRelyingPartyWebForms/Global.asax.cs index 6283987..8460d49 100644 --- a/samples/OpenIdRelyingPartyWebForms/Global.asax.cs +++ b/samples/OpenIdRelyingPartyWebForms/Global.asax.cs @@ -18,7 +18,7 @@ get { var googleWebConsumer = (WebConsumerOpenIdRelyingParty)HttpContext.Current.Application["GoogleWebConsumer"]; if (googleWebConsumer == null) { - googleWebConsumer = new WebConsumerOpenIdRelyingParty(GoogleConsumer.ServiceDescription, GoogleTokenManager); + googleWebConsumer = new WebConsumerOpenIdRelyingParty { ServiceProvider = GoogleConsumer.ServiceDescription }; HttpContext.Current.Application["GoogleWebConsumer"] = googleWebConsumer; } @@ -26,36 +26,6 @@ } } - internal static InMemoryTokenManager GoogleTokenManager { - get { - var tokenManager = (InMemoryTokenManager)HttpContext.Current.Application["GoogleTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - HttpContext.Current.Application["GoogleTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - internal static InMemoryTokenManager OwnSampleOPHybridTokenManager { - get { - var tokenManager = (InMemoryTokenManager)HttpContext.Current.Application["OwnSampleOPHybridTokenManager"]; - if (tokenManager == null) { - string consumerKey = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Request.ApplicationPath).AbsoluteUri; - string consumerSecret = "some crazy secret"; - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - HttpContext.Current.Application["OwnSampleOPHybridTokenManager"] = tokenManager; - } - - return tokenManager; - } - } - public static string ToString(NameValueCollection collection) { using (StringWriter sw = new StringWriter()) { foreach (string key in collection.Keys) { diff --git a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx index 7d5a54f..b8caa93 100644 --- a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx +++ b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx @@ -1,5 +1,5 @@ <%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="DisplayGoogleContacts.aspx.cs" - Inherits="OpenIdRelyingPartyWebForms.MembersOnly.DisplayGoogleContacts" %> + Inherits="OpenIdRelyingPartyWebForms.MembersOnly.DisplayGoogleContacts" Async="true" %> <asp:Content ID="Content1" runat="server" ContentPlaceHolderID="Main"> <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> diff --git a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs index c95fc7c..d06e2f6 100644 --- a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using System.Web; + using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; using DotNetOpenAuth.ApplicationBlock; @@ -10,17 +11,25 @@ public partial class DisplayGoogleContacts : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - if (!string.IsNullOrEmpty(State.GoogleAccessToken)) { - this.MultiView1.ActiveViewIndex = 1; - if (State.FetchResponse != null && State.FetchResponse.Attributes.Contains(WellKnownAttributes.Contact.Email)) { - this.emailLabel.Text = State.FetchResponse.Attributes[WellKnownAttributes.Contact.Email].Values[0]; - } else { - this.emailLabel.Text = "unavailable"; - } - this.claimedIdLabel.Text = this.User.Identity.Name; - var contactsDocument = GoogleConsumer.GetContacts(Global.GoogleWebConsumer, State.GoogleAccessToken, 25, 1); - this.RenderContacts(contactsDocument); - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!string.IsNullOrEmpty(State.GoogleAccessToken.Token)) { + this.MultiView1.ActiveViewIndex = 1; + if (State.FetchResponse != null && State.FetchResponse.Attributes.Contains(WellKnownAttributes.Contact.Email)) { + this.emailLabel.Text = State.FetchResponse.Attributes[WellKnownAttributes.Contact.Email].Values[0]; + } else { + this.emailLabel.Text = "unavailable"; + } + this.claimedIdLabel.Text = this.User.Identity.Name; + var google = new GoogleConsumer { + ConsumerKey = Global.GoogleWebConsumer.ConsumerKey, + ConsumerSecret = Global.GoogleWebConsumer.ConsumerSecret, + }; + var contactsDocument = await google.GetContactsAsync(State.GoogleAccessToken); + this.RenderContacts(contactsDocument); + } + })); } private void RenderContacts(XDocument contactsDocument) { diff --git a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.designer.cs b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.designer.cs index 5cc5894..9521781 100644 --- a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.designer.cs +++ b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.designer.cs @@ -1,10 +1,9 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:2.0.50727.4918 // // Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ diff --git a/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx b/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx index cec5f49..e9dcf5d 100644 --- a/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx +++ b/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NoIdentityOpenId.aspx.cs" +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NoIdentityOpenId.aspx.cs" Async="true" MasterPageFile="~/Site.Master" Inherits="OpenIdRelyingPartyWebForms.NoIdentityOpenId" %> <asp:Content runat="server" ContentPlaceHolderID="Main"> diff --git a/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs b/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs index ca12964..fcfa257 100644 --- a/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs @@ -1,5 +1,8 @@ namespace OpenIdRelyingPartyWebForms { using System; + using System.Threading; + using System.Web; + using System.Web.UI; using System.Web.UI.WebControls; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; @@ -7,10 +10,10 @@ using DotNetOpenAuth.OpenId.RelyingParty; public partial class NoIdentityOpenId : System.Web.UI.Page { - protected void Page_Load(object sender, EventArgs e) { + protected async void Page_Load(object sender, EventArgs e) { this.openIdBox.Focus(); using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) { - IAuthenticationResponse response = rp.GetResponse(); + IAuthenticationResponse response = await rp.GetResponseAsync(new HttpRequestWrapper(this.Request), this.Response.ClientDisconnectedToken); if (response != null) { switch (response.Status) { case AuthenticationStatus.ExtensionsOnly: @@ -45,32 +48,39 @@ } protected void beginButton_Click(object sender, EventArgs e) { - if (!this.Page.IsValid) { - return; // don't login if custom validation failed. - } - try { - using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) { - var request = rp.CreateRequest(this.openIdBox.Text); - request.IsExtensionOnly = true; + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!this.Page.IsValid) { + return; // don't login if custom validation failed. + } + try { + using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) { + var request = + await + rp.CreateRequestAsync(this.openIdBox.Text, new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + request.IsExtensionOnly = true; - // This is where you would add any OpenID extensions you wanted - // to include in the request. - request.AddExtension(new ClaimsRequest { - Email = DemandLevel.Request, - Country = DemandLevel.Request, - Gender = DemandLevel.Require, - PostalCode = DemandLevel.Require, - TimeZone = DemandLevel.Require, - }); + // This is where you would add any OpenID extensions you wanted + // to include in the request. + request.AddExtension( + new ClaimsRequest { + Email = DemandLevel.Request, + Country = DemandLevel.Request, + Gender = DemandLevel.Require, + PostalCode = DemandLevel.Require, + TimeZone = DemandLevel.Require, + }); - request.RedirectToProvider(); - } - } catch (ProtocolException ex) { - // The user probably entered an Identifier that - // was not a valid OpenID endpoint. - this.openidValidator.Text = ex.Message; - this.openidValidator.IsValid = false; - } + await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken); + } + } catch (ProtocolException ex) { + // The user probably entered an Identifier that + // was not a valid OpenID endpoint. + this.openidValidator.Text = ex.Message; + this.openidValidator.IsValid = false; + } + })); } protected void openidValidator_ServerValidate(object source, ServerValidateEventArgs args) { diff --git a/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj b/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj index cf12262..03675d2 100644 --- a/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj +++ b/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj @@ -72,6 +72,8 @@ <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Drawing" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web" /> <Reference Include="System.Web.ApplicationServices" /> <Reference Include="System.Web.DynamicData" /> @@ -100,9 +102,6 @@ </Content> </ItemGroup> <ItemGroup> - <Compile Include="..\DotNetOpenAuth.ApplicationBlock\InMemoryTokenManager.cs"> - <Link>Code\InMemoryTokenManager.cs</Link> - </Compile> <Compile Include="ajaxlogin.aspx.cs"> <DependentUpon>ajaxlogin.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> diff --git a/samples/OpenIdRelyingPartyWebForms/Web.config b/samples/OpenIdRelyingPartyWebForms/Web.config index 479b285..f5fada9 100644 --- a/samples/OpenIdRelyingPartyWebForms/Web.config +++ b/samples/OpenIdRelyingPartyWebForms/Web.config @@ -66,14 +66,13 @@ <!-- Google sign-up: https://www.google.com/accounts/ManageDomains --> <add key="googleConsumerKey" value="demo.dotnetopenauth.net"/> <add key="googleConsumerSecret" value="5Yv1TfKm1551QrXZ9GpqepeD"/> + + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <system.web> <!--<sessionState cookieless="true" />--> - <compilation debug="true" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <httpRuntime targetFramework="4.5" /> + <compilation debug="true" targetFramework="4.0" /> <customErrors mode="RemoteOnly"/> <authentication mode="Forms"> <forms name="OpenIdRelyingPartySession"/> <!-- named cookie prevents conflicts with other samples --> @@ -85,7 +84,7 @@ Medium: doesn't work unless originUrl=".*" or WebPermission.Connect is extended, and Google Apps doesn't work. Low: doesn't work because WebPermission.Connect is denied. --> - <trust level="Medium" originUrl=".*"/> + <trust level="Full" originUrl=".*"/> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/> </system.web> diff --git a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx index d2b3255..916fca3 100644 --- a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx +++ b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx @@ -1,5 +1,5 @@ <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ajaxlogin.aspx.cs" Inherits="OpenIdRelyingPartyWebForms.ajaxlogin" - ValidateRequest="false" MasterPageFile="~/Site.Master" %> + ValidateRequest="false" MasterPageFile="~/Site.Master" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="openid" %> <asp:Content runat="server" ContentPlaceHolderID="head"> diff --git a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs index f7d44d5..ebfece3 100644 --- a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs @@ -1,5 +1,6 @@ namespace OpenIdRelyingPartyWebForms { using System; + using System.Web.UI; using System.Web.UI.WebControls; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; @@ -30,17 +31,23 @@ } protected void submitButton_Click(object sender, EventArgs e) { - if (!Page.IsValid) { - return; - } - if (this.OpenIdAjaxTextBox1.AuthenticationResponse != null) { - if (this.OpenIdAjaxTextBox1.AuthenticationResponse.Status == AuthenticationStatus.Authenticated) { - // Save comment here! - this.multiView.ActiveViewIndex = 1; - } else { - this.multiView.ActiveViewIndex = 2; - } - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!Page.IsValid) { + return; + } + + var response = await this.OpenIdAjaxTextBox1.GetAuthenticationResponseAsync(Response.ClientDisconnectedToken); + if (response != null) { + if (response.Status == AuthenticationStatus.Authenticated) { + // Save comment here! + this.multiView.ActiveViewIndex = 1; + } else { + this.multiView.ActiveViewIndex = 2; + } + } + })); } protected void editComment_Click(object sender, EventArgs e) { diff --git a/samples/OpenIdRelyingPartyWebForms/login.aspx b/samples/OpenIdRelyingPartyWebForms/login.aspx index 17a230a..fc42b73 100644 --- a/samples/OpenIdRelyingPartyWebForms/login.aspx +++ b/samples/OpenIdRelyingPartyWebForms/login.aspx @@ -1,5 +1,5 @@ <%@ Page Language="C#" AutoEventWireup="True" CodeBehind="login.aspx.cs" Inherits="OpenIdRelyingPartyWebForms.login" - ValidateRequest="false" MasterPageFile="~/Site.Master" %> + ValidateRequest="false" MasterPageFile="~/Site.Master" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="rp" %> <%@ Register Assembly="DotNetOpenAuth.OpenId" Namespace="DotNetOpenAuth.OpenId.Extensions.SimpleRegistration" TagPrefix="sreg" %> diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx index 31c48fa..6c3f822 100644 --- a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx +++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx @@ -1,6 +1,6 @@ <%@ Page Language="C#" AutoEventWireup="True" CodeBehind="loginPlusOAuth.aspx.cs" Inherits="OpenIdRelyingPartyWebForms.loginPlusOAuth" ValidateRequest="false" - MasterPageFile="~/Site.Master" %> + MasterPageFile="~/Site.Master" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="rp" %> diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs index d4e9885..ecfaf49 100644 --- a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs @@ -1,7 +1,12 @@ namespace OpenIdRelyingPartyWebForms { using System; + using System.Threading.Tasks; + using System.Web; using System.Web.Security; + using System.Web.UI; + using DotNetOpenAuth.ApplicationBlock; + using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.Messages; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; @@ -12,40 +17,51 @@ private static readonly OpenIdRelyingParty relyingParty = new OpenIdRelyingParty(); protected void Page_Load(object sender, EventArgs e) { - if (!IsPostBack && string.Equals(Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase)) { - // Disable the button since the scenario won't work under localhost, - // and this will help encourage the user to read the the text above the button. - this.beginButton.Enabled = false; - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!IsPostBack && string.Equals(Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase)) { + // Disable the button since the scenario won't work under localhost, + // and this will help encourage the user to read the the text above the button. + this.beginButton.Enabled = false; + } - IAuthenticationResponse authResponse = relyingParty.GetResponse(); - if (authResponse != null) { - switch (authResponse.Status) { - case AuthenticationStatus.Authenticated: - State.FetchResponse = authResponse.GetExtension<FetchResponse>(); - AuthorizedTokenResponse accessToken = Global.GoogleWebConsumer.ProcessUserAuthorization(authResponse); - if (accessToken != null) { - State.GoogleAccessToken = accessToken.AccessToken; - FormsAuthentication.SetAuthCookie(authResponse.ClaimedIdentifier, false); - Response.Redirect("~/MembersOnly/DisplayGoogleContacts.aspx"); - } else { - MultiView1.SetActiveView(AuthorizationDenied); + IAuthenticationResponse authResponse = + await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (authResponse != null) { + switch (authResponse.Status) { + case AuthenticationStatus.Authenticated: + State.FetchResponse = authResponse.GetExtension<FetchResponse>(); + AccessTokenResponse accessToken = + await Global.GoogleWebConsumer.ProcessUserAuthorizationAsync(authResponse, Response.ClientDisconnectedToken); + if (accessToken != null) { + State.GoogleAccessToken = accessToken.AccessToken; + FormsAuthentication.SetAuthCookie(authResponse.ClaimedIdentifier, false); + Response.Redirect("~/MembersOnly/DisplayGoogleContacts.aspx"); + } else { + MultiView1.SetActiveView(AuthorizationDenied); + } + break; + case AuthenticationStatus.Canceled: + case AuthenticationStatus.Failed: + default: + this.MultiView1.SetActiveView(this.AuthenticationFailed); + break; + } } - break; - case AuthenticationStatus.Canceled: - case AuthenticationStatus.Failed: - default: - this.MultiView1.SetActiveView(this.AuthenticationFailed); - break; - } - } + })); } protected void beginButton_Click(object sender, EventArgs e) { - this.GetGoogleRequest().RedirectToProvider(); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var request = await this.GetGoogleRequestAsync(); + await request.RedirectToProviderAsync(); + })); } - private IAuthenticationRequest GetGoogleRequest() { + private async Task<IAuthenticationRequest> GetGoogleRequestAsync() { // Google requires that the realm and consumer key be equal, // so we constrain the realm to match the realm in the web.config file. // This does mean that the return_to URL must also fall under the key, @@ -53,8 +69,8 @@ // that is properly registered with Google. // We will customize the realm to use http or https based on what the // return_to URL will be (which will be this page). - Realm realm = Request.Url.Scheme + Uri.SchemeDelimiter + Global.GoogleTokenManager.ConsumerKey + "/"; - IAuthenticationRequest authReq = relyingParty.CreateRequest(GoogleOPIdentifier, realm); + Realm realm = Request.Url.Scheme + Uri.SchemeDelimiter + (new GoogleConsumer()).ConsumerKey + "/"; + IAuthenticationRequest authReq = await relyingParty.CreateRequestAsync(GoogleOPIdentifier, realm, cancellationToken: Response.ClientDisconnectedToken); // Prepare the OAuth extension string scope = GoogleConsumer.GetScopeUri(GoogleConsumer.Applications.Contacts); diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx index 13ef590..4647939 100644 --- a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx +++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx @@ -1,6 +1,6 @@ <%@ Page Language="C#" AutoEventWireup="True" CodeBehind="loginPlusOAuthSampleOP.aspx.cs" Inherits="OpenIdRelyingPartyWebForms.loginPlusOAuthSampleOP" ValidateRequest="false" - MasterPageFile="~/Site.Master" %> + MasterPageFile="~/Site.Master" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="rp" %> diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs index 75a9616..0446c36 100644 --- a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs @@ -1,6 +1,9 @@ namespace OpenIdRelyingPartyWebForms { using System; + using System.Web; using System.Web.Security; + using System.Web.UI; + using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; @@ -15,48 +18,58 @@ } protected void beginButton_Click(object sender, EventArgs e) { - if (!Page.IsValid) { - return; - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!Page.IsValid) { + return; + } - this.identifierBox.LogOn(); + await this.identifierBox.LogOnAsync(Response.ClientDisconnectedToken); + })); } protected void identifierBox_LoggingIn(object sender, OpenIdEventArgs e) { - ServiceProviderDescription serviceDescription = new ServiceProviderDescription { - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; - - var consumer = new WebConsumerOpenIdRelyingParty(serviceDescription, Global.OwnSampleOPHybridTokenManager); + var consumer = CreateConsumer(); consumer.AttachAuthorizationRequest(e.Request, "http://tempuri.org/IDataApi/GetName"); } protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e) { - State.FetchResponse = e.Response.GetExtension<FetchResponse>(); - - ServiceProviderDescription serviceDescription = new ServiceProviderDescription { - AccessTokenEndpoint = new MessageReceivingEndpoint(new Uri(e.Response.Provider.Uri, "/access_token.ashx"), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; - var consumer = new WebConsumerOpenIdRelyingParty(serviceDescription, Global.OwnSampleOPHybridTokenManager); - - AuthorizedTokenResponse accessToken = consumer.ProcessUserAuthorization(e.Response); - if (accessToken != null) { - this.MultiView1.SetActiveView(this.AuthorizationGiven); - - // At this point, the access token would be somehow associated with the user - // account at the RP. - ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken); - } else { - this.MultiView1.SetActiveView(this.AuthorizationDenied); - } - - // Avoid the redirect - e.Cancel = true; + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + State.FetchResponse = e.Response.GetExtension<FetchResponse>(); + + var serviceDescription = new ServiceProviderDescription { + TokenRequestEndpoint = new Uri(e.Response.Provider.Uri, "/access_token.ashx"), + }; + var consumer = CreateConsumer(); + consumer.ServiceProvider = serviceDescription; + AccessTokenResponse accessToken = await consumer.ProcessUserAuthorizationAsync(e.Response); + if (accessToken != null) { + this.MultiView1.SetActiveView(this.AuthorizationGiven); + + // At this point, the access token would be somehow associated with the user + // account at the RP. + ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken); + } else { + this.MultiView1.SetActiveView(this.AuthorizationDenied); + } + + // Avoid the redirect + e.Cancel = true; + })); } protected void identifierBox_Failed(object sender, OpenIdEventArgs e) { this.MultiView1.SetActiveView(this.AuthenticationFailed); } + + private static WebConsumerOpenIdRelyingParty CreateConsumer() { + var consumer = new WebConsumerOpenIdRelyingParty(); + consumer.ConsumerKey = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Request.ApplicationPath).AbsoluteUri; + consumer.ConsumerSecret = "some crazy secret"; + return consumer; + } } } diff --git a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx index a00eccd..3e8d631 100644 --- a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx +++ b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="loginProgrammatic.aspx.cs" +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="loginProgrammatic.aspx.cs" Async="true" Inherits="OpenIdRelyingPartyWebForms.loginProgrammatic" MasterPageFile="~/Site.Master" %> <asp:Content ID="Content1" runat="server" ContentPlaceHolderID="Main"> <h2>Login Page </h2> diff --git a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs index ed11148..f47eae0 100644 --- a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs @@ -1,6 +1,7 @@ namespace OpenIdRelyingPartyWebForms { using System; using System.Net; + using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; @@ -16,79 +17,91 @@ } protected void loginButton_Click(object sender, EventArgs e) { - if (!this.Page.IsValid) { - return; // don't login if custom validation failed. - } - try { - using (OpenIdRelyingParty openid = this.createRelyingParty()) { - IAuthenticationRequest request = openid.CreateRequest(this.openIdBox.Text); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!this.Page.IsValid) { + return; // don't login if custom validation failed. + } + try { + using (OpenIdRelyingParty openid = this.createRelyingParty()) { + IAuthenticationRequest request = + await + openid.CreateRequestAsync( + this.openIdBox.Text, new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); - // This is where you would add any OpenID extensions you wanted - // to include in the authentication request. - request.AddExtension(new ClaimsRequest { - Country = DemandLevel.Request, - Email = DemandLevel.Request, - Gender = DemandLevel.Require, - PostalCode = DemandLevel.Require, - TimeZone = DemandLevel.Require, - }); + // This is where you would add any OpenID extensions you wanted + // to include in the authentication request. + request.AddExtension( + new ClaimsRequest { + Country = DemandLevel.Request, + Email = DemandLevel.Request, + Gender = DemandLevel.Require, + PostalCode = DemandLevel.Require, + TimeZone = DemandLevel.Require, + }); - // Send your visitor to their Provider for authentication. - request.RedirectToProvider(); - } - } catch (ProtocolException ex) { - // The user probably entered an Identifier that - // was not a valid OpenID endpoint. - this.openidValidator.Text = ex.Message; - this.openidValidator.IsValid = false; - } + // Send your visitor to their Provider for authentication. + await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken); + } + } catch (ProtocolException ex) { + // The user probably entered an Identifier that + // was not a valid OpenID endpoint. + this.openidValidator.Text = ex.Message; + this.openidValidator.IsValid = false; + } + })); } protected void Page_Load(object sender, EventArgs e) { - this.openIdBox.Focus(); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + this.openIdBox.Focus(); - // For debugging/testing, we allow remote clearing of all associations... - // NOT a good idea on a production site. - if (Request.QueryString["clearAssociations"] == "1") { - Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore"); + // For debugging/testing, we allow remote clearing of all associations... + // NOT a good idea on a production site. + if (Request.QueryString["clearAssociations"] == "1") { + Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore"); - // Force a redirect now to prevent the user from logging in while associations - // are constantly being cleared. - UriBuilder builder = new UriBuilder(Request.Url); - builder.Query = null; - Response.Redirect(builder.Uri.AbsoluteUri); - } + // Force a redirect now to prevent the user from logging in while associations + // are constantly being cleared. + UriBuilder builder = new UriBuilder(Request.Url); + builder.Query = null; + Response.Redirect(builder.Uri.AbsoluteUri); + } - OpenIdRelyingParty openid = this.createRelyingParty(); - var response = openid.GetResponse(); - if (response != null) { - switch (response.Status) { - case AuthenticationStatus.Authenticated: - // This is where you would look for any OpenID extension responses included - // in the authentication assertion. - var claimsResponse = response.GetExtension<ClaimsResponse>(); - State.ProfileFields = claimsResponse; + OpenIdRelyingParty openid = this.createRelyingParty(); + var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (response != null) { + switch (response.Status) { + case AuthenticationStatus.Authenticated: + // This is where you would look for any OpenID extension responses included + // in the authentication assertion. + var claimsResponse = response.GetExtension<ClaimsResponse>(); + State.ProfileFields = claimsResponse; - // Store off the "friendly" username to display -- NOT for username lookup - State.FriendlyLoginName = response.FriendlyIdentifierForDisplay; + // Store off the "friendly" username to display -- NOT for username lookup + State.FriendlyLoginName = response.FriendlyIdentifierForDisplay; - // Use FormsAuthentication to tell ASP.NET that the user is now logged in, - // with the OpenID Claimed Identifier as their username. - FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false); - break; - case AuthenticationStatus.Canceled: - this.loginCanceledLabel.Visible = true; - break; - case AuthenticationStatus.Failed: - this.loginFailedLabel.Visible = true; - break; + // Use FormsAuthentication to tell ASP.NET that the user is now logged in, + // with the OpenID Claimed Identifier as their username. + FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false); + break; + case AuthenticationStatus.Canceled: + this.loginCanceledLabel.Visible = true; + break; + case AuthenticationStatus.Failed: + this.loginFailedLabel.Visible = true; + break; - // We don't need to handle SetupRequired because we're not setting - // IAuthenticationRequest.Mode to immediate mode. - ////case AuthenticationStatus.SetupRequired: - //// break; - } - } + // We don't need to handle SetupRequired because we're not setting + // IAuthenticationRequest.Mode to immediate mode. + ////case AuthenticationStatus.SetupRequired: + //// break; + } + } + })); } private OpenIdRelyingParty createRelyingParty() { diff --git a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.designer.cs b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.designer.cs index 088e305..d180211 100644 --- a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.designer.cs +++ b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.designer.cs @@ -1,10 +1,9 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ diff --git a/samples/OpenIdRelyingPartyWebForms/packages.config b/samples/OpenIdRelyingPartyWebForms/packages.config index 6562527..8e40260 100644 --- a/samples/OpenIdRelyingPartyWebForms/packages.config +++ b/samples/OpenIdRelyingPartyWebForms/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OpenIdRelyingPartyWebFormsVB/Global.asax.vb b/samples/OpenIdRelyingPartyWebFormsVB/Global.asax.vb index 257e11a..97b0d51 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/Global.asax.vb +++ b/samples/OpenIdRelyingPartyWebFormsVB/Global.asax.vb @@ -4,7 +4,6 @@ Imports System.Configuration Imports System.IO Imports System.Text Imports System.Web -Imports DotNetOpenAuth.ApplicationBlock Imports OpenIdRelyingPartyWebFormsVB Public Class Global_asax diff --git a/samples/OpenIdRelyingPartyWebFormsVB/Login.aspx b/samples/OpenIdRelyingPartyWebFormsVB/Login.aspx index c28611e..25538e8 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/Login.aspx +++ b/samples/OpenIdRelyingPartyWebFormsVB/Login.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Login.aspx.vb" Inherits="OpenIdRelyingPartyWebFormsVB.Login" +<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Login.aspx.vb" Inherits="OpenIdRelyingPartyWebFormsVB.Login" Async="true" ValidateRequest="false" MasterPageFile="~/Site.Master" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.RelyingParty.UI" Namespace="DotNetOpenAuth.OpenId.RelyingParty" TagPrefix="rp" %> diff --git a/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx b/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx index 7f1fa0e..becc9a0 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx +++ b/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="vb" AutoEventWireup="true" CodeBehind="loginProgrammatic.aspx.vb" +<%@ Page Language="vb" AutoEventWireup="true" CodeBehind="loginProgrammatic.aspx.vb" Async="true" Inherits="OpenIdRelyingPartyWebFormsVB.LoginProgrammatic" MasterPageFile="~/Site.Master" %> <asp:Content ID="Content1" runat="server" ContentPlaceHolderID="Main"> <h2>Login Page </h2> diff --git a/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.designer.vb b/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.designer.vb index 907fcda..e747a88 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.designer.vb +++ b/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.designer.vb @@ -1,10 +1,9 @@ '------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. -' Runtime Version:2.0.50727.4927 ' ' Changes to this file may cause incorrect behavior and will be lost if -' the code is regenerated. +' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ @@ -12,7 +11,6 @@ Option Strict On Option Explicit On - Partial Public Class LoginProgrammatic '''<summary> diff --git a/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.vb b/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.vb index 6cac182..b3c1620 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.vb +++ b/samples/OpenIdRelyingPartyWebFormsVB/LoginProgrammatic.aspx.vb @@ -1,4 +1,5 @@ Imports System.Net +Imports System.Threading Imports System.Web.Security Imports DotNetOpenAuth.Messaging Imports DotNetOpenAuth.OpenId @@ -15,13 +16,13 @@ Public Class LoginProgrammatic args.IsValid = Identifier.IsValid(args.Value) End Sub - Protected Sub loginButton_Click(ByVal sender As Object, ByVal e As EventArgs) + Protected Async Sub loginButton_Click(ByVal sender As Object, ByVal e As EventArgs) If Not Me.Page.IsValid Then Return ' don't login if custom validation failed. End If Try - Dim request As IAuthenticationRequest = relyingParty.CreateRequest(Me.openIdBox.Text) + Dim request As IAuthenticationRequest = Await relyingParty.CreateRequestAsync(Me.openIdBox.Text) ' This is where you would add any OpenID extensions you wanted ' to include in the authentication request. request.AddExtension(New ClaimsRequest() With { _ @@ -32,7 +33,7 @@ Public Class LoginProgrammatic .TimeZone = DemandLevel.Require _ }) ' Send your visitor to their Provider for authentication. - request.RedirectToProvider() + Await request.RedirectToProviderAsync() Catch ex As ProtocolException ' The user probably entered an Identifier that ' was not a valid OpenID endpoint. @@ -41,7 +42,7 @@ Public Class LoginProgrammatic End Try End Sub - Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load + Protected Async Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Me.openIdBox.Focus() ' For debugging/testing, we allow remote clearing of all associations... ' NOT a good idea on a production site. @@ -53,7 +54,7 @@ Public Class LoginProgrammatic builder.Query = Nothing Me.Response.Redirect(builder.Uri.AbsoluteUri) End If - Dim response As IAuthenticationResponse = relyingParty.GetResponse + Dim response As IAuthenticationResponse = Await relyingParty.GetResponseAsync(New HttpRequestWrapper(Request)) If response IsNot Nothing Then Select Case response.Status Case AuthenticationStatus.Authenticated diff --git a/samples/OpenIdRelyingPartyWebFormsVB/OpenIdRelyingPartyWebFormsVB.vbproj b/samples/OpenIdRelyingPartyWebFormsVB/OpenIdRelyingPartyWebFormsVB.vbproj index c044f4c..75d0490 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/OpenIdRelyingPartyWebFormsVB.vbproj +++ b/samples/OpenIdRelyingPartyWebFormsVB/OpenIdRelyingPartyWebFormsVB.vbproj @@ -64,6 +64,8 @@ <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Drawing" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web.ApplicationServices" /> <Reference Include="System.Web.DynamicData" /> <Reference Include="System.Web.Entity" /> @@ -216,10 +218,6 @@ <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project> <Name>DotNetOpenAuth.OpenId</Name> </ProjectReference> - <ProjectReference Include="..\DotNetOpenAuth.ApplicationBlock\DotNetOpenAuth.ApplicationBlock.csproj"> - <Project>{AA78D112-D889-414B-A7D4-467B34C7B663}</Project> - <Name>DotNetOpenAuth.ApplicationBlock</Name> - </ProjectReference> </ItemGroup> <ItemGroup> <Folder Include="App_Data\" /> diff --git a/samples/OpenIdRelyingPartyWebFormsVB/Web.config b/samples/OpenIdRelyingPartyWebFormsVB/Web.config index b849324..7f4fb2f 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/Web.config +++ b/samples/OpenIdRelyingPartyWebFormsVB/Web.config @@ -66,18 +66,16 @@ <!-- Google sign-up: https://www.google.com/accounts/ManageDomains --> <add key="googleConsumerKey" value="demo.dotnetopenauth.net"/> <add key="googleConsumerSecret" value="5Yv1TfKm1551QrXZ9GpqepeD"/> + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <system.web> + <httpRuntime targetFramework="4.5" /> <!--<sessionState cookieless="true" />--> - <compilation debug="true" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <compilation debug="true" targetFramework="4.5" /> <customErrors mode="RemoteOnly"/> <authentication mode="Forms"> - <forms name="OpenIdRelyingPartyVBSession"/> <!-- named cookie prevents conflicts with other samples --> + <forms name="OpenIdRelyingPartyVBSession" loginUrl="loginProgrammatic.aspx"/> <!-- named cookie prevents conflicts with other samples --> </authentication> <trace enabled="false" writeToDiagnosticsTrace="true" /> <!-- Trust level discussion: diff --git a/samples/OpenIdRelyingPartyWebFormsVB/packages.config b/samples/OpenIdRelyingPartyWebFormsVB/packages.config index 6562527..8e40260 100644 --- a/samples/OpenIdRelyingPartyWebFormsVB/packages.config +++ b/samples/OpenIdRelyingPartyWebFormsVB/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/samples/OpenIdWebRingSsoProvider/Code/Util.cs b/samples/OpenIdWebRingSsoProvider/Code/Util.cs index 5599b73..13ecf41 100644 --- a/samples/OpenIdWebRingSsoProvider/Code/Util.cs +++ b/samples/OpenIdWebRingSsoProvider/Code/Util.cs @@ -7,6 +7,8 @@ namespace OpenIdWebRingSsoProvider.Code { using System; using System.Configuration; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; @@ -50,9 +52,10 @@ namespace OpenIdWebRingSsoProvider.Code { return new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Response.ApplyAppPathModifier("~/user.aspx/" + username)); } - internal static void ProcessAuthenticationChallenge(IAuthenticationRequest idrequest) { + internal static async Task ProcessAuthenticationChallengeAsync(IAuthenticationRequest idrequest, CancellationToken cancellationToken) { // Verify that RP discovery is successful. - if (idrequest.IsReturnUrlDiscoverable(ProviderEndpoint.Provider.Channel.WebRequestHandler) != RelyingPartyDiscoveryResult.Success) { + var providerEndpoint = new ProviderEndpoint(); + if (await idrequest.IsReturnUrlDiscoverableAsync(providerEndpoint.Provider.Channel.HostFactories, cancellationToken) != RelyingPartyDiscoveryResult.Success) { idrequest.IsAuthenticated = false; return; } diff --git a/samples/OpenIdWebRingSsoProvider/Default.aspx b/samples/OpenIdWebRingSsoProvider/Default.aspx index 5e392c5..d3c4e05 100644 --- a/samples/OpenIdWebRingSsoProvider/Default.aspx +++ b/samples/OpenIdWebRingSsoProvider/Default.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="OpenIdWebRingSsoProvider._Default" %> +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="OpenIdWebRingSsoProvider._Default" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.UI" Namespace="DotNetOpenAuth" TagPrefix="openid" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> diff --git a/samples/OpenIdWebRingSsoProvider/Default.aspx.cs b/samples/OpenIdWebRingSsoProvider/Default.aspx.cs index d7e5310..6a930bd 100644 --- a/samples/OpenIdWebRingSsoProvider/Default.aspx.cs +++ b/samples/OpenIdWebRingSsoProvider/Default.aspx.cs @@ -5,18 +5,28 @@ using System.Web; using System.Web.UI; using System.Web.UI.WebControls; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Provider; using OpenIdWebRingSsoProvider.Code; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { - // The user may have just completed a login. If they're logged in, see if we can complete the OpenID login. - if (User.Identity.IsAuthenticated && ProviderEndpoint.PendingAuthenticationRequest != null) { - Util.ProcessAuthenticationChallenge(ProviderEndpoint.PendingAuthenticationRequest); - if (ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated.HasValue) { - ProviderEndpoint.SendResponse(); - } - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + // The user may have just completed a login. If they're logged in, see if we can complete the OpenID login. + if (User.Identity.IsAuthenticated && ProviderEndpoint.PendingAuthenticationRequest != null) { + await + Util.ProcessAuthenticationChallengeAsync( + ProviderEndpoint.PendingAuthenticationRequest, Response.ClientDisconnectedToken); + if (ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated.HasValue) { + var providerEndpoint = new ProviderEndpoint(); + var responseMessage = await providerEndpoint.PrepareResponseAsync(this.Response.ClientDisconnectedToken); + await responseMessage.SendAsync(new HttpContextWrapper(this.Context), this.Response.ClientDisconnectedToken); + this.Context.Response.End(); + } + } + })); } } } diff --git a/samples/OpenIdWebRingSsoProvider/Login.aspx b/samples/OpenIdWebRingSsoProvider/Login.aspx index 336b8ad..3c0b4e6 100644 --- a/samples/OpenIdWebRingSsoProvider/Login.aspx +++ b/samples/OpenIdWebRingSsoProvider/Login.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="OpenIdWebRingSsoProvider.Login" %> +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="OpenIdWebRingSsoProvider.Login" Async="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> diff --git a/samples/OpenIdWebRingSsoProvider/Login.aspx.cs b/samples/OpenIdWebRingSsoProvider/Login.aspx.cs index 584cff7..10e5aad 100644 --- a/samples/OpenIdWebRingSsoProvider/Login.aspx.cs +++ b/samples/OpenIdWebRingSsoProvider/Login.aspx.cs @@ -5,6 +5,7 @@ using System.Web; using System.Web.UI; using System.Web.UI.WebControls; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Provider; using OpenIdWebRingSsoProvider.Code; @@ -35,11 +36,18 @@ } protected void cancelButton_Click(object sender, EventArgs e) { - var req = ProviderEndpoint.PendingAuthenticationRequest; - if (req != null) { - req.IsAuthenticated = false; - ProviderEndpoint.SendResponse(); - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var req = ProviderEndpoint.PendingAuthenticationRequest; + if (req != null) { + req.IsAuthenticated = false; + var providerEndpoint = new ProviderEndpoint(); + var response = await providerEndpoint.PrepareResponseAsync(Response.ClientDisconnectedToken); + await response.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); + this.Context.Response.End(); + } + })); } } }
\ No newline at end of file diff --git a/samples/OpenIdWebRingSsoProvider/OpenIdWebRingSsoProvider.csproj b/samples/OpenIdWebRingSsoProvider/OpenIdWebRingSsoProvider.csproj index 69c73ed..25ab7ac 100644 --- a/samples/OpenIdWebRingSsoProvider/OpenIdWebRingSsoProvider.csproj +++ b/samples/OpenIdWebRingSsoProvider/OpenIdWebRingSsoProvider.csproj @@ -9,6 +9,7 @@ <IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication> <IISExpressWindowsAuthentication>disabled</IISExpressWindowsAuthentication> <IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\src\</SolutionDir> </PropertyGroup> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> @@ -52,6 +53,8 @@ <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web.DynamicData" /> <Reference Include="System.Web.Entity" /> <Reference Include="System.Drawing" /> @@ -136,6 +139,9 @@ <Name>DotNetOpenAuth.OpenId</Name> </ProjectReference> </ItemGroup> + <ItemGroup> + <Content Include="packages.config" /> + </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /> @@ -165,4 +171,5 @@ </VisualStudio> </ProjectExtensions> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " /> + <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> </Project>
\ No newline at end of file diff --git a/samples/OpenIdWebRingSsoProvider/Server.aspx b/samples/OpenIdWebRingSsoProvider/Server.aspx index 31373be..b0c0bdd 100644 --- a/samples/OpenIdWebRingSsoProvider/Server.aspx +++ b/samples/OpenIdWebRingSsoProvider/Server.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Server.aspx.cs" Inherits="OpenIdWebRingSsoProvider.Server" ValidateRequest="false" %> +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Server.aspx.cs" Inherits="OpenIdWebRingSsoProvider.Server" ValidateRequest="false" Async="true" %> <%@ Register Assembly="DotNetOpenAuth.OpenId.Provider.UI" Namespace="DotNetOpenAuth.OpenId.Provider" TagPrefix="openid" %> diff --git a/samples/OpenIdWebRingSsoProvider/Server.aspx.cs b/samples/OpenIdWebRingSsoProvider/Server.aspx.cs index 101e608..805e38f 100644 --- a/samples/OpenIdWebRingSsoProvider/Server.aspx.cs +++ b/samples/OpenIdWebRingSsoProvider/Server.aspx.cs @@ -13,7 +13,11 @@ } protected void providerEndpoint1_AuthenticationChallenge(object sender, AuthenticationChallengeEventArgs e) { - Util.ProcessAuthenticationChallenge(e.Request); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + await Util.ProcessAuthenticationChallengeAsync(e.Request, ct); + })); } } } diff --git a/samples/OpenIdWebRingSsoProvider/Web.config b/samples/OpenIdWebRingSsoProvider/Web.config index 3304e97..901ba5f 100644 --- a/samples/OpenIdWebRingSsoProvider/Web.config +++ b/samples/OpenIdWebRingSsoProvider/Web.config @@ -57,21 +57,20 @@ <add key="whitelistedRealms" value="http://localhost:39165/;http://othertrustedrealm/"/> <!-- Set ImplicitAuth to true when using Windows auth, or false for FormsAuthentication --> <add key="ImplicitAuth" value="true"/> + + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <connectionStrings/> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> - <compilation debug="false" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <compilation debug="false" targetFramework="4.0" /> <!-- this sample-only provider uses the hard-coded list of users in the App_Data\Users.xml file --> <membership defaultProvider="AspNetReadOnlyXmlMembershipProvider"> <providers> diff --git a/samples/OpenIdWebRingSsoProvider/packages.config b/samples/OpenIdWebRingSsoProvider/packages.config new file mode 100644 index 0000000..d8ffcb7 --- /dev/null +++ b/samples/OpenIdWebRingSsoProvider/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx index 2e7df2e..e16cf79 100644 --- a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx +++ b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="OpenIdWebRingSsoRelyingParty.Login" %> +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="OpenIdWebRingSsoRelyingParty.Login" Async="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> diff --git a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs index 7f7f91e..d1b1413 100644 --- a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs +++ b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs @@ -22,71 +22,77 @@ } protected void Page_Load(object sender, EventArgs e) { - UriBuilder returnToBuilder = new UriBuilder(Request.Url); - returnToBuilder.Path = "/login.aspx"; - returnToBuilder.Query = null; - returnToBuilder.Fragment = null; - Uri returnTo = returnToBuilder.Uri; - returnToBuilder.Path = "/"; - Realm realm = returnToBuilder.Uri; + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + UriBuilder returnToBuilder = new UriBuilder(Request.Url); + returnToBuilder.Path = "/login.aspx"; + returnToBuilder.Query = null; + returnToBuilder.Fragment = null; + Uri returnTo = returnToBuilder.Uri; + returnToBuilder.Path = "/"; + Realm realm = returnToBuilder.Uri; - var response = relyingParty.GetResponse(); - if (response == null) { - if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated) { - // The user must have been directed here because he has insufficient - // permissions to access something. - this.MultiView1.ActiveViewIndex = 1; - } else { - // Because this is a sample of a controlled SSO environment, - // we don't ask the user which Provider to use... we just send - // them straight off to the one Provider we trust. - var request = relyingParty.CreateRequest( - ConfigurationManager.AppSettings["SsoProviderOPIdentifier"], - realm, - returnTo); - var fetchRequest = new FetchRequest(); - fetchRequest.Attributes.AddOptional(RolesAttribute); - request.AddExtension(fetchRequest); - request.RedirectToProvider(); - } - } else { - switch (response.Status) { - case AuthenticationStatus.Canceled: - this.errorLabel.Text = "Login canceled."; - break; - case AuthenticationStatus.Failed: - this.errorLabel.Text = HttpUtility.HtmlEncode(response.Exception.Message); - break; - case AuthenticationStatus.Authenticated: - IList<string> roles = null; - var fetchResponse = response.GetExtension<FetchResponse>(); - if (fetchResponse != null) { - if (fetchResponse.Attributes.Contains(RolesAttribute)) { - roles = fetchResponse.Attributes[RolesAttribute].Values; + var response = + await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (response == null) { + if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated) { + // The user must have been directed here because he has insufficient + // permissions to access something. + this.MultiView1.ActiveViewIndex = 1; + } else { + // Because this is a sample of a controlled SSO environment, + // we don't ask the user which Provider to use... we just send + // them straight off to the one Provider we trust. + var request = + await + relyingParty.CreateRequestAsync( + ConfigurationManager.AppSettings["SsoProviderOPIdentifier"], realm, returnTo, Response.ClientDisconnectedToken); + var fetchRequest = new FetchRequest(); + fetchRequest.Attributes.AddOptional(RolesAttribute); + request.AddExtension(fetchRequest); + await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken); } - } - if (roles == null) { - roles = new List<string>(0); - } + } else { + switch (response.Status) { + case AuthenticationStatus.Canceled: + this.errorLabel.Text = "Login canceled."; + break; + case AuthenticationStatus.Failed: + this.errorLabel.Text = HttpUtility.HtmlEncode(response.Exception.Message); + break; + case AuthenticationStatus.Authenticated: + IList<string> roles = null; + var fetchResponse = response.GetExtension<FetchResponse>(); + if (fetchResponse != null) { + if (fetchResponse.Attributes.Contains(RolesAttribute)) { + roles = fetchResponse.Attributes[RolesAttribute].Values; + } + } + if (roles == null) { + roles = new List<string>(0); + } - // Apply the roles to this auth ticket - const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file - var ticket = new FormsAuthenticationTicket( - 2, - response.ClaimedIdentifier, - DateTime.Now, - DateTime.Now.AddMinutes(TimeoutInMinutes), - false, // non-persistent, since login is automatic and we wanted updated roles - string.Join(";", roles.ToArray())); + // Apply the roles to this auth ticket + const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file + var ticket = new FormsAuthenticationTicket( + 2, + response.ClaimedIdentifier, + DateTime.Now, + DateTime.Now.AddMinutes(TimeoutInMinutes), + false, + // non-persistent, since login is automatic and we wanted updated roles + string.Join(";", roles.ToArray())); - HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); - Response.SetCookie(cookie); - Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl); - break; - default: - break; - } - } + HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); + Response.SetCookie(cookie); + Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl); + break; + default: + break; + } + } + })); } protected void retryButton_Click(object sender, EventArgs e) { diff --git a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.designer.cs b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.designer.cs index 7ed2669..3e6bbf2 100644 --- a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.designer.cs +++ b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.designer.cs @@ -1,10 +1,9 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. +// the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ diff --git a/samples/OpenIdWebRingSsoRelyingParty/OpenIdWebRingSsoRelyingParty.csproj b/samples/OpenIdWebRingSsoRelyingParty/OpenIdWebRingSsoRelyingParty.csproj index cd027b2..9eaeb65 100644 --- a/samples/OpenIdWebRingSsoRelyingParty/OpenIdWebRingSsoRelyingParty.csproj +++ b/samples/OpenIdWebRingSsoRelyingParty/OpenIdWebRingSsoRelyingParty.csproj @@ -9,6 +9,7 @@ <IISExpressAnonymousAuthentication /> <IISExpressWindowsAuthentication /> <IISExpressUseClassicPipelineMode /> + <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\src\</SolutionDir> </PropertyGroup> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> @@ -53,6 +54,8 @@ <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Drawing" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Web" /> <Reference Include="System.Web.ApplicationServices" /> <Reference Include="System.Web.DynamicData" /> @@ -74,18 +77,21 @@ <ItemGroup> <Compile Include="Admin\Default.aspx.cs"> <DependentUpon>Default.aspx</DependentUpon> + <SubType>ASPXCodeBehind</SubType> </Compile> <Compile Include="Admin\Default.aspx.designer.cs"> <DependentUpon>Default.aspx</DependentUpon> </Compile> <Compile Include="Default.aspx.cs"> <DependentUpon>Default.aspx</DependentUpon> + <SubType>ASPXCodeBehind</SubType> </Compile> <Compile Include="Default.aspx.designer.cs"> <DependentUpon>Default.aspx</DependentUpon> </Compile> <Compile Include="Login.aspx.cs"> <DependentUpon>Login.aspx</DependentUpon> + <SubType>ASPXCodeBehind</SubType> </Compile> <Compile Include="Login.aspx.designer.cs"> <DependentUpon>Login.aspx</DependentUpon> @@ -118,6 +124,9 @@ <Name>DotNetOpenAuth.OpenId</Name> </ProjectReference> </ItemGroup> + <ItemGroup> + <Content Include="packages.config" /> + </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /> @@ -147,4 +156,5 @@ </VisualStudio> </ProjectExtensions> <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " /> + <Import Project="$(SolutionDir)\.nuget\nuget.targets" /> </Project>
\ No newline at end of file diff --git a/samples/OpenIdWebRingSsoRelyingParty/Web.config b/samples/OpenIdWebRingSsoRelyingParty/Web.config index b64f037..6b645c5 100644 --- a/samples/OpenIdWebRingSsoRelyingParty/Web.config +++ b/samples/OpenIdWebRingSsoRelyingParty/Web.config @@ -64,22 +64,20 @@ <appSettings> <add key="SsoProviderOPIdentifier" value="http://localhost:39167/" /> <add key="SsoProviderOPEndpoint" value="http://localhost:39167/server.aspx" /> + + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <connectionStrings/> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> - <compilation debug="false" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - - </compilation> + <compilation debug="false" targetFramework="4.0" /> <!-- The <authentication> section enables configuration of the security authentication mode used by diff --git a/samples/OpenIdWebRingSsoRelyingParty/packages.config b/samples/OpenIdWebRingSsoRelyingParty/packages.config new file mode 100644 index 0000000..d8ffcb7 --- /dev/null +++ b/samples/OpenIdWebRingSsoRelyingParty/packages.config @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.AspNet.Test/DotNetOpenAuth.AspNet.Test.csproj b/src/DotNetOpenAuth.AspNet.Test/DotNetOpenAuth.AspNet.Test.csproj index 00da7c5..e640992 100644 --- a/src/DotNetOpenAuth.AspNet.Test/DotNetOpenAuth.AspNet.Test.csproj +++ b/src/DotNetOpenAuth.AspNet.Test/DotNetOpenAuth.AspNet.Test.csproj @@ -65,6 +65,14 @@ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project> <Name>DotNetOpenAuth.Core</Name> </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OAuth.Common\DotNetOpenAuth.OAuth.Common.csproj"> + <Project>{115217c5-22cd-415c-a292-0dd0238cdd89}</Project> + <Name>DotNetOpenAuth.OAuth.Common</Name> + </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OAuth.Consumer\DotNetOpenAuth.OAuth.Consumer.csproj"> + <Project>{b202e40d-4663-4a2b-acda-865f88ff7caa}</Project> + <Name>DotNetOpenAuth.OAuth.Consumer</Name> + </ProjectReference> <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj"> <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project> <Name>DotNetOpenAuth.OAuth</Name> diff --git a/src/DotNetOpenAuth.AspNet.Test/OAuth2ClientTest.cs b/src/DotNetOpenAuth.AspNet.Test/OAuth2ClientTest.cs index e60df01..ad5a69d 100644 --- a/src/DotNetOpenAuth.AspNet.Test/OAuth2ClientTest.cs +++ b/src/DotNetOpenAuth.AspNet.Test/OAuth2ClientTest.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.AspNet.Test { using DotNetOpenAuth.AspNet.Clients; using Moq; using NUnit.Framework; + using System.Threading.Tasks; [TestFixture] public class OAuth2ClientTest { @@ -28,14 +29,14 @@ namespace DotNetOpenAuth.AspNet.Test { } [TestCase] - public void RequestAuthenticationIssueCorrectRedirect() { + public async Task RequestAuthenticationIssueCorrectRedirect() { // Arrange var client = new MockOAuth2Client(); var context = new Mock<HttpContextBase>(MockBehavior.Strict); context.Setup(c => c.Response.Redirect("http://live.com/?q=http://return.to.me/", true)).Verifiable(); // Act - client.RequestAuthentication(context.Object, new Uri("http://return.to.me")); + await client.RequestAuthenticationAsync(context.Object, new Uri("http://return.to.me")); // Assert context.Verify(); @@ -47,7 +48,7 @@ namespace DotNetOpenAuth.AspNet.Test { var client = new MockOAuth2Client(); // Act && Assert - Assert.Throws<ArgumentNullException>(() => client.VerifyAuthentication(null, new Uri("http://me.com"))); + Assert.Throws<ArgumentNullException>(() => client.VerifyAuthenticationAsync(null, new Uri("http://me.com")).GetAwaiter().GetResult()); } [TestCase] @@ -56,11 +57,11 @@ namespace DotNetOpenAuth.AspNet.Test { var client = new MockOAuth2Client(); // Act && Assert - Assert.Throws<InvalidOperationException>(() => client.VerifyAuthentication(new Mock<HttpContextBase>().Object)); + Assert.Throws<InvalidOperationException>(() => client.VerifyAuthenticationAsync(new Mock<HttpContextBase>().Object).GetAwaiter().GetResult()); } [TestCase] - public void VerifyAuthenticationFailsIfCodeIsNotPresent() { + public async Task VerifyAuthenticationFailsIfCodeIsNotPresent() { // Arrange var client = new MockOAuth2Client(); var context = new Mock<HttpContextBase>(MockBehavior.Strict); @@ -68,14 +69,14 @@ namespace DotNetOpenAuth.AspNet.Test { context.Setup(c => c.Request.QueryString).Returns(queryStrings); // Act - AuthenticationResult result = client.VerifyAuthentication(context.Object, new Uri("http://me.com")); + AuthenticationResult result = await client.VerifyAuthenticationAsync(context.Object, new Uri("http://me.com")); // Assert Assert.IsFalse(result.IsSuccessful); } [TestCase] - public void VerifyAuthenticationFailsIfAccessTokenIsNull() { + public async Task VerifyAuthenticationFailsIfAccessTokenIsNull() { // Arrange var client = new MockOAuth2Client(); var context = new Mock<HttpContextBase>(MockBehavior.Strict); @@ -84,14 +85,14 @@ namespace DotNetOpenAuth.AspNet.Test { context.Setup(c => c.Request.QueryString).Returns(queryStrings); // Act - AuthenticationResult result = client.VerifyAuthentication(context.Object, new Uri("http://me.com")); + AuthenticationResult result = await client.VerifyAuthenticationAsync(context.Object, new Uri("http://me.com")); // Assert Assert.IsFalse(result.IsSuccessful); } [TestCase] - public void VerifyAuthenticationSucceeds() { + public async Task VerifyAuthenticationSucceeds() { // Arrange var client = new MockOAuth2Client(); var context = new Mock<HttpContextBase>(MockBehavior.Strict); @@ -100,7 +101,7 @@ namespace DotNetOpenAuth.AspNet.Test { context.Setup(c => c.Request.QueryString).Returns(queryStrings); // Act - AuthenticationResult result = client.VerifyAuthentication(context.Object, new Uri("http://me.com")); + AuthenticationResult result = await client.VerifyAuthenticationAsync(context.Object, new Uri("http://me.com")); // Assert Assert.True(result.IsSuccessful); @@ -125,9 +126,9 @@ namespace DotNetOpenAuth.AspNet.Test { return (authorizationCode == "secret") ? "abcde" : null; } - protected override IDictionary<string, string> GetUserData(string accessToken) { + protected override NameValueCollection GetUserData(string accessToken) { if (accessToken == "abcde") { - return new Dictionary<string, string> + return new NameValueCollection { { "id", "12345" }, { "name", "John Doe" }, diff --git a/src/DotNetOpenAuth.AspNet.Test/OAuthClientTest.cs b/src/DotNetOpenAuth.AspNet.Test/OAuthClientTest.cs index 3b72b9e..25dd50b 100644 --- a/src/DotNetOpenAuth.AspNet.Test/OAuthClientTest.cs +++ b/src/DotNetOpenAuth.AspNet.Test/OAuthClientTest.cs @@ -6,6 +6,7 @@ namespace DotNetOpenAuth.AspNet.Test { using System; + using System.Collections.Specialized; using System.Web; using DotNetOpenAuth.AspNet; using DotNetOpenAuth.AspNet.Clients; @@ -13,6 +14,9 @@ namespace DotNetOpenAuth.AspNet.Test { using DotNetOpenAuth.OAuth.Messages; using Moq; using NUnit.Framework; + using DotNetOpenAuth.OAuth; + using System.Threading; + using System.Threading.Tasks; [TestFixture] public class OAuthClientTest { @@ -29,57 +33,55 @@ namespace DotNetOpenAuth.AspNet.Test { } [TestCase] - public void RequestAuthenticationInvokeMethodOnWebWorker() { + public async Task RequestAuthenticationInvokeMethodOnWebWorker() { // Arrange + var returnUri = new Uri("http://live.com/my/path.cshtml?q=one"); var webWorker = new Mock<IOAuthWebWorker>(MockBehavior.Strict); webWorker - .Setup(w => w.RequestAuthentication(It.Is<Uri>(u => u.ToString().Equals("http://live.com/my/path.cshtml?q=one")))) + .Setup(w => w.RequestAuthenticationAsync(returnUri, It.IsAny<CancellationToken>())) + .Returns(Task.FromResult(new Uri("http://someauth/uri"))) .Verifiable(); var client = new MockOAuthClient(webWorker.Object); - var returnUri = new Uri("http://live.com/my/path.cshtml?q=one"); var context = new Mock<HttpContextBase>(); // Act - client.RequestAuthentication(context.Object, returnUri); + await client.RequestAuthenticationAsync(context.Object, returnUri); // Assert webWorker.Verify(); } [TestCase] - public void VerifyAuthenticationFailsIfResponseTokenIsNull() { + public async Task VerifyAuthenticationFailsIfResponseTokenIsNull() { // Arrange var webWorker = new Mock<IOAuthWebWorker>(MockBehavior.Strict); - webWorker.Setup(w => w.ProcessUserAuthorization()).Returns((AuthorizedTokenResponse)null); + webWorker.Setup(w => w.ProcessUserAuthorizationAsync(It.IsAny<HttpContextBase>(), CancellationToken.None)).Returns(Task.FromResult<AccessTokenResponse>(null)); var client = new MockOAuthClient(webWorker.Object); var context = new Mock<HttpContextBase>(); // Act - client.VerifyAuthentication(context.Object); + await client.VerifyAuthenticationAsync(context.Object); // Assert webWorker.Verify(); } [TestCase] - public void VerifyAuthenticationFailsIfAccessTokenIsInvalid() { + public async Task VerifyAuthenticationFailsIfAccessTokenIsInvalid() { // Arrange var endpoint = new MessageReceivingEndpoint("http://live.com/path/?a=b", HttpDeliveryMethods.GetRequest); var request = new AuthorizedTokenRequest(endpoint, new Version("1.0")); - var response = new AuthorizedTokenResponse(request) { - AccessToken = "invalid token" - }; var webWorker = new Mock<IOAuthWebWorker>(MockBehavior.Strict); - webWorker.Setup(w => w.ProcessUserAuthorization()).Returns(response).Verifiable(); + webWorker.Setup(w => w.ProcessUserAuthorizationAsync(It.IsAny<HttpContextBase>(), CancellationToken.None)).Returns(Task.FromResult<AccessTokenResponse>(null)).Verifiable(); var client = new MockOAuthClient(webWorker.Object); var context = new Mock<HttpContextBase>(); // Act - AuthenticationResult result = client.VerifyAuthentication(context.Object); + AuthenticationResult result = await client.VerifyAuthenticationAsync(context.Object); // Assert webWorker.Verify(); @@ -88,22 +90,21 @@ namespace DotNetOpenAuth.AspNet.Test { } [TestCase] - public void VerifyAuthenticationSucceeds() { + public async Task VerifyAuthenticationSucceeds() { // Arrange var endpoint = new MessageReceivingEndpoint("http://live.com/path/?a=b", HttpDeliveryMethods.GetRequest); var request = new AuthorizedTokenRequest(endpoint, new Version("1.0")); - var response = new AuthorizedTokenResponse(request) { - AccessToken = "ok" - }; var webWorker = new Mock<IOAuthWebWorker>(MockBehavior.Strict); - webWorker.Setup(w => w.ProcessUserAuthorization()).Returns(response).Verifiable(); + webWorker + .Setup(w => w.ProcessUserAuthorizationAsync(It.IsAny<HttpContextBase>(), CancellationToken.None)) + .Returns(Task.FromResult(new AccessTokenResponse("ok", "secret", new NameValueCollection()))).Verifiable(); var client = new MockOAuthClient(webWorker.Object); var context = new Mock<HttpContextBase>(); // Act - AuthenticationResult result = client.VerifyAuthentication(context.Object); + AuthenticationResult result = await client.VerifyAuthenticationAsync(context.Object); // Assert webWorker.Verify(); @@ -113,7 +114,6 @@ namespace DotNetOpenAuth.AspNet.Test { Assert.AreEqual("12345", result.ProviderUserId); Assert.AreEqual("super", result.UserName); Assert.IsNotNull(result.ExtraData); - Assert.IsTrue(result.ExtraData.ContainsKey("accesstoken")); Assert.AreEqual("ok", result.ExtraData["accesstoken"]); } @@ -133,12 +133,12 @@ namespace DotNetOpenAuth.AspNet.Test { : base("mockoauth", worker) { } - protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { - if (response.AccessToken == "ok") { - return new AuthenticationResult(true, "mockoauth", "12345", "super", response.ExtraData); + protected override Task<AuthenticationResult> VerifyAuthenticationCoreAsync(AccessTokenResponse response, CancellationToken cancellationToken) { + if (response.AccessToken.Token == "ok") { + return Task.FromResult(new AuthenticationResult(true, "mockoauth", "12345", "super", response.ExtraData)); } - return AuthenticationResult.Failed; + return Task.FromResult(AuthenticationResult.Failed); } } } diff --git a/src/DotNetOpenAuth.AspNet/AuthenticationResult.cs b/src/DotNetOpenAuth.AspNet/AuthenticationResult.cs index 9e8492d..4493288 100644 --- a/src/DotNetOpenAuth.AspNet/AuthenticationResult.cs +++ b/src/DotNetOpenAuth.AspNet/AuthenticationResult.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.AspNet { using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using DotNetOpenAuth.Messaging; + using System.Collections.Specialized; /// <summary> /// Represents the result of OAuth or OpenID authentication. @@ -46,10 +47,8 @@ namespace DotNetOpenAuth.AspNet { /// <param name="exception">The exception.</param> /// <param name="provider">The provider name.</param> public AuthenticationResult(Exception exception, string provider) - : this(isSuccessful: false) - { - if (exception == null) - { + : this(isSuccessful: false) { + if (exception == null) { throw new ArgumentNullException("exception"); } @@ -76,15 +75,12 @@ namespace DotNetOpenAuth.AspNet { /// The extra data. /// </param> public AuthenticationResult( - bool isSuccessful, string provider, string providerUserId, string userName, IDictionary<string, string> extraData) { + bool isSuccessful, string provider, string providerUserId, string userName, NameValueCollection extraData) { this.IsSuccessful = isSuccessful; this.Provider = provider; this.ProviderUserId = providerUserId; this.UserName = userName; - if (extraData != null) { - // wrap extraData in a read-only dictionary - this.ExtraData = new ReadOnlyDictionary<string, string>(extraData); - } + this.ExtraData = extraData ?? new NameValueCollection(); } /// <summary> @@ -95,7 +91,7 @@ namespace DotNetOpenAuth.AspNet { /// <summary> /// Gets the optional extra data that may be returned from the provider /// </summary> - public IDictionary<string, string> ExtraData { get; private set; } + public NameValueCollection ExtraData { get; private set; } /// <summary> /// Gets a value indicating whether the authentication step is successful. diff --git a/src/DotNetOpenAuth.AspNet/Clients/DictionaryExtensions.cs b/src/DotNetOpenAuth.AspNet/Clients/DictionaryExtensions.cs index f441c07..a84fdcf 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/DictionaryExtensions.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/DictionaryExtensions.cs @@ -7,6 +7,7 @@ namespace DotNetOpenAuth.AspNet.Clients { using System; using System.Collections.Generic; + using System.Collections.Specialized; using System.Xml.Linq; /// <summary> @@ -25,8 +26,8 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <param name="elementName"> /// Name of the element. /// </param> - public static void AddDataIfNotEmpty( - this Dictionary<string, string> dictionary, XDocument document, string elementName) { + internal static void AddDataIfNotEmpty( + this NameValueCollection dictionary, XDocument document, string elementName) { var element = document.Root.Element(elementName); if (element != null) { dictionary.AddItemIfNotEmpty(elementName, element.Value); @@ -45,7 +46,7 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <param name="value"> /// The value. /// </param> - public static void AddItemIfNotEmpty(this IDictionary<string, string> dictionary, string key, string value) { + internal static void AddItemIfNotEmpty(this NameValueCollection dictionary, string key, string value) { if (key == null) { throw new ArgumentNullException("key"); } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/AuthenticationOnlyCookieOAuthTokenManager.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/AuthenticationOnlyCookieOAuthTokenManager.cs deleted file mode 100644 index efc382f..0000000 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/AuthenticationOnlyCookieOAuthTokenManager.cs +++ /dev/null @@ -1,127 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="AuthenticationOnlyCookieOAuthTokenManager.cs" company="Microsoft"> -// Copyright (c) Microsoft. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.AspNet.Clients { - using System; - using System.Text; - using System.Web; - using System.Web.Security; - - /// <summary> - /// Stores OAuth tokens in the current request's cookie - /// </summary> - public class AuthenticationOnlyCookieOAuthTokenManager : IOAuthTokenManager { - /// <summary> - /// Key used for token cookie - /// </summary> - protected const string TokenCookieKey = "OAuthTokenSecret"; - - /// <summary> - /// Primary request context. - /// </summary> - private readonly HttpContextBase primaryContext; - - /// <summary> - /// Initializes a new instance of the <see cref="AuthenticationOnlyCookieOAuthTokenManager"/> class. - /// </summary> - public AuthenticationOnlyCookieOAuthTokenManager() { - } - - /// <summary> - /// Initializes a new instance of the <see cref="AuthenticationOnlyCookieOAuthTokenManager"/> class. - /// </summary> - /// <param name="context">The current request context.</param> - public AuthenticationOnlyCookieOAuthTokenManager(HttpContextBase context) { - this.primaryContext = context; - } - - /// <summary> - /// Gets the effective HttpContext object to use. - /// </summary> - protected HttpContextBase Context { - get { - return this.primaryContext ?? new HttpContextWrapper(HttpContext.Current); - } - } - - /// <summary> - /// Gets the token secret from the specified token. - /// </summary> - /// <param name="token">The token.</param> - /// <returns> - /// The token's secret - /// </returns> - public virtual string GetTokenSecret(string token) { - HttpCookie cookie = this.Context.Request.Cookies[TokenCookieKey]; - if (cookie == null || string.IsNullOrEmpty(cookie.Values[token])) { - return null; - } - - string secret = DecodeAndUnprotectToken(token, cookie.Values[token]); - return secret; - } - - /// <summary> - /// Replaces the request token with access token. - /// </summary> - /// <param name="requestToken">The request token.</param> - /// <param name="accessToken">The access token.</param> - /// <param name="accessTokenSecret">The access token secret.</param> - public virtual void ReplaceRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret) { - var cookie = new HttpCookie(TokenCookieKey) { - Value = string.Empty, - Expires = DateTime.UtcNow.AddDays(-5) - }; - this.Context.Response.Cookies.Set(cookie); - } - - /// <summary> - /// Stores the request token together with its secret. - /// </summary> - /// <param name="requestToken">The request token.</param> - /// <param name="requestTokenSecret">The request token secret.</param> - public virtual void StoreRequestToken(string requestToken, string requestTokenSecret) { - var cookie = new HttpCookie(TokenCookieKey) { - HttpOnly = true - }; - - if (FormsAuthentication.RequireSSL) { - cookie.Secure = true; - } - - var encryptedToken = ProtectAndEncodeToken(requestToken, requestTokenSecret); - cookie.Values[requestToken] = encryptedToken; - - this.Context.Response.Cookies.Set(cookie); - } - - /// <summary> - /// Protect and url-encode the specified token secret. - /// </summary> - /// <param name="token">The token to be used as a key.</param> - /// <param name="tokenSecret">The token secret to be protected</param> - /// <returns>The encrypted and protected string.</returns> - protected static string ProtectAndEncodeToken(string token, string tokenSecret) - { - byte[] cookieBytes = Encoding.UTF8.GetBytes(tokenSecret); - var secretBytes = MachineKeyUtil.Protect(cookieBytes, TokenCookieKey, "Token:" + token); - return HttpServerUtility.UrlTokenEncode(secretBytes); - } - - /// <summary> - /// Url-decode and unprotect the specified encrypted token string. - /// </summary> - /// <param name="token">The token to be used as a key.</param> - /// <param name="encryptedToken">The encrypted token to be decrypted</param> - /// <returns>The original token secret</returns> - protected static string DecodeAndUnprotectToken(string token, string encryptedToken) - { - byte[] cookieBytes = HttpServerUtility.UrlTokenDecode(encryptedToken); - byte[] clearBytes = MachineKeyUtil.Unprotect(cookieBytes, TokenCookieKey, "Token:" + token); - return Encoding.UTF8.GetString(clearBytes); - } - } -}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/CookieOAuthTokenManager.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/CookieOAuthTokenManager.cs deleted file mode 100644 index 398ee85..0000000 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/CookieOAuthTokenManager.cs +++ /dev/null @@ -1,79 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CookieOAuthTokenManager.cs" company="Microsoft"> -// Copyright (c) Microsoft. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.AspNet.Clients { - using System.Web; - using System.Web.Security; - - /// <summary> - /// Stores OAuth tokens in the current request's cookie. - /// </summary> - /// <remarks> - /// This class is different from the <see cref="AuthenticationOnlyCookieOAuthTokenManager"/> in that - /// it also stores the access token after the authentication has succeeded. - /// </remarks> - public class CookieOAuthTokenManager : AuthenticationOnlyCookieOAuthTokenManager { - /// <summary> - /// Initializes a new instance of the <see cref="CookieOAuthTokenManager"/> class. - /// </summary> - public CookieOAuthTokenManager() { - } - - /// <summary> - /// Initializes a new instance of the <see cref="CookieOAuthTokenManager"/> class. - /// </summary> - /// <param name="context">The current request context.</param> - public CookieOAuthTokenManager(HttpContextBase context) - : base(context) { - } - - /// <summary> - /// Gets the token secret from the specified token. - /// </summary> - /// <param name="token">The token.</param> - /// <returns> - /// The token's secret - /// </returns> - public override string GetTokenSecret(string token) { - string secret = base.GetTokenSecret(token); - if (secret != null) { - return secret; - } - - // The base class checks for cookies in the Request object. - // Here we check in the Response object as well because we - // may have set it earlier in the request life cycle. - HttpCookie cookie = this.Context.Response.Cookies[TokenCookieKey]; - if (cookie == null || string.IsNullOrEmpty(cookie.Values[token])) { - return null; - } - - secret = DecodeAndUnprotectToken(token, cookie.Values[token]); - return secret; - } - - /// <summary> - /// Replaces the request token with access token. - /// </summary> - /// <param name="requestToken">The request token.</param> - /// <param name="accessToken">The access token.</param> - /// <param name="accessTokenSecret">The access token secret.</param> - public override void ReplaceRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret) { - var cookie = new HttpCookie(TokenCookieKey) { - HttpOnly = true - }; - - if (FormsAuthentication.RequireSSL) { - cookie.Secure = true; - } - - var encryptedToken = ProtectAndEncodeToken(accessToken, accessTokenSecret); - cookie.Values[accessToken] = encryptedToken; - - this.Context.Response.Cookies.Set(cookie); - } - } -}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs index e216906..1b6318f 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs @@ -8,6 +8,10 @@ namespace DotNetOpenAuth.AspNet.Clients { using System; using System.Collections.Generic; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; @@ -17,13 +21,13 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// The dot net open auth web consumer. /// </summary> - public class DotNetOpenAuthWebConsumer : IOAuthWebWorker, IDisposable { + public class DotNetOpenAuthWebConsumer : IOAuthWebWorker { #region Constants and Fields /// <summary> /// The _web consumer. /// </summary> - private readonly WebConsumer webConsumer; + private readonly Consumer webConsumer; #endregion @@ -38,75 +42,65 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <param name="tokenManager"> /// The token manager. /// </param> - public DotNetOpenAuthWebConsumer(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) { + public DotNetOpenAuthWebConsumer(ServiceProviderDescription serviceDescription, string consumerKey, string consumerSecret) { Requires.NotNull(serviceDescription, "serviceDescription"); - Requires.NotNull(tokenManager, "tokenManager"); - this.webConsumer = new WebConsumer(serviceDescription, tokenManager); + this.webConsumer = new Consumer { + ServiceProvider = serviceDescription, + ConsumerKey = consumerKey, + ConsumerSecret = consumerSecret, + TemporaryCredentialStorage = new CookieTemporaryCredentialStorage(), + }; } #endregion - #region Public Methods and Operators - /// <summary> - /// The prepare authorized request. + /// Gets the DotNetOpenAuth <see cref="WebConsumer"/> instance that can be used to make OAuth 1.0 authorized HTTP requests. /// </summary> - /// <param name="profileEndpoint"> - /// The profile endpoint. - /// </param> - /// <param name="accessToken"> - /// The access token. - /// </param> - /// <returns>An HTTP request.</returns> - public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint profileEndpoint, string accessToken) { - return this.webConsumer.PrepareAuthorizedRequest(profileEndpoint, accessToken); + public Consumer Consumer { + get { return this.webConsumer; } } + #region Public Methods and Operators + /// <summary> - /// The process user authorization. + /// Creates an HTTP message handler that authorizes outgoing web requests. /// </summary> - /// <returns>The response message.</returns> - public AuthorizedTokenResponse ProcessUserAuthorization() { - return this.webConsumer.ProcessUserAuthorization(); + /// <param name="accessToken">The access token.</param> + public HttpMessageHandler CreateMessageHandler(AccessToken accessToken) { + Requires.NotNullOrEmpty(accessToken.Token, "accessToken"); + + return this.Consumer.CreateMessageHandler(accessToken); } /// <summary> - /// The request authentication. + /// The process user authorization. /// </summary> - /// <param name="callback"> - /// The callback. - /// </param> - public void RequestAuthentication(Uri callback) { - var redirectParameters = new Dictionary<string, string>(); - UserAuthorizationRequest request = this.webConsumer.PrepareRequestUserAuthorization( - callback, null, redirectParameters); - this.webConsumer.Channel.PrepareResponse(request).Send(); - } - - #endregion + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The response message. + /// </returns> + public Task<AccessTokenResponse> ProcessUserAuthorizationAsync(HttpContextBase context = null, CancellationToken cancellationToken = default(CancellationToken)) { + if (context == null) { + context = new HttpContextWrapper(HttpContext.Current); + } - #region IDisposable members + return this.webConsumer.ProcessUserAuthorizationAsync(context.Request.Url, cancellationToken: cancellationToken); + } /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// The request authentication. /// </summary> - /// <filterpriority>2</filterpriority> - public void Dispose() { - this.Dispose(true); - GC.SuppressFinalize(this); + /// <param name="callback">The callback.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The response message. + /// </returns> + public Task<Uri> RequestAuthenticationAsync(Uri callback, CancellationToken cancellationToken = default(CancellationToken)) { + return this.webConsumer.RequestUserAuthorizationAsync(callback, cancellationToken: cancellationToken); } #endregion - - /// <summary> - /// Releases unmanaged and - optionally - managed resources - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool disposing) { - if (disposing) { - this.webConsumer.Dispose(); - } - } } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthTokenManager.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthTokenManager.cs deleted file mode 100644 index 92f1c22..0000000 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthTokenManager.cs +++ /dev/null @@ -1,38 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="IOAuthTokenManager.cs" company="Microsoft"> -// Copyright (c) Microsoft. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.AspNet.Clients { - /// <summary> - /// A token manager for use by a web site in its role as a consumer of - /// an individual ServiceProvider. - /// </summary> - /// <remarks> - /// This interface is used by clients of the DotNetOpenAuth.AspNet classes. - /// </remarks> - public interface IOAuthTokenManager { - /// <summary> - /// Gets the token secret from the specified token. - /// </summary> - /// <param name="token">The token.</param> - /// <returns>The token's secret</returns> - string GetTokenSecret(string token); - - /// <summary> - /// Stores the request token together with its secret. - /// </summary> - /// <param name="requestToken">The request token.</param> - /// <param name="requestTokenSecret">The request token secret.</param> - void StoreRequestToken(string requestToken, string requestTokenSecret); - - /// <summary> - /// Replaces the request token with access token. - /// </summary> - /// <param name="requestToken">The request token.</param> - /// <param name="accessToken">The access token.</param> - /// <param name="accessTokenSecret">The access token secret.</param> - void ReplaceRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret); - } -}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs index a054a1c..e3ee3e8 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs @@ -7,41 +7,39 @@ namespace DotNetOpenAuth.AspNet.Clients { using System; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using System.Web; using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.Messages; /// <summary> - /// The io auth web worker. + /// The interface implemented by all OAuth web authentication modules in this assembly. /// </summary> public interface IOAuthWebWorker { - #region Public Methods and Operators - /// <summary> - /// The prepare authorized request. + /// Creates an HTTP message handler that authorizes outgoing web requests. /// </summary> - /// <param name="profileEndpoint"> - /// The profile endpoint. - /// </param> - /// <param name="accessToken"> - /// The access token. - /// </param> - /// <returns>An HTTP request.</returns> - HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint profileEndpoint, string accessToken); + /// <param name="accessToken">The access token.</param> + HttpMessageHandler CreateMessageHandler(AccessToken accessToken); /// <summary> /// The process user authorization. /// </summary> - /// <returns>The response message.</returns> - AuthorizedTokenResponse ProcessUserAuthorization(); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The access token, if obtained; otherwise <c>null</c>. + /// </returns> + Task<AccessTokenResponse> ProcessUserAuthorizationAsync(HttpContextBase context = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The request authentication. /// </summary> - /// <param name="callback"> - /// The callback. - /// </param> - void RequestAuthentication(Uri callback); - - #endregion + /// <param name="callback">The callback.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The URL to redirect the user agent to.</returns> + Task<Uri> RequestAuthenticationAsync(Uri callback, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/InMemoryOAuthTokenManager.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/InMemoryOAuthTokenManager.cs deleted file mode 100644 index a7b641c..0000000 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/InMemoryOAuthTokenManager.cs +++ /dev/null @@ -1,158 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="InMemoryOAuthTokenManager.cs" company="Microsoft"> -// Copyright (c) Microsoft. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.AspNet.Clients { - using System; - using System.Collections.Generic; - using DotNetOpenAuth.OAuth; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - using Validation; - - /// <summary> - /// An implementation of IOAuthTokenManager which stores keys in memory. - /// </summary> - public sealed class InMemoryOAuthTokenManager : IConsumerTokenManager { - #region Constants and Fields - - /// <summary> - /// The _tokens and secrets. - /// </summary> - private readonly Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); - - #endregion - - #region Constructors and Destructors - - /// <summary> - /// Initializes a new instance of the <see cref="InMemoryOAuthTokenManager"/> class. - /// </summary> - /// <param name="consumerKey"> - /// The consumer key. - /// </param> - /// <param name="consumerSecret"> - /// The consumer secret. - /// </param> - public InMemoryOAuthTokenManager(string consumerKey, string consumerSecret) { - Requires.NotNull(consumerKey, "consumerKey"); - Requires.NotNull(consumerSecret, "consumerSecret"); - - this.ConsumerKey = consumerKey; - this.ConsumerSecret = consumerSecret; - } - - #endregion - - #region Public Properties - - /// <summary> - /// Gets the consumer key. - /// </summary> - public string ConsumerKey { get; private set; } - - /// <summary> - /// Gets the consumer secret. - /// </summary> - public string ConsumerSecret { get; private set; } - - #endregion - - #region Public Methods and Operators - - /// <summary> - /// Deletes a request token and its associated secret and stores a new access token and secret. - /// </summary> - /// <param name="consumerKey"> - /// The Consumer that is exchanging its request token for an access token. - /// </param> - /// <param name="requestToken"> - /// The Consumer's request token that should be deleted/expired. - /// </param> - /// <param name="accessToken"> - /// The new access token that is being issued to the Consumer. - /// </param> - /// <param name="accessTokenSecret"> - /// The secret associated with the newly issued access token. - /// </param> - /// <remarks> - /// <para> - /// Any scope of granted privileges associated with the request token from the - /// original call to - /// <see cref="StoreNewRequestToken"/> - /// should be carried over - /// to the new Access Token. - /// </para> - /// <para> - /// To associate a user account with the new access token, - /// <see cref="System.Web.HttpContext.User">HttpContext.Current.User</see> - /// may be - /// useful in an ASP.NET web application within the implementation of this method. - /// Alternatively you may store the access token here without associating with a user account, - /// and wait until - /// <see cref="WebConsumer.ProcessUserAuthorization()"/> - /// or - /// <see cref="DesktopConsumer.ProcessUserAuthorization(string, string)"/> - /// return the access - /// token to associate the access token with a user account at that point. - /// </para> - /// </remarks> - public void ExpireRequestTokenAndStoreNewAccessToken( - string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { - this.tokensAndSecrets.Remove(requestToken); - this.tokensAndSecrets[accessToken] = accessTokenSecret; - } - - /// <summary> - /// Gets the Token Secret given a request or access token. - /// </summary> - /// <param name="token"> - /// The request or access token. - /// </param> - /// <returns> - /// The secret associated with the given token. - /// </returns> - /// <exception cref="ArgumentException"> - /// Thrown if the secret cannot be found for the given token. - /// </exception> - public string GetTokenSecret(string token) { - return this.tokensAndSecrets[token]; - } - - /// <summary> - /// Classifies a token as a request token or an access token. - /// </summary> - /// <param name="token"> - /// The token to classify. - /// </param> - /// <returns> - /// Request or Access token, or invalid if the token is not recognized. - /// </returns> - public TokenType GetTokenType(string token) { - throw new NotImplementedException(); - } - - /// <summary> - /// Stores a newly generated unauthorized request token, secret, and optional application-specific parameters for later recall. - /// </summary> - /// <param name="request"> - /// The request message that resulted in the generation of a new unauthorized request token. - /// </param> - /// <param name="response"> - /// The response message that includes the unauthorized request token. - /// </param> - /// <exception cref="ArgumentException"> - /// Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection. - /// </exception> - /// <remarks> - /// Request tokens stored by this method SHOULD NOT associate any user account with this token. It usually opens up security holes in your application to do so. Instead, you associate a user account with access tokens (not request tokens) in the <see cref="ExpireRequestTokenAndStoreNewAccessToken"/> method. - /// </remarks> - public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { - this.tokensAndSecrets[response.Token] = response.TokenSecret; - } - - #endregion - } -} diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs index 3c157f3..daf3441 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs @@ -10,11 +10,15 @@ namespace DotNetOpenAuth.AspNet.Clients { using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using System.Xml.Linq; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; + using System.Collections.Specialized; /// <summary> /// Represents LinkedIn authentication client. @@ -25,21 +29,10 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// Describes the OAuth service provider endpoints for LinkedIn. /// </summary> - public static readonly ServiceProviderDescription LinkedInServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = - new MessageReceivingEndpoint( - "https://api.linkedin.com/uas/oauth/requestToken", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - UserAuthorizationEndpoint = - new MessageReceivingEndpoint( - "https://www.linkedin.com/uas/oauth/authenticate", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - AccessTokenEndpoint = - new MessageReceivingEndpoint( - "https://api.linkedin.com/uas/oauth/accessToken", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; + public static readonly ServiceProviderDescription LinkedInServiceDescription = new ServiceProviderDescription( + "https://api.linkedin.com/uas/oauth/requestToken", + "https://www.linkedin.com/uas/oauth/authenticate", + "https://api.linkedin.com/uas/oauth/accessToken"); #endregion @@ -48,28 +41,10 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// Initializes a new instance of the <see cref="LinkedInClient"/> class. /// </summary> - /// <remarks> - /// Tokens exchanged during the OAuth handshake are stored in cookies. - /// </remarks> - /// <param name="consumerKey"> - /// The LinkedIn app's consumer key. - /// </param> - /// <param name="consumerSecret"> - /// The LinkedIn app's consumer secret. - /// </param> - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", - Justification = "We can't dispose the object because we still need it through the app lifetime.")] - public LinkedInClient(string consumerKey, string consumerSecret) - : this(consumerKey, consumerSecret, new CookieOAuthTokenManager()) { } - - /// <summary> - /// Initializes a new instance of the <see cref="LinkedInClient"/> class. - /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> - /// <param name="tokenManager">The token manager.</param> - public LinkedInClient(string consumerKey, string consumerSecret, IOAuthTokenManager tokenManager) - : base("linkedIn", LinkedInServiceDescription, new SimpleConsumerTokenManager(consumerKey, consumerSecret, tokenManager)) { + public LinkedInClient(string consumerKey, string consumerSecret) + : base("linkedIn", LinkedInServiceDescription, consumerKey, consumerSecret) { } #endregion @@ -79,46 +54,48 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> - /// <param name="response"> - /// The response token returned from service provider - /// </param> + /// <param name="response">The response token returned from service provider</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// Authentication result. + /// Authentication result. /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care if the request fails.")] - protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { + protected override async Task<AuthenticationResult> VerifyAuthenticationCoreAsync(AccessTokenResponse response, CancellationToken cancellationToken = default(CancellationToken)) { // See here for Field Selectors API http://developer.linkedin.com/docs/DOC-1014 const string ProfileRequestUrl = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,industry,summary)"; - string accessToken = response.AccessToken; - - var profileEndpoint = new MessageReceivingEndpoint(ProfileRequestUrl, HttpDeliveryMethods.GetRequest); - HttpWebRequest request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken); - + var accessToken = response.AccessToken; + var authorizingHandler = this.WebWorker.CreateMessageHandler(accessToken); try { - using (WebResponse profileResponse = request.GetResponse()) { - using (Stream responseStream = profileResponse.GetResponseStream()) { - XDocument document = LoadXDocumentFromStream(responseStream); - string userId = document.Root.Element("id").Value; - - string firstName = document.Root.Element("first-name").Value; - string lastName = document.Root.Element("last-name").Value; - string userName = firstName + " " + lastName; - - var extraData = new Dictionary<string, string>(); - extraData.Add("accesstoken", accessToken); - extraData.Add("name", userName); - extraData.AddDataIfNotEmpty(document, "headline"); - extraData.AddDataIfNotEmpty(document, "summary"); - extraData.AddDataIfNotEmpty(document, "industry"); - - return new AuthenticationResult( - isSuccessful: true, provider: this.ProviderName, providerUserId: userId, userName: userName, extraData: extraData); + using (var httpClient = new HttpClient(authorizingHandler)) { + using (HttpResponseMessage profileResponse = await httpClient.GetAsync(ProfileRequestUrl, cancellationToken)) { + using (Stream responseStream = await profileResponse.Content.ReadAsStreamAsync()) { + XDocument document = LoadXDocumentFromStream(responseStream); + string userId = document.Root.Element("id").Value; + + string firstName = document.Root.Element("first-name").Value; + string lastName = document.Root.Element("last-name").Value; + string userName = firstName + " " + lastName; + + var extraData = new NameValueCollection(); + extraData.Add("accesstoken", accessToken.Token); + extraData.Add("accesstokensecret", accessToken.Secret); + extraData.Add("name", userName); + extraData.AddDataIfNotEmpty(document, "headline"); + extraData.AddDataIfNotEmpty(document, "summary"); + extraData.AddDataIfNotEmpty(document, "industry"); + + return new AuthenticationResult( + isSuccessful: true, + provider: this.ProviderName, + providerUserId: userId, + userName: userName, + extraData: extraData); + } } } - } - catch (Exception exception) { + } catch (Exception exception) { return new AuthenticationResult(exception); } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/OAuthClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/OAuthClient.cs index a0afeca..1841ef3 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/OAuthClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/OAuthClient.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.AspNet.Clients { using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Xml; using System.Xml.Linq; @@ -17,6 +19,7 @@ namespace DotNetOpenAuth.AspNet.Clients { using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; using Validation; + using System.Collections.Specialized; /// <summary> /// Represents base class for OAuth 1.0 clients @@ -31,34 +34,14 @@ namespace DotNetOpenAuth.AspNet.Clients { /// Name of the provider. /// </param> /// <param name="serviceDescription"> - /// The service description. - /// </param> - /// <param name="consumerKey"> - /// The consumer key. - /// </param> - /// <param name="consumerSecret"> - /// The consumer secret. - /// </param> - protected OAuthClient( - string providerName, ServiceProviderDescription serviceDescription, string consumerKey, string consumerSecret) - : this(providerName, serviceDescription, new InMemoryOAuthTokenManager(consumerKey, consumerSecret)) { } - - /// <summary> - /// Initializes a new instance of the <see cref="OAuthClient"/> class. - /// </summary> - /// <param name="providerName"> - /// Name of the provider. - /// </param> - /// <param name="serviceDescription"> /// The service Description. /// </param> /// <param name="tokenManager"> /// The token Manager. /// </param> - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "I don't know how to ensure this rule is followed given this API")] protected OAuthClient( - string providerName, ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) - : this(providerName, new DotNetOpenAuthWebConsumer(serviceDescription, tokenManager)) { + string providerName, ServiceProviderDescription serviceDescription, string consumerKey, string consumerSecret) + : this(providerName, new DotNetOpenAuthWebConsumer(serviceDescription, consumerKey, consumerSecret)) { } /// <summary> @@ -103,42 +86,40 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// Attempts to authenticate users by forwarding them to an external website, and upon succcess or failure, redirect users back to the specified url. /// </summary> - /// <param name="context"> - /// The context. - /// </param> - /// <param name="returnUrl"> - /// The return url after users have completed authenticating against external website. - /// </param> - public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl) { + /// <param name="context">The context.</param> + /// <param name="returnUrl">The return url after users have completed authenticating against external website.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public virtual Task RequestAuthenticationAsync(HttpContextBase context, Uri returnUrl, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(returnUrl, "returnUrl"); Requires.NotNull(context, "context"); Uri callback = returnUrl.StripQueryArgumentsWithPrefix("oauth_"); - this.WebWorker.RequestAuthentication(callback); + return this.WebWorker.RequestAuthenticationAsync(callback, cancellationToken); } /// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> - /// <param name="context"> - /// The context. - /// </param> + /// <param name="context">The context.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// An instance of <see cref="AuthenticationResult"/> containing authentication result. + /// An instance of <see cref="AuthenticationResult" /> containing authentication result. /// </returns> - public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context) { - AuthorizedTokenResponse response = this.WebWorker.ProcessUserAuthorization(); + public virtual async Task<AuthenticationResult> VerifyAuthenticationAsync(HttpContextBase context, CancellationToken cancellationToken = default(CancellationToken)) { + AccessTokenResponse response = await this.WebWorker.ProcessUserAuthorizationAsync(context, cancellationToken); if (response == null) { return AuthenticationResult.Failed; } - AuthenticationResult result = this.VerifyAuthenticationCore(response); + AuthenticationResult result = await this.VerifyAuthenticationCoreAsync(response, cancellationToken); if (result.IsSuccessful && result.ExtraData != null) { // add the access token to the user data dictionary just in case page developers want to use it - var wrapExtraData = result.ExtraData.IsReadOnly - ? new Dictionary<string, string>(result.ExtraData) - : result.ExtraData; - wrapExtraData["accesstoken"] = response.AccessToken; + var wrapExtraData = new NameValueCollection(result.ExtraData); + wrapExtraData["accesstoken"] = response.AccessToken.Token; + wrapExtraData["accesstokensecret"] = response.AccessToken.Secret; AuthenticationResult wrapResult = new AuthenticationResult( result.IsSuccessful, @@ -174,12 +155,13 @@ namespace DotNetOpenAuth.AspNet.Clients { /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> /// <param name="response"> - /// The response token returned from service provider + /// The access token returned from service provider /// </param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Authentication result /// </returns> - protected abstract AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response); + protected abstract Task<AuthenticationResult> VerifyAuthenticationCoreAsync(AccessTokenResponse response, CancellationToken cancellationToken); #endregion } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/SimpleConsumerTokenManager.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/SimpleConsumerTokenManager.cs deleted file mode 100644 index 899204c..0000000 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/SimpleConsumerTokenManager.cs +++ /dev/null @@ -1,104 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="SimpleConsumerTokenManager.cs" company="Microsoft"> -// Copyright (c) Microsoft. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.AspNet.Clients { - using System; - using DotNetOpenAuth.OAuth.ChannelElements; - using Validation; - - /// <summary> - /// Simple wrapper around IConsumerTokenManager - /// </summary> - public class SimpleConsumerTokenManager : IConsumerTokenManager { - /// <summary> - /// Store the token manager. - /// </summary> - private readonly IOAuthTokenManager tokenManager; - - /// <summary> - /// Initializes a new instance of the <see cref="SimpleConsumerTokenManager"/> class. - /// </summary> - /// <param name="consumerKey">The consumer key.</param> - /// <param name="consumerSecret">The consumer secret.</param> - /// <param name="tokenManager">The OAuth token manager.</param> - public SimpleConsumerTokenManager(string consumerKey, string consumerSecret, IOAuthTokenManager tokenManager) { - Requires.NotNullOrEmpty(consumerKey, "consumerKey"); - Requires.NotNullOrEmpty(consumerSecret, "consumerSecret"); - Requires.NotNull(tokenManager, "oAuthTokenManager"); - - this.ConsumerKey = consumerKey; - this.ConsumerSecret = consumerSecret; - this.tokenManager = tokenManager; - } - - /// <summary> - /// Gets the consumer key. - /// </summary> - /// <value> - /// The consumer key. - /// </value> - public string ConsumerKey { - get; - private set; - } - - /// <summary> - /// Gets the consumer secret. - /// </summary> - /// <value> - /// The consumer secret. - /// </value> - public string ConsumerSecret { - get; - private set; - } - - /// <summary> - /// Gets the Token Secret given a request or access token. - /// </summary> - /// <param name="token">The request or access token.</param> - /// <returns> - /// The secret associated with the given token. - /// </returns> - /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception> - public string GetTokenSecret(string token) { - return this.tokenManager.GetTokenSecret(token); - } - - /// <summary> - /// Stores a newly generated unauthorized request token, secret, and optional - /// application-specific parameters for later recall. - /// </summary> - /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param> - /// <param name="response">The response message that includes the unauthorized request token.</param> - /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception> - public void StoreNewRequestToken(DotNetOpenAuth.OAuth.Messages.UnauthorizedTokenRequest request, DotNetOpenAuth.OAuth.Messages.ITokenSecretContainingMessage response) { - this.tokenManager.StoreRequestToken(response.Token, response.TokenSecret); - } - - /// <summary> - /// Deletes a request token and its associated secret and stores a new access token and secret. - /// </summary> - /// <param name="consumerKey">The Consumer that is exchanging its request token for an access token.</param> - /// <param name="requestToken">The Consumer's request token that should be deleted/expired.</param> - /// <param name="accessToken">The new access token that is being issued to the Consumer.</param> - /// <param name="accessTokenSecret">The secret associated with the newly issued access token.</param> - public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { - this.tokenManager.ReplaceRequestTokenWithAccessToken(requestToken, accessToken, accessTokenSecret); - } - - /// <summary> - /// Classifies a token as a request token or an access token. - /// </summary> - /// <param name="token">The token to classify.</param> - /// <returns> - /// Request or Access token, or invalid if the token is not recognized. - /// </returns> - public TokenType GetTokenType(string token) { - throw new NotSupportedException(); - } - } -}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs index 886917a..0c17ed3 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs @@ -10,11 +10,15 @@ namespace DotNetOpenAuth.AspNet.Clients { using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using System.Xml.Linq; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; + using System.Collections.Specialized; /// <summary> /// Represents a Twitter client @@ -25,51 +29,23 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// The description of Twitter's OAuth protocol URIs for use with their "Sign in with Twitter" feature. /// </summary> - public static readonly ServiceProviderDescription TwitterServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = - new MessageReceivingEndpoint( - "https://api.twitter.com/oauth/request_token", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - UserAuthorizationEndpoint = - new MessageReceivingEndpoint( - "https://api.twitter.com/oauth/authenticate", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - AccessTokenEndpoint = - new MessageReceivingEndpoint( - "https://api.twitter.com/oauth/access_token", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; + public static readonly ServiceProviderDescription TwitterServiceDescription = + new ServiceProviderDescription( + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/authenticate", + "https://api.twitter.com/oauth/access_token"); #endregion #region Constructors and Destructors /// <summary> - /// Initializes a new instance of the <see cref="TwitterClient"/> class with the specified consumer key and consumer secret. - /// </summary> - /// <remarks> - /// Tokens exchanged during the OAuth handshake are stored in cookies. - /// </remarks> - /// <param name="consumerKey"> - /// The consumer key. - /// </param> - /// <param name="consumerSecret"> - /// The consumer secret. - /// </param> - [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", - Justification = "We can't dispose the object because we still need it through the app lifetime.")] - public TwitterClient(string consumerKey, string consumerSecret) - : this(consumerKey, consumerSecret, new AuthenticationOnlyCookieOAuthTokenManager()) { } - - /// <summary> /// Initializes a new instance of the <see cref="TwitterClient"/> class. /// </summary> /// <param name="consumerKey">The consumer key.</param> /// <param name="consumerSecret">The consumer secret.</param> - /// <param name="tokenManager">The token manager.</param> - public TwitterClient(string consumerKey, string consumerSecret, IOAuthTokenManager tokenManager) - : base("twitter", TwitterServiceDescription, new SimpleConsumerTokenManager(consumerKey, consumerSecret, tokenManager)) { + public TwitterClient(string consumerKey, string consumerSecret) + : base("twitter", TwitterServiceDescription, consumerKey, consumerSecret) { } #endregion @@ -79,34 +55,34 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> - /// <param name="response"> - /// The response token returned from service provider - /// </param> + /// <param name="response">The response token returned from service provider</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// Authentication result + /// Authentication result /// </returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't care if the request for additional data fails.")] - protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { - string accessToken = response.AccessToken; + protected override async Task<AuthenticationResult> VerifyAuthenticationCoreAsync(AccessTokenResponse response, CancellationToken cancellationToken) { string userId = response.ExtraData["user_id"]; string userName = response.ExtraData["screen_name"]; var profileRequestUrl = new Uri("https://api.twitter.com/1/users/show.xml?user_id=" + MessagingUtilities.EscapeUriDataStringRfc3986(userId)); - var profileEndpoint = new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest); - HttpWebRequest request = this.WebWorker.PrepareAuthorizedRequest(profileEndpoint, accessToken); + var authorizingHandler = this.WebWorker.CreateMessageHandler(response.AccessToken); - var extraData = new Dictionary<string, string>(); - extraData.Add("accesstoken", accessToken); + var extraData = new NameValueCollection(); + extraData.Add("accesstoken", response.AccessToken.Token); + extraData.Add("accesstokensecret", response.AccessToken.Secret); try { - using (WebResponse profileResponse = request.GetResponse()) { - using (Stream responseStream = profileResponse.GetResponseStream()) { - XDocument document = LoadXDocumentFromStream(responseStream); - extraData.AddDataIfNotEmpty(document, "name"); - extraData.AddDataIfNotEmpty(document, "location"); - extraData.AddDataIfNotEmpty(document, "description"); - extraData.AddDataIfNotEmpty(document, "url"); + using (var httpClient = new HttpClient(authorizingHandler)) { + using (HttpResponseMessage profileResponse = await httpClient.GetAsync(profileRequestUrl, cancellationToken)) { + using (Stream responseStream = await profileResponse.Content.ReadAsStreamAsync()) { + XDocument document = LoadXDocumentFromStream(responseStream); + extraData.AddDataIfNotEmpty(document, "name"); + extraData.AddDataIfNotEmpty(document, "location"); + extraData.AddDataIfNotEmpty(document, "description"); + extraData.AddDataIfNotEmpty(document, "url"); + } } } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs index d20e452..c06c1dc 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/FacebookClient.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.AspNet.Clients { using System.Web; using DotNetOpenAuth.Messaging; using Validation; + using System.Collections.Specialized; /// <summary> /// The facebook client. @@ -92,7 +93,7 @@ namespace DotNetOpenAuth.AspNet.Clients { /// The access token. /// </param> /// <returns>A dictionary of profile data.</returns> - protected override IDictionary<string, string> GetUserData(string accessToken) { + protected override NameValueCollection GetUserData(string accessToken) { FacebookGraphData graphData; var request = WebRequest.Create( @@ -104,7 +105,7 @@ namespace DotNetOpenAuth.AspNet.Clients { } // this dictionary must contains - var userData = new Dictionary<string, string>(); + var userData = new NameValueCollection(); userData.AddItemIfNotEmpty("id", graphData.Id); userData.AddItemIfNotEmpty("username", graphData.Email); userData.AddItemIfNotEmpty("name", graphData.Name); diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/MicrosoftClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/MicrosoftClient.cs index 3e5f71f..b9c4941 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/MicrosoftClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/MicrosoftClient.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.AspNet.Clients { using System.Net; using DotNetOpenAuth.Messaging; using Validation; + using System.Collections.Specialized; /// <summary> /// The Microsoft account client. @@ -110,7 +111,7 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <returns> /// A dictionary contains key-value pairs of user data /// </returns> - protected override IDictionary<string, string> GetUserData(string accessToken) { + protected override NameValueCollection GetUserData(string accessToken) { MicrosoftClientUserData graph; var request = WebRequest.Create( @@ -121,7 +122,7 @@ namespace DotNetOpenAuth.AspNet.Clients { } } - var userData = new Dictionary<string, string>(); + var userData = new NameValueCollection(); userData.AddItemIfNotEmpty("id", graph.Id); userData.AddItemIfNotEmpty("username", graph.Name); userData.AddItemIfNotEmpty("name", graph.Name); diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs index 014f459..8e6b5f3 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth2/OAuth2Client.cs @@ -8,8 +8,14 @@ namespace DotNetOpenAuth.AspNet.Clients { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Threading; + using System.Threading.Tasks; using System.Web; + + using DotNetOpenAuth.Messaging; + using Validation; + using System.Collections.Specialized; /// <summary> /// Represents the base class for OAuth 2.0 clients @@ -57,30 +63,31 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// Attempts to authenticate users by forwarding them to an external website, and upon succcess or failure, redirect users back to the specified url. /// </summary> - /// <param name="context"> - /// The context. - /// </param> - /// <param name="returnUrl"> - /// The return url after users have completed authenticating against external website. - /// </param> - public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl) { + /// <param name="context">The context.</param> + /// <param name="returnUrl">The return url after users have completed authenticating against external website.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public virtual Task RequestAuthenticationAsync(HttpContextBase context, Uri returnUrl, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(context, "context"); Requires.NotNull(returnUrl, "returnUrl"); string redirectUrl = this.GetServiceLoginUrl(returnUrl).AbsoluteUri; context.Response.Redirect(redirectUrl, endResponse: true); + return MessagingUtilities.CompletedTask; } /// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> - /// <param name="context"> - /// The context. - /// </param> + /// <param name="context">The context.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// An instance of <see cref="AuthenticationResult"/> containing authentication result. + /// An instance of <see cref="AuthenticationResult" /> containing authentication result. /// </returns> - public AuthenticationResult VerifyAuthentication(HttpContextBase context) { + /// <exception cref="System.InvalidOperationException">Always thrown.</exception> + public Task<AuthenticationResult> VerifyAuthenticationAsync(HttpContextBase context, CancellationToken cancellationToken = default(CancellationToken)) { throw new InvalidOperationException(WebResources.OAuthRequireReturnUrl); } @@ -89,10 +96,11 @@ namespace DotNetOpenAuth.AspNet.Clients { /// </summary> /// <param name="context">The context.</param> /// <param name="returnPageUrl">The return URL which should match the value passed to RequestAuthentication() method.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// An instance of <see cref="AuthenticationResult"/> containing authentication result. + /// An instance of <see cref="AuthenticationResult" /> containing authentication result. /// </returns> - public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context, Uri returnPageUrl) { + public virtual async Task<AuthenticationResult> VerifyAuthenticationAsync(HttpContextBase context, Uri returnPageUrl, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(context, "context"); string code = context.Request.QueryString["code"]; @@ -105,19 +113,15 @@ namespace DotNetOpenAuth.AspNet.Clients { return AuthenticationResult.Failed; } - IDictionary<string, string> userData = this.GetUserData(accessToken); + var userData = this.GetUserData(accessToken); if (userData == null) { return AuthenticationResult.Failed; } - string id = userData["id"]; - string name; - // Some oAuth providers do not return value for the 'username' attribute. // In that case, try the 'name' attribute. If it's still unavailable, fall back to 'id' - if (!userData.TryGetValue("username", out name) && !userData.TryGetValue("name", out name)) { - name = id; - } + string id = userData["id"]; + string name = userData["username"] ?? userData["name"] ?? id; // add the access token to the user data dictionary just in case page developers want to use it userData["accesstoken"] = accessToken; @@ -152,7 +156,7 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <returns> /// A dictionary contains key-value pairs of user data /// </returns> - protected abstract IDictionary<string, string> GetUserData(string accessToken); + protected abstract NameValueCollection GetUserData(string accessToken); /// <summary> /// Queries the access token from the specified authorization code. diff --git a/src/DotNetOpenAuth.AspNet/Clients/OpenID/GoogleOpenIdClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OpenID/GoogleOpenIdClient.cs index 6b4061a..2a68bd8 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OpenID/GoogleOpenIdClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OpenID/GoogleOpenIdClient.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.AspNet.Clients { using System.Collections.Generic; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.OpenId.RelyingParty; + using System.Collections.Specialized; /// <summary> /// Represents Google OpenID client. @@ -32,10 +33,10 @@ namespace DotNetOpenAuth.AspNet.Clients { /// The response message. /// </param> /// <returns>A dictionary of profile data; or null if no data is available.</returns> - protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response) { + protected override NameValueCollection GetExtraData(IAuthenticationResponse response) { FetchResponse fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse != null) { - var extraData = new Dictionary<string, string>(); + var extraData = new NameValueCollection(); extraData.AddItemIfNotEmpty("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); extraData.AddItemIfNotEmpty("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country)); extraData.AddItemIfNotEmpty("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First)); diff --git a/src/DotNetOpenAuth.AspNet/Clients/OpenID/OpenIDClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OpenID/OpenIDClient.cs index a41b504..901741b 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OpenID/OpenIDClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OpenID/OpenIDClient.cs @@ -8,11 +8,14 @@ namespace DotNetOpenAuth.AspNet.Clients { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; using Validation; + using System.Collections.Specialized; /// <summary> /// Base classes for OpenID clients. @@ -79,51 +82,47 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <summary> /// Attempts to authenticate users by forwarding them to an external website, and upon succcess or failure, redirect users back to the specified url. /// </summary> - /// <param name="context"> - /// The context of the current request. - /// </param> - /// <param name="returnUrl"> - /// The return url after users have completed authenticating against external website. - /// </param> + /// <param name="context">The context of the current request.</param> + /// <param name="returnUrl">The return url after users have completed authenticating against external website.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "We don't have a Uri object handy.")] - public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl) { + public virtual async Task RequestAuthenticationAsync(HttpContextBase context, Uri returnUrl, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(returnUrl, "returnUrl"); var realm = new Realm(returnUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)); - IAuthenticationRequest request = RelyingParty.CreateRequest(this.providerIdentifier, realm, returnUrl); + IAuthenticationRequest request = await RelyingParty.CreateRequestAsync(this.providerIdentifier, realm, returnUrl, cancellationToken); // give subclasses a chance to modify request message, e.g. add extension attributes, etc. this.OnBeforeSendingAuthenticationRequest(request); - request.RedirectToProvider(); + await request.RedirectToProviderAsync(context); } /// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> - /// <param name="context"> - /// The context of the current request. - /// </param> + /// <param name="context">The context of the current request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// An instance of <see cref="AuthenticationResult"/> containing authentication result. + /// An instance of <see cref="AuthenticationResult" /> containing authentication result. /// </returns> - public virtual AuthenticationResult VerifyAuthentication(HttpContextBase context) { - IAuthenticationResponse response = RelyingParty.GetResponse(); + /// <exception cref="System.InvalidOperationException">Thrown if no OpenID response was found in the incoming HTTP request.</exception> + public virtual async Task<AuthenticationResult> VerifyAuthenticationAsync(HttpContextBase context, CancellationToken cancellationToken = default(CancellationToken)) { + IAuthenticationResponse response = await RelyingParty.GetResponseAsync(context.Request, cancellationToken); if (response == null) { throw new InvalidOperationException(WebResources.OpenIDFailedToGetResponse); } if (response.Status == AuthenticationStatus.Authenticated) { string id = response.ClaimedIdentifier; - string username; - - Dictionary<string, string> extraData = this.GetExtraData(response) ?? new Dictionary<string, string>(); + var extraData = this.GetExtraData(response) ?? new NameValueCollection(); // try to look up username from the 'username' or 'email' property. If not found, fall back to 'friendly id' - if (!extraData.TryGetValue("username", out username) && !extraData.TryGetValue("email", out username)) { - username = response.FriendlyIdentifierForDisplay; - } + string username = extraData["username"] ?? extraData["email"] ?? response.FriendlyIdentifierForDisplay; return new AuthenticationResult(true, this.ProviderName, id, username, extraData); } @@ -142,7 +141,7 @@ namespace DotNetOpenAuth.AspNet.Clients { /// The response message. /// </param> /// <returns>Always null.</returns> - protected virtual Dictionary<string, string> GetExtraData(IAuthenticationResponse response) { + protected virtual NameValueCollection GetExtraData(IAuthenticationResponse response) { return null; } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OpenID/YahooOpenIdClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OpenID/YahooOpenIdClient.cs index bd420fc..d282d4f 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OpenID/YahooOpenIdClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OpenID/YahooOpenIdClient.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.AspNet.Clients { using System.Collections.Generic; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using DotNetOpenAuth.OpenId.RelyingParty; + using System.Collections.Specialized; /// <summary> /// The yahoo open id client. @@ -32,10 +33,10 @@ namespace DotNetOpenAuth.AspNet.Clients { /// The response message. /// </param> /// <returns>A dictionary of profile data; or null if no data is available.</returns> - protected override Dictionary<string, string> GetExtraData(IAuthenticationResponse response) { + protected override NameValueCollection GetExtraData(IAuthenticationResponse response) { FetchResponse fetchResponse = response.GetExtension<FetchResponse>(); if (fetchResponse != null) { - var extraData = new Dictionary<string, string>(); + var extraData = new NameValueCollection(); extraData.AddItemIfNotEmpty("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); extraData.AddItemIfNotEmpty("fullName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName)); diff --git a/src/DotNetOpenAuth.AspNet/DotNetOpenAuth.AspNet.csproj b/src/DotNetOpenAuth.AspNet/DotNetOpenAuth.AspNet.csproj index 16229c7..b3b52d9 100644 --- a/src/DotNetOpenAuth.AspNet/DotNetOpenAuth.AspNet.csproj +++ b/src/DotNetOpenAuth.AspNet/DotNetOpenAuth.AspNet.csproj @@ -32,6 +32,8 @@ <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.Web" /> <Reference Include="System.Xml.Linq" /> @@ -39,21 +41,15 @@ <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Data" /> <Reference Include="System.Xml" /> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> <Compile Include="AuthenticationResult.cs" /> <Compile Include="Clients\DictionaryExtensions.cs" /> <Compile Include="Clients\OAuth2\WindowsLiveClient.cs" /> - <Compile Include="Clients\OAuth\AuthenticationOnlyCookieOAuthTokenManager.cs"> - <SubType>Code</SubType> - </Compile> - <Compile Include="Clients\OAuth\CookieOAuthTokenManager.cs" /> - <Compile Include="Clients\OAuth\IOAuthTokenManager.cs" /> - <Compile Include="Clients\OAuth\SimpleConsumerTokenManager.cs" /> <Compile Include="IAuthenticationClient.cs" /> <Compile Include="Clients\OAuth2\FacebookClient.cs" /> <Compile Include="Clients\OAuth2\FacebookGraphData.cs" /> @@ -63,7 +59,6 @@ <Compile Include="Clients\OAuth2\MicrosoftClient.cs" /> <Compile Include="Clients\OAuth2\MicrosoftClientUserData.cs" /> <Compile Include="Clients\OAuth\DotNetOpenAuthWebConsumer.cs" /> - <Compile Include="Clients\OAuth\InMemoryOAuthTokenManager.cs" /> <Compile Include="Clients\OAuth\IOAuthWebWorker.cs" /> <Compile Include="Clients\OAuth\LinkedInClient.cs" /> <Compile Include="Clients\OAuth\OAuthClient.cs" /> @@ -71,7 +66,6 @@ <Compile Include="Clients\OpenID\GoogleOpenIdClient.cs" /> <Compile Include="Clients\OpenID\OpenIdClient.cs" /> <Compile Include="Clients\OpenID\YahooOpenIdClient.cs" /> - <Compile Include="MachineKeyUtil.cs" /> <Compile Include="UriHelper.cs" /> <Compile Include="IOpenAuthDataProvider.cs" /> <Compile Include="OpenAuthAuthenticationTicketHelper.cs" /> diff --git a/src/DotNetOpenAuth.AspNet/IAuthenticationClient.cs b/src/DotNetOpenAuth.AspNet/IAuthenticationClient.cs index 4d9acde..b13f0d1 100644 --- a/src/DotNetOpenAuth.AspNet/IAuthenticationClient.cs +++ b/src/DotNetOpenAuth.AspNet/IAuthenticationClient.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.AspNet { using System; + using System.Threading; + using System.Threading.Tasks; using System.Web; /// <summary> @@ -20,23 +22,20 @@ namespace DotNetOpenAuth.AspNet { /// <summary> /// Attempts to authenticate users by forwarding them to an external website, and upon succcess or failure, redirect users back to the specified url. /// </summary> - /// <param name="context"> - /// The context of the current request. - /// </param> - /// <param name="returnUrl"> - /// The return url after users have completed authenticating against external website. - /// </param> - void RequestAuthentication(HttpContextBase context, Uri returnUrl); + /// <param name="context">The context of the current request.</param> + /// <param name="returnUrl">The return url after users have completed authenticating against external website.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>A task that completes with the async operation.</returns> + Task RequestAuthenticationAsync(HttpContextBase context, Uri returnUrl, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Check if authentication succeeded after user is redirected back from the service provider. /// </summary> - /// <param name="context"> - /// The context of the current request. - /// </param> + /// <param name="context">The context of the current request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// An instance of <see cref="AuthenticationResult"/> containing authentication result. + /// An instance of <see cref="AuthenticationResult" /> containing authentication result. /// </returns> - AuthenticationResult VerifyAuthentication(HttpContextBase context); + Task<AuthenticationResult> VerifyAuthenticationAsync(HttpContextBase context, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/src/DotNetOpenAuth.AspNet/OpenAuthSecurityManager.cs b/src/DotNetOpenAuth.AspNet/OpenAuthSecurityManager.cs index 6736205..7669072 100644 --- a/src/DotNetOpenAuth.AspNet/OpenAuthSecurityManager.cs +++ b/src/DotNetOpenAuth.AspNet/OpenAuthSecurityManager.cs @@ -8,6 +8,8 @@ namespace DotNetOpenAuth.AspNet { using System; using System.Diagnostics.CodeAnalysis; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Security; using DotNetOpenAuth.AspNet.Clients; @@ -141,10 +143,12 @@ namespace DotNetOpenAuth.AspNet { /// <summary> /// Requests the specified provider to start the authentication by directing users to an external website /// </summary> - /// <param name="returnUrl"> - /// The return url after user is authenticated. - /// </param> - public void RequestAuthentication(string returnUrl) { + /// <param name="returnUrl">The return url after user is authenticated.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public async Task RequestAuthenticationAsync(string returnUrl, CancellationToken cancellationToken = default(CancellationToken)) { // convert returnUrl to an absolute path Uri uri; if (!string.IsNullOrEmpty(returnUrl)) { @@ -176,20 +180,21 @@ namespace DotNetOpenAuth.AspNet { this.requestContext.Response.Cookies.Add(xsrfCookie); // issue the redirect to the external auth provider - this.authenticationProvider.RequestAuthentication(this.requestContext, uri); + await this.authenticationProvider.RequestAuthenticationAsync(this.requestContext, uri, cancellationToken); } /// <summary> /// Checks if user is successfully authenticated when user is redirected back to this user. /// </summary> /// <param name="returnUrl">The return Url which must match exactly the Url passed into RequestAuthentication() earlier.</param> - /// <remarks> - /// This returnUrl parameter only applies to OAuth2 providers. For other providers, it ignores the returnUrl parameter. - /// </remarks> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The result of the authentication. /// </returns> - public AuthenticationResult VerifyAuthentication(string returnUrl) { + /// <remarks> + /// This returnUrl parameter only applies to OAuth2 providers. For other providers, it ignores the returnUrl parameter. + /// </remarks> + public async Task<AuthenticationResult> VerifyAuthenticationAsync(string returnUrl, CancellationToken cancellationToken = default(CancellationToken)) { // check for XSRF attack string sessionId; bool successful = this.ValidateRequestAgainstXsrfAttack(out sessionId); @@ -223,7 +228,7 @@ namespace DotNetOpenAuth.AspNet { uri = uri.AttachQueryStringParameter(SessionIdQueryStringName, sessionId); try { - AuthenticationResult result = oauth2Client.VerifyAuthentication(this.requestContext, uri); + AuthenticationResult result = await oauth2Client.VerifyAuthenticationAsync(this.requestContext, uri, cancellationToken); if (!result.IsSuccessful) { // if the result is a Failed result, creates a new Failed response which has providerName info. result = new AuthenticationResult( @@ -241,7 +246,7 @@ namespace DotNetOpenAuth.AspNet { } } else { - return this.authenticationProvider.VerifyAuthentication(this.requestContext); + return await this.authenticationProvider.VerifyAuthenticationAsync(this.requestContext, cancellationToken); } } diff --git a/src/DotNetOpenAuth.AspNet/WebResources.Designer.cs b/src/DotNetOpenAuth.AspNet/WebResources.Designer.cs index fd79a73..da1d1ca 100644 --- a/src/DotNetOpenAuth.AspNet/WebResources.Designer.cs +++ b/src/DotNetOpenAuth.AspNet/WebResources.Designer.cs @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:4.0.30319.544 +// Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -79,15 +79,6 @@ namespace DotNetOpenAuth.AspNet { } /// <summary> - /// Looks up a localized string similar to The provided data could not be decrypted. If the current application is deployed in a web farm configuration, ensure that the 'decryptionKey' and 'validationKey' attributes are explicitly specified in the <machineKey> configuration section.. - /// </summary> - internal static string Generic_CryptoFailure { - get { - return ResourceManager.GetString("Generic_CryptoFailure", resourceCulture); - } - } - - /// <summary> /// Looks up a localized string similar to An OAuth data provider has already been registered for this application.. /// </summary> internal static string OAuthDataProviderRegistered { diff --git a/src/DotNetOpenAuth.AspNet/WebResources.resx b/src/DotNetOpenAuth.AspNet/WebResources.resx index c1552e9..a491579 100644 --- a/src/DotNetOpenAuth.AspNet/WebResources.resx +++ b/src/DotNetOpenAuth.AspNet/WebResources.resx @@ -123,9 +123,6 @@ <data name="FailedToEncryptTicket" xml:space="preserve"> <value>Unable to encrypt the authentication ticket.</value> </data> - <data name="Generic_CryptoFailure" xml:space="preserve"> - <value>The provided data could not be decrypted. If the current application is deployed in a web farm configuration, ensure that the 'decryptionKey' and 'validationKey' attributes are explicitly specified in the <machineKey> configuration section.</value> - </data> <data name="OAuthDataProviderRegistered" xml:space="preserve"> <value>An OAuth data provider has already been registered for this application.</value> </data> diff --git a/src/DotNetOpenAuth.AspNet/packages.config b/src/DotNetOpenAuth.AspNet/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.AspNet/packages.config +++ b/src/DotNetOpenAuth.AspNet/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj b/src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj index 86913d3..b68bf1c 100644 --- a/src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj +++ b/src/DotNetOpenAuth.Core.UI/DotNetOpenAuth.Core.UI.csproj @@ -33,9 +33,9 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.Core.UI/packages.config b/src/DotNetOpenAuth.Core.UI/packages.config index 58890d8..e3309bc 100644 --- a/src/DotNetOpenAuth.Core.UI/packages.config +++ b/src/DotNetOpenAuth.Core.UI/packages.config @@ -1,4 +1,4 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs index 08bd2a1..fa146a2 100644 --- a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs +++ b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationCollection.cs @@ -41,11 +41,14 @@ namespace DotNetOpenAuth.Configuration { /// Creates instances of all the types listed in the collection. /// </summary> /// <param name="allowInternals">if set to <c>true</c> then internal types may be instantiated.</param> - /// <returns>A sequence of instances generated from types in this collection. May be empty, but never null.</returns> - internal IEnumerable<T> CreateInstances(bool allowInternals) { + /// <param name="hostFactories">The host factories.</param> + /// <returns> + /// A sequence of instances generated from types in this collection. May be empty, but never null. + /// </returns> + internal IEnumerable<T> CreateInstances(bool allowInternals, IHostFactories hostFactories) { return from element in this.Cast<TypeConfigurationElement<T>>() where !element.IsEmpty - select element.CreateInstance(default(T), allowInternals); + select element.CreateInstance(default(T), allowInternals, hostFactories); } /// <summary> diff --git a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs index d554832..bcf199f 100644 --- a/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs +++ b/src/DotNetOpenAuth.Core/Configuration/TypeConfigurationElement.cs @@ -75,9 +75,12 @@ namespace DotNetOpenAuth.Configuration { /// Creates an instance of the type described in the .config file. /// </summary> /// <param name="defaultValue">The value to return if no type is given in the .config file.</param> - /// <returns>The newly instantiated type.</returns> - public T CreateInstance(T defaultValue) { - return this.CreateInstance(defaultValue, false); + /// <param name="hostFactories">The host factories.</param> + /// <returns> + /// The newly instantiated type. + /// </returns> + public T CreateInstance(T defaultValue, IHostFactories hostFactories) { + return this.CreateInstance(defaultValue, false, hostFactories); } /// <summary> @@ -85,9 +88,13 @@ namespace DotNetOpenAuth.Configuration { /// </summary> /// <param name="defaultValue">The value to return if no type is given in the .config file.</param> /// <param name="allowInternals">if set to <c>true</c> then internal types may be instantiated.</param> - /// <returns>The newly instantiated type.</returns> + /// <param name="hostFactories">The host factories.</param> + /// <returns> + /// The newly instantiated type. + /// </returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")] - public T CreateInstance(T defaultValue, bool allowInternals) { + public T CreateInstance(T defaultValue, bool allowInternals, IHostFactories hostFactories) { + T instance; if (this.CustomType != null) { if (!allowInternals) { // Although .NET will usually prevent our instantiating non-public types, @@ -95,7 +102,7 @@ namespace DotNetOpenAuth.Configuration { // But we don't want the host site to be able to do this, so we check ourselves. ErrorUtilities.VerifyArgument((this.CustomType.Attributes & TypeAttributes.Public) != 0, Strings.ConfigurationTypeMustBePublic, this.CustomType.FullName); } - return (T)Activator.CreateInstance(this.CustomType); + instance = (T)Activator.CreateInstance(this.CustomType); } else if (!string.IsNullOrEmpty(this.XamlSource)) { string source = this.XamlSource; if (source.StartsWith("~/", StringComparison.Ordinal)) { @@ -103,11 +110,18 @@ namespace DotNetOpenAuth.Configuration { source = HttpContext.Current.Server.MapPath(source); } using (Stream xamlFile = File.OpenRead(source)) { - return CreateInstanceFromXaml(xamlFile); + instance = CreateInstanceFromXaml(xamlFile); } } else { - return defaultValue; + instance = defaultValue; } + + var requiresHostFactories = instance as IRequireHostFactories; + if (requiresHostFactories != null) { + requiresHostFactories.HostFactories = hostFactories; + } + + return instance; } /// <summary> diff --git a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj index c0ec53b..6148241 100644 --- a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj +++ b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj @@ -20,14 +20,20 @@ </PropertyGroup> <ItemGroup> <Compile Include="Assumes.cs" /> + <Compile Include="IHostFactories.cs" /> + <Compile Include="IRequireHostFactories.cs" /> + <Compile Include="MachineKeyUtil.cs" /> <Compile Include="Messaging\Base64WebEncoder.cs" /> <Compile Include="Messaging\Bindings\AsymmetricCryptoKeyStoreWrapper.cs" /> <Compile Include="Messaging\Bindings\CryptoKey.cs" /> <Compile Include="Messaging\Bindings\CryptoKeyCollisionException.cs" /> + <Compile Include="Messaging\Bindings\HardCodedKeyCryptoKeyStore.cs" /> <Compile Include="Messaging\Bindings\ICryptoKeyStore.cs" /> <Compile Include="Messaging\Bindings\MemoryCryptoKeyStore.cs" /> <Compile Include="Messaging\BinaryDataBagFormatter.cs" /> - <Compile Include="Messaging\CachedDirectWebResponse.cs" /> + <Compile Include="Messaging\HttpResponseMessageWithOriginal.cs" /> + <Compile Include="Messaging\MessageProtectionTasks.cs" /> + <Compile Include="Messaging\MultipartContentMember.cs" /> <Compile Include="Messaging\DataBagFormatterBase.cs" /> <Compile Include="Messaging\HmacAlgorithms.cs" /> <Compile Include="Messaging\HttpRequestHeaders.cs" /> @@ -40,7 +46,6 @@ <Compile Include="Messaging\IHttpDirectResponse.cs" /> <Compile Include="Messaging\IExtensionMessage.cs" /> <Compile Include="Messaging\IMessage.cs" /> - <Compile Include="Messaging\IncomingWebResponse.cs" /> <Compile Include="Messaging\IDirectResponseProtocolMessage.cs" /> <Compile Include="Messaging\EmptyDictionary.cs" /> <Compile Include="Messaging\EmptyEnumerator.cs" /> @@ -51,9 +56,6 @@ <Compile Include="Messaging\InternalErrorException.cs" /> <Compile Include="Messaging\IStreamSerializingDataBag.cs" /> <Compile Include="Messaging\KeyedCollectionDelegate.cs" /> - <Compile Include="Messaging\MultipartPostPart.cs" /> - <Compile Include="Messaging\NetworkDirectWebResponse.cs" /> - <Compile Include="Messaging\OutgoingWebResponseActionResult.cs" /> <Compile Include="Messaging\ProtocolFaultResponseException.cs" /> <Compile Include="Messaging\Reflection\IMessagePartEncoder.cs" /> <Compile Include="Messaging\Reflection\IMessagePartFormattingEncoder.cs" /> @@ -70,7 +72,6 @@ <Compile Include="Messaging\IMessageWithBinaryData.cs" /> <Compile Include="Messaging\ChannelEventArgs.cs" /> <Compile Include="Messaging\Bindings\NonceMemoryStore.cs" /> - <Compile Include="Messaging\IDirectWebRequestHandler.cs" /> <Compile Include="Messaging\Bindings\INonceStore.cs" /> <Compile Include="Messaging\Bindings\StandardReplayProtectionBindingElement.cs" /> <Compile Include="Messaging\MessagePartAttribute.cs" /> @@ -99,14 +100,11 @@ <Compile Include="Messaging\Reflection\MessageDictionary.cs" /> <Compile Include="Messaging\Reflection\MessagePart.cs" /> <Compile Include="Messaging\UnprotectedMessageException.cs" /> - <Compile Include="Messaging\OutgoingWebResponse.cs" /> <Compile Include="Messaging\IProtocolMessage.cs" /> <Compile Include="Messaging\HttpDeliveryMethods.cs" /> <Compile Include="Messaging\MessageTransport.cs" /> <Compile Include="Messaging\ProtocolException.cs" /> <Compile Include="Messaging\TimespanSecondsEncoder.cs" /> - <Compile Include="Messaging\UntrustedWebRequestHandler.cs" /> - <Compile Include="Messaging\StandardWebRequestHandler.cs" /> <Compile Include="Messaging\MessageReceivingEndpoint.cs" /> </ItemGroup> <ItemGroup> @@ -178,33 +176,32 @@ </Reference> <Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http.WebRequest" /> - <Reference Include="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.Helpers.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.Helpers.dll</HintPath> </Reference> - <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.Mvc.3.0.20105.1\lib\net40\System.Web.Mvc.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.Mvc.4.0.20710.0\lib\net40\System.Web.Mvc.dll</HintPath> </Reference> - <Reference Include="System.Web.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.Razor.1.0.20105.408\lib\net40\System.Web.Razor.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.Razor.2.0.20715.0\lib\net40\System.Web.Razor.dll</HintPath> </Reference> - <Reference Include="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.WebPages.dll</HintPath> </Reference> - <Reference Include="System.Web.WebPages.Deployment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> </Reference> - <Reference Include="System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.WebPages.Razor.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath> </Reference> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> diff --git a/src/DotNetOpenAuth.Core/IHostFactories.cs b/src/DotNetOpenAuth.Core/IHostFactories.cs new file mode 100644 index 0000000..d171ed8 --- /dev/null +++ b/src/DotNetOpenAuth.Core/IHostFactories.cs @@ -0,0 +1,41 @@ +//----------------------------------------------------------------------- +// <copyright file="IHostFactories.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + + /// <summary> + /// Provides the host application or tests with the ability to create standard message handlers or stubs. + /// </summary> + public interface IHostFactories { + /// <summary> + /// Initializes a new instance of a concrete derivation of <see cref="HttpMessageHandler"/> + /// to be used for outbound HTTP traffic. + /// </summary> + /// <returns>An instance of <see cref="HttpMessageHandler"/>.</returns> + /// <remarks> + /// An instance of <see cref="WebRequestHandler"/> is recommended where available; + /// otherwise an instance of <see cref="HttpClientHandler"/> is recommended. + /// </remarks> + HttpMessageHandler CreateHttpMessageHandler(); + + /// <summary> + /// Initializes a new instance of the <see cref="HttpClient"/> class + /// to be used for outbound HTTP traffic. + /// </summary> + /// <param name="handler"> + /// The handler to pass to the <see cref="HttpClient"/> constructor. + /// May be null to use the default that would be provided by <see cref="CreateHttpMessageHandler"/>. + /// </param> + /// <returns>An instance of <see cref="HttpClient"/>.</returns> + HttpClient CreateHttpClient(HttpMessageHandler handler = null); + } +} diff --git a/src/DotNetOpenAuth.Core/IRequireHostFactories.cs b/src/DotNetOpenAuth.Core/IRequireHostFactories.cs new file mode 100644 index 0000000..60fa970 --- /dev/null +++ b/src/DotNetOpenAuth.Core/IRequireHostFactories.cs @@ -0,0 +1,20 @@ +//----------------------------------------------------------------------- +// <copyright file="IRequireHostFactories.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth { + /// <summary> + /// An interface implemented by DotNetOpenAuth extensions that need to create host-specific instances of specific interfaces. + /// </summary> + public interface IRequireHostFactories { + /// <summary> + /// Gets or sets the host factories used by this instance. + /// </summary> + /// <value> + /// The host factories. + /// </value> + IHostFactories HostFactories { get; set; } + } +} diff --git a/src/DotNetOpenAuth.Core/Loggers/Log4NetLogger.cs b/src/DotNetOpenAuth.Core/Loggers/Log4NetLogger.cs index 293a6b2..01da034 100644 --- a/src/DotNetOpenAuth.Core/Loggers/Log4NetLogger.cs +++ b/src/DotNetOpenAuth.Core/Loggers/Log4NetLogger.cs @@ -201,6 +201,8 @@ namespace DotNetOpenAuth.Loggers { return IsLog4NetPresent ? CreateLogger(name) : null; } catch (FileLoadException) { // wrong log4net.dll version return null; + } catch (TargetInvocationException) { // Thrown due to some security issues on .NET 4.5. + return null; } catch (TypeLoadException) { // Thrown by mono (http://stackoverflow.com/questions/10805773/error-when-pushing-dotnetopenauth-to-staging-or-production-environment) return null; } diff --git a/src/DotNetOpenAuth.AspNet/MachineKeyUtil.cs b/src/DotNetOpenAuth.Core/MachineKeyUtil.cs index eb2020b..eceb38c 100644 --- a/src/DotNetOpenAuth.AspNet/MachineKeyUtil.cs +++ b/src/DotNetOpenAuth.Core/MachineKeyUtil.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace DotNetOpenAuth.AspNet { +namespace DotNetOpenAuth { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -183,7 +183,7 @@ namespace DotNetOpenAuth.AspNet { } // if we reached this point, some cryptographic operation failed - throw new CryptographicException(WebResources.Generic_CryptoFailure); + throw new CryptographicException(Strings.Generic_CryptoFailure); } /// <summary> diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/HardCodedKeyCryptoKeyStore.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/HardCodedKeyCryptoKeyStore.cs new file mode 100644 index 0000000..c828616 --- /dev/null +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/HardCodedKeyCryptoKeyStore.cs @@ -0,0 +1,98 @@ +//----------------------------------------------------------------------- +// <copyright file="HardCodedKeyCryptoKeyStore.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging.Bindings { + using System; + using System.Collections.Generic; + using Validation; + + /// <summary> + /// A trivial implementation of <see cref="ICryptoKeyStore"/> that has only one fixed key. + /// This is meant for simple, low-security applications. Greater security requires an + /// implementation of <see cref="ICryptoKeyStore"/> that actually stores and retrieves + /// keys from a persistent store. + /// </summary> + public class HardCodedKeyCryptoKeyStore : ICryptoKeyStore { + /// <summary> + /// The handle to report for the hard-coded key. + /// </summary> + private const string HardCodedKeyHandle = "fxd"; + + /// <summary> + /// The one crypto key singleton instance. + /// </summary> + private readonly CryptoKey OneCryptoKey; + + /// <summary> + /// Initializes a new instance of the <see cref="HardCodedKeyCryptoKeyStore"/> class. + /// </summary> + /// <param name="secretAsBase64">The 256-bit secret as a base64 encoded string.</param> + public HardCodedKeyCryptoKeyStore(string secretAsBase64) + : this(Convert.FromBase64String(Requires.NotNull(secretAsBase64, "secretAsBase64"))) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="HardCodedKeyCryptoKeyStore"/> class. + /// </summary> + /// <param name="secret">The 256-bit secret.</param> + public HardCodedKeyCryptoKeyStore(byte[] secret) { + Requires.NotNull(secret, "secret"); + this.OneCryptoKey = new CryptoKey(secret, DateTime.MaxValue.AddDays(-2).ToUniversalTime()); + } + + #region ICryptoKeyStore Members + + /// <summary> + /// Gets the key in a given bucket and handle. + /// </summary> + /// <param name="bucket">The bucket name. Case sensitive.</param> + /// <param name="handle">The key handle. Case sensitive.</param> + /// <returns> + /// The cryptographic key, or <c>null</c> if no matching key was found. + /// </returns> + public CryptoKey GetKey(string bucket, string handle) { + if (handle == HardCodedKeyHandle) { + return OneCryptoKey; + } + + return null; + } + + /// <summary> + /// Gets a sequence of existing keys within a given bucket. + /// </summary> + /// <param name="bucket">The bucket name. Case sensitive.</param> + /// <returns> + /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc" />. + /// </returns> + public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) { + return new[] { new KeyValuePair<string, CryptoKey>(HardCodedKeyHandle, OneCryptoKey) }; + } + + /// <summary> + /// Stores a cryptographic key. + /// </summary> + /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param> + /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param> + /// <param name="key">The key to store.</param> + /// <exception cref="System.NotSupportedException"></exception> + public void StoreKey(string bucket, string handle, CryptoKey key) { + throw new NotSupportedException(); + } + + /// <summary> + /// Removes the key. + /// </summary> + /// <param name="bucket">The bucket name. Case sensitive.</param> + /// <param name="handle">The key handle. Case sensitive.</param> + /// <exception cref="System.NotSupportedException"></exception> + public void RemoveKey(string bucket, string handle) { + throw new NotSupportedException(); + } + + #endregion + } +}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardExpirationBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardExpirationBindingElement.cs index 7ab78db..f19d4bd 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardExpirationBindingElement.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardExpirationBindingElement.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Configuration; /// <summary> @@ -14,6 +16,16 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// </summary> internal class StandardExpirationBindingElement : IChannelBindingElement { /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> CompletedExpirationTask = Task.FromResult<MessageProtections?>(MessageProtections.Expiration); + + /// <summary> /// Initializes a new instance of the <see cref="StandardExpirationBindingElement"/> class. /// </summary> internal StandardExpirationBindingElement() { @@ -51,24 +63,30 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// Sets the timestamp on an outgoing message. /// </summary> /// <param name="message">The outgoing message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection" /> properties where applicable. + /// </remarks> + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage; if (expiringMessage != null) { expiringMessage.UtcCreationDate = DateTime.UtcNow; - return MessageProtections.Expiration; + return CompletedExpirationTask; } - return null; + return NullTask; } /// <summary> /// Reads the timestamp on a message and throws an exception if the message is too old. /// </summary> /// <param name="message">The incoming message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -78,7 +96,7 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// Thrown when the binding element rules indicate that this message is invalid and should /// NOT be processed. /// </exception> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage; if (expiringMessage != null) { // Yes the UtcCreationDate is supposed to always be in UTC already, @@ -96,10 +114,10 @@ namespace DotNetOpenAuth.Messaging.Bindings { MessagingStrings.MessageTimestampInFuture, creationDate); - return MessageProtections.Expiration; + return CompletedExpirationTask; } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs index 45bccdf..65c7882 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Bindings/StandardReplayProtectionBindingElement.cs @@ -7,6 +7,8 @@ namespace DotNetOpenAuth.Messaging.Bindings { using System; using System.Diagnostics; + using System.Threading; + using System.Threading.Tasks; using Validation; /// <summary> @@ -14,6 +16,16 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// </summary> internal class StandardReplayProtectionBindingElement : IChannelBindingElement { /// <summary> + /// A reusable, precompleted task that can be returned many times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A reusable, precompleted task that can be returned many times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> CompletedReplayProtectionTask = Task.FromResult<MessageProtections?>(MessageProtections.ReplayProtection); + + /// <summary> /// These are the characters that may be chosen from when forming a random nonce. /// </summary> private const string AllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; @@ -96,30 +108,36 @@ namespace DotNetOpenAuth.Messaging.Bindings { /// Applies a nonce to the message. /// </summary> /// <param name="message">The message to apply replay protection to.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage; if (nonceMessage != null) { nonceMessage.Nonce = this.GenerateUniqueFragment(); - return MessageProtections.ReplayProtection; + return CompletedReplayProtectionTask; } - return null; + return NullTask; } /// <summary> /// Verifies that the nonce in an incoming message has not been seen before. /// </summary> /// <param name="message">The incoming message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> /// <exception cref="ReplayedMessageException">Thrown when the nonce check revealed a replayed message.</exception> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + /// <remarks> + /// Implementations that provide message protection must honor the + /// <see cref="MessagePartAttribute.RequiredProtection" /> properties where applicable. + /// </remarks> + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage; if (nonceMessage != null && nonceMessage.Nonce != null) { ErrorUtilities.VerifyProtocol(nonceMessage.Nonce.Length > 0 || this.AllowZeroLengthNonce, MessagingStrings.InvalidNonceReceived); @@ -129,10 +147,10 @@ namespace DotNetOpenAuth.Messaging.Bindings { throw new ReplayedMessageException(message); } - return MessageProtections.ReplayProtection; + return CompletedReplayProtectionTask; } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs deleted file mode 100644 index 20b1831..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/CachedDirectWebResponse.cs +++ /dev/null @@ -1,182 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CachedDirectWebResponse.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.IO; - using System.Net; - using System.Text; - using Validation; - - /// <summary> - /// Cached details on the response from a direct web request to a remote party. - /// </summary> - [DebuggerDisplay("{Status} {ContentType.MediaType}, length: {ResponseStream.Length}")] - internal class CachedDirectWebResponse : IncomingWebResponse { - /// <summary> - /// A seekable, repeatable response stream. - /// </summary> - private MemoryStream responseStream; - - /// <summary> - /// Initializes a new instance of the <see cref="CachedDirectWebResponse"/> class. - /// </summary> - internal CachedDirectWebResponse() { - } - - /// <summary> - /// Initializes a new instance of the <see cref="CachedDirectWebResponse"/> class. - /// </summary> - /// <param name="requestUri">The request URI.</param> - /// <param name="response">The response.</param> - /// <param name="maximumBytesToRead">The maximum bytes to read.</param> - internal CachedDirectWebResponse(Uri requestUri, HttpWebResponse response, int maximumBytesToRead) - : base(requestUri, response) { - Requires.NotNull(requestUri, "requestUri"); - Requires.NotNull(response, "response"); - this.responseStream = CacheNetworkStreamAndClose(response, maximumBytesToRead); - - // BUGBUG: if the response was exactly maximumBytesToRead, we'll incorrectly believe it was truncated. - this.ResponseTruncated = this.responseStream.Length == maximumBytesToRead; - } - - /// <summary> - /// Initializes a new instance of the <see cref="CachedDirectWebResponse"/> class. - /// </summary> - /// <param name="requestUri">The request URI.</param> - /// <param name="responseUri">The final URI to respond to the request.</param> - /// <param name="headers">The headers.</param> - /// <param name="statusCode">The status code.</param> - /// <param name="contentType">Type of the content.</param> - /// <param name="contentEncoding">The content encoding.</param> - /// <param name="responseStream">The response stream.</param> - internal CachedDirectWebResponse(Uri requestUri, Uri responseUri, WebHeaderCollection headers, HttpStatusCode statusCode, string contentType, string contentEncoding, MemoryStream responseStream) - : base(requestUri, responseUri, headers, statusCode, contentType, contentEncoding) { - Requires.NotNull(requestUri, "requestUri"); - Requires.NotNull(responseStream, "responseStream"); - this.responseStream = responseStream; - } - - /// <summary> - /// Gets a value indicating whether the cached response stream was - /// truncated to a maximum allowable length. - /// </summary> - public bool ResponseTruncated { get; private set; } - - /// <summary> - /// Gets the body of the HTTP response. - /// </summary> - public override Stream ResponseStream { - get { return this.responseStream; } - } - - /// <summary> - /// Gets or sets the cached response stream. - /// </summary> - internal MemoryStream CachedResponseStream { - get { return this.responseStream; } - set { this.responseStream = value; } - } - - /// <summary> - /// Creates a text reader for the response stream. - /// </summary> - /// <returns>The text reader, initialized for the proper encoding.</returns> - public override StreamReader GetResponseReader() { - this.ResponseStream.Seek(0, SeekOrigin.Begin); - string contentEncoding = this.Headers[HttpResponseHeader.ContentEncoding]; - Encoding encoding = null; - if (!string.IsNullOrEmpty(contentEncoding)) { - try { - encoding = Encoding.GetEncoding(contentEncoding); - } catch (ArgumentException ex) { - Logger.Messaging.ErrorFormat("Encoding.GetEncoding(\"{0}\") threw ArgumentException: {1}", contentEncoding, ex); - } - } - - return encoding != null ? new StreamReader(this.ResponseStream, encoding) : new StreamReader(this.ResponseStream); - } - - /// <summary> - /// Gets the body of the response as a string. - /// </summary> - /// <returns>The entire body of the response.</returns> - internal string GetResponseString() { - if (this.ResponseStream != null) { - string value = this.GetResponseReader().ReadToEnd(); - this.ResponseStream.Seek(0, SeekOrigin.Begin); - return value; - } else { - return null; - } - } - - /// <summary> - /// Gets an offline snapshot version of this instance. - /// </summary> - /// <param name="maximumBytesToCache">The maximum bytes from the response stream to cache.</param> - /// <returns>A snapshot version of this instance.</returns> - /// <remarks> - /// If this instance is a <see cref="NetworkDirectWebResponse"/> creating a snapshot - /// will automatically close and dispose of the underlying response stream. - /// If this instance is a <see cref="CachedDirectWebResponse"/>, the result will - /// be the self same instance. - /// </remarks> - internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) { - return this; - } - - /// <summary> - /// Sets the response to some string, encoded as UTF-8. - /// </summary> - /// <param name="body">The string to set the response to.</param> - internal void SetResponse(string body) { - if (body == null) { - this.responseStream = null; - return; - } - - Encoding encoding = Encoding.UTF8; - this.Headers[HttpResponseHeader.ContentEncoding] = encoding.HeaderName; - this.responseStream = new MemoryStream(); - StreamWriter writer = new StreamWriter(this.ResponseStream, encoding); - writer.Write(body); - writer.Flush(); - this.ResponseStream.Seek(0, SeekOrigin.Begin); - } - - /// <summary> - /// Caches the network stream and closes it if it is open. - /// </summary> - /// <param name="response">The response whose stream is to be cloned.</param> - /// <param name="maximumBytesToRead">The maximum bytes to cache.</param> - /// <returns>The seekable Stream instance that contains a copy of what was returned in the HTTP response.</returns> - [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Assume(System.Boolean,System.String,System.String)", Justification = "No localization required.")] - private static MemoryStream CacheNetworkStreamAndClose(HttpWebResponse response, int maximumBytesToRead) { - Requires.NotNull(response, "response"); - - // Now read and cache the network stream - Stream networkStream = response.GetResponseStream(); - MemoryStream cachedStream = new MemoryStream(response.ContentLength < 0 ? 4 * 1024 : Math.Min((int)response.ContentLength, maximumBytesToRead)); - try { - Assumes.True(networkStream.CanRead, "HttpWebResponse.GetResponseStream() always returns a readable stream."); // CC missing - Assumes.True(cachedStream.CanWrite, "This is a MemoryStream -- it's always writable."); // CC missing - networkStream.CopyTo(cachedStream); - cachedStream.Seek(0, SeekOrigin.Begin); - - networkStream.Dispose(); - response.Close(); - - return cachedStream; - } catch { - cachedStream.Dispose(); - throw; - } - } - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/Channel.cs b/src/DotNetOpenAuth.Core/Messaging/Channel.cs index 9c2ba8c..9414166 100644 --- a/src/DotNetOpenAuth.Core/Messaging/Channel.cs +++ b/src/DotNetOpenAuth.Core/Messaging/Channel.cs @@ -17,10 +17,14 @@ namespace DotNetOpenAuth.Messaging { using System.Linq; using System.Net; using System.Net.Cache; + using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; + using System.Net.Sockets; using System.Runtime.Serialization.Json; using System.Text; using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Xml; using DotNetOpenAuth.Messaging.Reflection; @@ -136,31 +140,25 @@ namespace DotNetOpenAuth.Messaging { private IMessageFactory messageTypeProvider; /// <summary> - /// Backing store for the <see cref="CachePolicy"/> property. - /// </summary> - private RequestCachePolicy cachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); - - /// <summary> /// Backing field for the <see cref="MaximumIndirectMessageUrlLength"/> property. /// </summary> private int maximumIndirectMessageUrlLength = Configuration.DotNetOpenAuthSection.Messaging.MaximumIndirectMessageUrlLength; /// <summary> - /// Initializes a new instance of the <see cref="Channel"/> class. + /// Initializes a new instance of the <see cref="Channel" /> class. /// </summary> - /// <param name="messageTypeProvider"> - /// A class prepared to analyze incoming messages and indicate what concrete - /// message types can deserialize from it. - /// </param> - /// <param name="bindingElements"> - /// The binding elements to use in sending and receiving messages. - /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages. - /// </param> - protected Channel(IMessageFactory messageTypeProvider, params IChannelBindingElement[] bindingElements) { + /// <param name="messageTypeProvider">A class prepared to analyze incoming messages and indicate what concrete + /// message types can deserialize from it.</param> + /// <param name="bindingElements">The binding elements to use in sending and receiving messages. + /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages.</param> + /// <param name="hostFactories">The host factories.</param> + protected Channel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements, IHostFactories hostFactories) { Requires.NotNull(messageTypeProvider, "messageTypeProvider"); + Requires.NotNull(bindingElements, "bindingElements"); + Requires.NotNull(hostFactories, "hostFactories"); this.messageTypeProvider = messageTypeProvider; - this.WebRequestHandler = new StandardWebRequestHandler(); + this.HostFactories = hostFactories; this.XmlDictionaryReaderQuotas = DefaultUntrustedXmlDictionaryReaderQuotas; this.outgoingBindingElements = new List<IChannelBindingElement>(ValidateAndPrepareBindingElements(bindingElements)); @@ -178,14 +176,9 @@ namespace DotNetOpenAuth.Messaging { internal event EventHandler<ChannelEventArgs> Sending; /// <summary> - /// Gets or sets an instance to a <see cref="IDirectWebRequestHandler"/> that will be used when - /// submitting HTTP requests and waiting for responses. + /// Gets the host factories instance to use. /// </summary> - /// <remarks> - /// This defaults to a straightforward implementation, but can be set - /// to a mock object for testing purposes. - /// </remarks> - public IDirectWebRequestHandler WebRequestHandler { get; set; } + public IHostFactories HostFactories { get; private set; } /// <summary> /// Gets or sets the maximum allowable size for a 301 Redirect response before we send @@ -272,75 +265,25 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> - /// Gets or sets the cache policy to use for direct message requests. - /// </summary> - /// <value>Default is <see cref="HttpRequestCacheLevel.NoCacheNoStore"/>.</value> - protected RequestCachePolicy CachePolicy { - get { - return this.cachePolicy; - } - - set { - Requires.NotNull(value, "value"); - this.cachePolicy = value; - } - } - - /// <summary> /// Gets or sets the XML dictionary reader quotas. /// </summary> /// <value>The XML dictionary reader quotas.</value> protected virtual XmlDictionaryReaderQuotas XmlDictionaryReaderQuotas { get; set; } /// <summary> - /// Sends an indirect message (either a request or response) - /// or direct message response for transmission to a remote party - /// and ends execution on the current page or handler. - /// </summary> - /// <param name="message">The one-way message to send</param> - /// <exception cref="ThreadAbortException">Thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception> - /// <remarks> - /// Requires an HttpContext.Current context. - /// </remarks> - [EditorBrowsable(EditorBrowsableState.Never)] - public void Send(IProtocolMessage message) { - RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); - Requires.NotNull(message, "message"); - this.PrepareResponse(message).Respond(HttpContext.Current, true); - } - - /// <summary> - /// Sends an indirect message (either a request or response) - /// or direct message response for transmission to a remote party - /// and skips most of the remaining ASP.NET request handling pipeline. - /// Not safe to call from ASP.NET web forms. - /// </summary> - /// <param name="message">The one-way message to send</param> - /// <remarks> - /// Requires an HttpContext.Current context. - /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because - /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response. - /// Use the <see cref="Send"/> method instead for web forms. - /// </remarks> - public void Respond(IProtocolMessage message) { - RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); - Requires.NotNull(message, "message"); - this.PrepareResponse(message).Respond(); - } - - /// <summary> /// Prepares an indirect message (either a request or response) /// or direct message response for transmission to a remote party. /// </summary> /// <param name="message">The one-way message to send</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> - public OutgoingWebResponse PrepareResponse(IProtocolMessage message) { + public async Task<HttpResponseMessage> PrepareResponseAsync(IProtocolMessage message, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(message, "message"); - this.ProcessOutgoingMessage(message); + await this.ProcessOutgoingMessageAsync(message, cancellationToken); Logger.Channel.DebugFormat("Sending message: {0}", message.GetType().Name); - OutgoingWebResponse result; + HttpResponseMessage result; switch (message.Transport) { case MessageTransport.Direct: // This is a response to a direct message. @@ -369,8 +312,13 @@ namespace DotNetOpenAuth.Messaging { // Apply caching policy to any response. We want to disable all caching because in auth* protocols, // caching can be utilized in identity spoofing attacks. - result.Headers[HttpResponseHeader.CacheControl] = "no-cache, no-store, max-age=0, must-revalidate"; - result.Headers[HttpResponseHeader.Pragma] = "no-cache"; + result.Headers.CacheControl = new CacheControlHeaderValue { + NoCache = true, + NoStore = true, + MaxAge = TimeSpan.Zero, + MustRevalidate = true, + }; + result.Headers.Pragma.Add(new NameValueHeaderValue("no-cache")); return result; } @@ -378,114 +326,74 @@ namespace DotNetOpenAuth.Messaging { /// <summary> /// Gets the protocol message embedded in the given HTTP request, if present. /// </summary> - /// <returns>The deserialized message, if one is found. Null otherwise.</returns> - /// <remarks> - /// Requires an HttpContext.Current context. - /// </remarks> - /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> - public IDirectedProtocolMessage ReadFromRequest() { - return this.ReadFromRequest(this.GetRequestFromContext()); - } - - /// <summary> - /// Gets the protocol message embedded in the given HTTP request, if present. - /// </summary> - /// <typeparam name="TRequest">The expected type of the message to be received.</typeparam> - /// <param name="request">The deserialized message, if one is found. Null otherwise.</param> - /// <returns>True if the expected message was recognized and deserialized. False otherwise.</returns> - /// <remarks> - /// Requires an HttpContext.Current context. - /// </remarks> - /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> - /// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception> - public bool TryReadFromRequest<TRequest>(out TRequest request) - where TRequest : class, IProtocolMessage { - return TryReadFromRequest<TRequest>(this.GetRequestFromContext(), out request); - } - - /// <summary> - /// Gets the protocol message embedded in the given HTTP request, if present. - /// </summary> /// <typeparam name="TRequest">The expected type of the message to be received.</typeparam> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="httpRequest">The request to search for an embedded message.</param> - /// <param name="request">The deserialized message, if one is found. Null otherwise.</param> - /// <returns>True if the expected message was recognized and deserialized. False otherwise.</returns> - /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> + /// <returns> + /// True if the expected message was recognized and deserialized. False otherwise. + /// </returns> + /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current" /> is null.</exception> /// <exception cref="ProtocolException">Thrown when a request message of an unexpected type is received.</exception> - public bool TryReadFromRequest<TRequest>(HttpRequestBase httpRequest, out TRequest request) + public async Task<TRequest> TryReadFromRequestAsync<TRequest>(HttpRequestMessage httpRequest, CancellationToken cancellationToken) where TRequest : class, IProtocolMessage { Requires.NotNull(httpRequest, "httpRequest"); - IProtocolMessage untypedRequest = this.ReadFromRequest(httpRequest); + IProtocolMessage untypedRequest = await this.ReadFromRequestAsync(httpRequest, cancellationToken); if (untypedRequest == null) { - request = null; - return false; + return null; } - request = untypedRequest as TRequest; + var request = untypedRequest as TRequest; ErrorUtilities.VerifyProtocol(request != null, MessagingStrings.UnexpectedMessageReceived, typeof(TRequest), untypedRequest.GetType()); - - return true; - } - - /// <summary> - /// Gets the protocol message embedded in the current HTTP request. - /// </summary> - /// <typeparam name="TRequest">The expected type of the message to be received.</typeparam> - /// <returns>The deserialized message. Never null.</returns> - /// <remarks> - /// Requires an HttpContext.Current context. - /// </remarks> - /// <exception cref="InvalidOperationException">Thrown when <see cref="HttpContext.Current"/> is null.</exception> - /// <exception cref="ProtocolException">Thrown if the expected message was not recognized in the response.</exception> - [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "This returns and verifies the appropriate message type.")] - public TRequest ReadFromRequest<TRequest>() - where TRequest : class, IProtocolMessage { - return this.ReadFromRequest<TRequest>(this.GetRequestFromContext()); + return request; } /// <summary> /// Gets the protocol message embedded in the given HTTP request. /// </summary> /// <typeparam name="TRequest">The expected type of the message to be received.</typeparam> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="httpRequest">The request to search for an embedded message.</param> - /// <returns>The deserialized message. Never null.</returns> + /// <returns> + /// The deserialized message. Never null. + /// </returns> /// <exception cref="ProtocolException">Thrown if the expected message was not recognized in the response.</exception> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "This returns and verifies the appropriate message type.")] - public TRequest ReadFromRequest<TRequest>(HttpRequestBase httpRequest) + public async Task<TRequest> ReadFromRequestAsync<TRequest>(HttpRequestMessage httpRequest, CancellationToken cancellationToken) where TRequest : class, IProtocolMessage { Requires.NotNull(httpRequest, "httpRequest"); - TRequest request; - if (this.TryReadFromRequest<TRequest>(httpRequest, out request)) { - return request; - } else { - throw ErrorUtilities.ThrowProtocol(MessagingStrings.ExpectedMessageNotReceived, typeof(TRequest)); - } + + TRequest request = await this.TryReadFromRequestAsync<TRequest>(httpRequest, cancellationToken); + ErrorUtilities.VerifyProtocol(request != null, MessagingStrings.ExpectedMessageNotReceived, typeof(TRequest)); + return request; } /// <summary> /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="httpRequest">The request to search for an embedded message.</param> - /// <returns>The deserialized message, if one is found. Null otherwise.</returns> - public IDirectedProtocolMessage ReadFromRequest(HttpRequestBase httpRequest) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The deserialized message, if one is found. Null otherwise. + /// </returns> + public async Task<IDirectedProtocolMessage> ReadFromRequestAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken) { Requires.NotNull(httpRequest, "httpRequest"); - if (Logger.Channel.IsInfoEnabled && httpRequest.GetPublicFacingUrl() != null) { - Logger.Channel.InfoFormat("Scanning incoming request for messages: {0}", httpRequest.GetPublicFacingUrl().AbsoluteUri); + if (Logger.Channel.IsInfoEnabled && httpRequest.RequestUri != null) { + Logger.Channel.InfoFormat("Scanning incoming request for messages: {0}", httpRequest.RequestUri.AbsoluteUri); } - IDirectedProtocolMessage requestMessage = this.ReadFromRequestCore(httpRequest); + IDirectedProtocolMessage requestMessage = await this.ReadFromRequestCoreAsync(httpRequest, cancellationToken); if (requestMessage != null) { Logger.Channel.DebugFormat("Incoming request received: {0}", requestMessage.GetType().Name); var directRequest = requestMessage as IHttpDirectRequest; if (directRequest != null) { - foreach (string header in httpRequest.Headers) { - directRequest.Headers[header] = httpRequest.Headers[header]; + foreach (var header in httpRequest.Headers) { + directRequest.Headers.Add(header.Key, header.Value); } } - this.ProcessIncomingMessage(requestMessage); + await this.ProcessIncomingMessageAsync(requestMessage, cancellationToken); } return requestMessage; @@ -496,17 +404,18 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <typeparam name="TResponse">The expected type of the message to be received.</typeparam> /// <param name="requestMessage">The message to send.</param> - /// <returns>The remote party's response.</returns> - /// <exception cref="ProtocolException"> - /// Thrown if no message is recognized in the response - /// or an unexpected type of message is received. - /// </exception> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The remote party's response. + /// </returns> + /// <exception cref="ProtocolException">Thrown if no message is recognized in the response + /// or an unexpected type of message is received.</exception> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "This returns and verifies the appropriate message type.")] - public TResponse Request<TResponse>(IDirectedProtocolMessage requestMessage) + public async Task<TResponse> RequestAsync<TResponse>(IDirectedProtocolMessage requestMessage, CancellationToken cancellationToken) where TResponse : class, IProtocolMessage { Requires.NotNull(requestMessage, "requestMessage"); - IProtocolMessage response = this.Request(requestMessage); + IProtocolMessage response = await this.RequestAsync(requestMessage, cancellationToken); ErrorUtilities.VerifyProtocol(response != null, MessagingStrings.ExpectedMessageNotReceived, typeof(TResponse)); var expectedResponse = response as TResponse; @@ -519,18 +428,21 @@ namespace DotNetOpenAuth.Messaging { /// Sends a direct message to a remote party and waits for the response. /// </summary> /// <param name="requestMessage">The message to send.</param> - /// <returns>The remote party's response. Guaranteed to never be null.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The remote party's response. Guaranteed to never be null. + /// </returns> /// <exception cref="ProtocolException">Thrown if the response does not include a protocol message.</exception> - public IProtocolMessage Request(IDirectedProtocolMessage requestMessage) { + public async Task<IProtocolMessage> RequestAsync(IDirectedProtocolMessage requestMessage, CancellationToken cancellationToken) { Requires.NotNull(requestMessage, "requestMessage"); - this.ProcessOutgoingMessage(requestMessage); + await this.ProcessOutgoingMessageAsync(requestMessage, cancellationToken); Logger.Channel.DebugFormat("Sending {0} request.", requestMessage.GetType().Name); - var responseMessage = this.RequestCore(requestMessage); + var responseMessage = await this.RequestCoreAsync(requestMessage, cancellationToken); ErrorUtilities.VerifyProtocol(responseMessage != null, MessagingStrings.ExpectedMessageNotReceived, typeof(IProtocolMessage).Name); Logger.Channel.DebugFormat("Received {0} response.", responseMessage.GetType().Name); - this.ProcessIncomingMessage(responseMessage); + await this.ProcessIncomingMessageAsync(responseMessage, cancellationToken); return responseMessage; } @@ -551,12 +463,14 @@ namespace DotNetOpenAuth.Messaging { /// Verifies the integrity and applicability of an incoming message. /// </summary> /// <param name="message">The message just received.</param> - /// <exception cref="ProtocolException"> - /// Thrown when the message is somehow invalid. - /// This can be due to tampering, replay attack or expiration, among other things. - /// </exception> - internal void ProcessIncomingMessageTestHook(IProtocolMessage message) { - this.ProcessIncomingMessage(message); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + /// <exception cref="ProtocolException">Thrown when the message is somehow invalid. + /// This can be due to tampering, replay attack or expiration, among other things.</exception> + internal Task ProcessIncomingMessageTestHookAsync(IProtocolMessage message, CancellationToken cancellationToken) { + return this.ProcessIncomingMessageAsync(message, cancellationToken); } /// <summary> @@ -565,10 +479,10 @@ namespace DotNetOpenAuth.Messaging { /// <param name="request">The message to send.</param> /// <returns>The <see cref="HttpWebRequest"/> prepared to send the request.</returns> /// <remarks> - /// This method must be overridden by a derived class, unless the <see cref="RequestCore"/> method + /// This method must be overridden by a derived class, unless the <see cref="RequestCoreAsync"/> method /// is overridden and does not require this method. /// </remarks> - internal HttpWebRequest CreateHttpRequestTestHook(IDirectedProtocolMessage request) { + internal HttpRequestMessage CreateHttpRequestTestHook(IDirectedProtocolMessage request) { return this.CreateHttpRequest(request); } @@ -581,7 +495,7 @@ namespace DotNetOpenAuth.Messaging { /// <remarks> /// This method implements spec OAuth V1.0 section 5.3. /// </remarks> - internal OutgoingWebResponse PrepareDirectResponseTestHook(IProtocolMessage response) { + internal HttpResponseMessage PrepareDirectResponseTestHook(IProtocolMessage response) { return this.PrepareDirectResponse(response); } @@ -591,20 +505,39 @@ namespace DotNetOpenAuth.Messaging { /// <param name="response">The response that is anticipated to contain an protocol message.</param> /// <returns>The deserialized message parts, if found. Null otherwise.</returns> /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> - internal IDictionary<string, string> ReadFromResponseCoreTestHook(IncomingWebResponse response) { - return this.ReadFromResponseCore(response); + internal Task<IDictionary<string, string>> ReadFromResponseCoreAsyncTestHook(HttpResponseMessage response, CancellationToken cancellationToken) { + return this.ReadFromResponseCoreAsync(response, cancellationToken); } - /// <remarks> - /// This method should NOT be called by derived types - /// except when sending ONE WAY request messages. - /// </remarks> /// <summary> /// Prepares a message for transmit by applying signatures, nonces, etc. /// </summary> /// <param name="message">The message to prepare for sending.</param> - internal void ProcessOutgoingMessageTestHook(IProtocolMessage message) { - this.ProcessOutgoingMessage(message); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + /// <remarks> + /// This method should NOT be called by derived types + /// except when sending ONE WAY request messages. + /// </remarks> + internal Task ProcessOutgoingMessageTestHookAsync(IProtocolMessage message, CancellationToken cancellationToken = default(CancellationToken)) { + return this.ProcessOutgoingMessageAsync(message, cancellationToken); + } + + /// <summary> + /// Parses the URL encoded form content. + /// </summary> + /// <param name="request">The request.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>A sequence of key=value pairs found in the request's entity; or an empty sequence if none are found.</returns> + protected internal static async Task<IEnumerable<KeyValuePair<string, string>>> ParseUrlEncodedFormContentAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + if (request.Content != null && request.Content.Headers.ContentType != null + && request.Content.Headers.ContentType.MediaType.Equals(HttpFormUrlEncoded)) { + return HttpUtility.ParseQueryString(await request.Content.ReadAsStringAsync()).AsKeyValuePairs(); + } + + return Enumerable.Empty<KeyValuePair<string, string>>(); } /// <summary> @@ -635,19 +568,43 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> + /// Adds just the binary data part of a message to a multipart form content object. + /// </summary> + /// <param name="requestMessageWithBinaryData">The request message with binary data.</param> + /// <returns>The initialized HttpContent.</returns> + protected static MultipartFormDataContent InitializeMultipartFormDataContent(IMessageWithBinaryData requestMessageWithBinaryData) { + Requires.NotNull(requestMessageWithBinaryData, "requestMessageWithBinaryData"); + + var content = new MultipartFormDataContent(); + foreach (var part in requestMessageWithBinaryData.BinaryData) { + if (string.IsNullOrEmpty(part.Name)) { + content.Add(part.Content); + } else if (string.IsNullOrEmpty(part.FileName)) { + content.Add(part.Content, part.Name); + } else { + content.Add(part.Content, part.Name, part.FileName); + } + } + + return content; + } + + /// <summary> /// Checks whether a given HTTP method is expected to include an entity body in its request. /// </summary> /// <param name="httpMethod">The HTTP method.</param> /// <returns><c>true</c> if the HTTP method is supposed to have an entity; <c>false</c> otherwise.</returns> - protected static bool HttpMethodHasEntity(string httpMethod) { - if (string.Equals(httpMethod, "GET", StringComparison.Ordinal) || - string.Equals(httpMethod, "HEAD", StringComparison.Ordinal) || - string.Equals(httpMethod, "DELETE", StringComparison.Ordinal) || - string.Equals(httpMethod, "OPTIONS", StringComparison.Ordinal)) { + protected static bool HttpMethodHasEntity(HttpMethod httpMethod) { + Requires.NotNull(httpMethod, "httpMethod"); + + if (httpMethod == HttpMethod.Get || + httpMethod == HttpMethod.Head || + httpMethod == HttpMethod.Delete || + httpMethod == HttpMethod.Options) { return false; - } else if (string.Equals(httpMethod, "POST", StringComparison.Ordinal) || - string.Equals(httpMethod, "PUT", StringComparison.Ordinal) || - string.Equals(httpMethod, "PATCH", StringComparison.Ordinal)) { + } else if (httpMethod == HttpMethod.Post || + httpMethod == HttpMethod.Put || + string.Equals(httpMethod.Method, "PATCH", StringComparison.Ordinal)) { return true; } else { throw ErrorUtilities.ThrowArgumentNamed("httpMethod", MessagingStrings.UnsupportedHttpVerb, httpMethod); @@ -659,11 +616,11 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <param name="message">The message.</param> /// <param name="response">The HTTP response.</param> - protected static void ApplyMessageTemplate(IMessage message, OutgoingWebResponse response) { + protected static void ApplyMessageTemplate(IMessage message, HttpResponseMessage response) { Requires.NotNull(message, "message"); var httpMessage = message as IHttpDirectResponse; if (httpMessage != null) { - response.Status = httpMessage.HttpStatusCode; + response.StatusCode = httpMessage.HttpStatusCode; foreach (string headerName in httpMessage.Headers) { response.Headers.Add(headerName, httpMessage.Headers[headerName]); } @@ -699,63 +656,76 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> - /// Gets the direct response of a direct HTTP request. - /// </summary> - /// <param name="webRequest">The web request.</param> - /// <returns>The response to the web request.</returns> - /// <exception cref="ProtocolException">Thrown on network or protocol errors.</exception> - protected virtual IncomingWebResponse GetDirectResponse(HttpWebRequest webRequest) { - Requires.NotNull(webRequest, "webRequest"); - return this.WebRequestHandler.GetResponse(webRequest); - } - - /// <summary> /// Submits a direct request message to some remote party and blocks waiting for an immediately reply. /// </summary> /// <param name="request">The request message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The response message, or null if the response did not carry a message.</returns> /// <remarks> /// Typically a deriving channel will override <see cref="CreateHttpRequest"/> to customize this method's /// behavior. However in non-HTTP frameworks, such as unit test mocks, it may be appropriate to override /// this method to eliminate all use of an HTTP transport. /// </remarks> - protected virtual IProtocolMessage RequestCore(IDirectedProtocolMessage request) { + protected virtual async Task<IProtocolMessage> RequestCoreAsync(IDirectedProtocolMessage request, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); Requires.That(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); - HttpWebRequest webRequest = this.CreateHttpRequest(request); + if (this.OutgoingMessageFilter != null) { + this.OutgoingMessageFilter(request); + } + + var webRequest = this.CreateHttpRequest(request); var directRequest = request as IHttpDirectRequest; if (directRequest != null) { - foreach (string header in directRequest.Headers) { - webRequest.Headers[header] = directRequest.Headers[header]; + foreach (var header in directRequest.Headers) { + webRequest.Headers.Add(header.Key, header.Value); } } - IDictionary<string, string> responseFields; - IDirectResponseProtocolMessage responseMessage; - - using (IncomingWebResponse response = this.GetDirectResponse(webRequest)) { - if (response.ResponseStream == null) { - return null; - } - - responseFields = this.ReadFromResponseCore(response); - if (responseFields == null) { - return null; - } - - responseMessage = this.MessageFactory.GetNewResponseMessage(request, responseFields); - if (responseMessage == null) { - return null; + try { + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.SendAsync(webRequest, cancellationToken)) { + if (response.Content != null) { + var responseFields = await this.ReadFromResponseCoreAsync(response, cancellationToken); + if (responseFields != null) { + var responseMessage = this.MessageFactory.GetNewResponseMessage(request, responseFields); + if (responseMessage != null) { + this.OnReceivingDirectResponse(response, responseMessage); + + var messageAccessor = this.MessageDescriptions.GetAccessor(responseMessage); + messageAccessor.Deserialize(responseFields); + + return responseMessage; + } + } + } + + if (!response.IsSuccessStatusCode) { + var errorContent = (response.Content != null) ? await response.Content.ReadAsStringAsync() : null; + Logger.Http.ErrorFormat( + "Error received in HTTP response: {0} {1}\n{2}", (int)response.StatusCode, response.ReasonPhrase, errorContent); + response.EnsureSuccessStatusCode(); // throw so we can wrap it in our catch block. + } + + return null; + } } - - this.OnReceivingDirectResponse(response, responseMessage); + } catch (HttpRequestException requestException) { + throw ErrorUtilities.Wrap(requestException, "Error sending HTTP request or receiving response."); } + } - var messageAccessor = this.MessageDescriptions.GetAccessor(responseMessage); - messageAccessor.Deserialize(responseFields); + /// <summary> + /// Provides derived-types the opportunity to wrap an <see cref="HttpMessageHandler"/> with another one. + /// </summary> + /// <param name="innerHandler">The inner handler received from <see cref="IHostFactories"/></param> + /// <returns>The handler to use in <see cref="HttpClient"/> instances.</returns> + protected virtual HttpMessageHandler WrapMessageHandler(HttpMessageHandler innerHandler) { + //TODO: make sure that everyone calls this to wrap their handlers rather than using the one directly returned + //from IHostFactories. - return responseMessage; + // No wrapping by default. + return innerHandler; } /// <summary> @@ -763,24 +733,27 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <param name="response">The HTTP direct response.</param> /// <param name="message">The newly instantiated message, prior to deserialization.</param> - protected virtual void OnReceivingDirectResponse(IncomingWebResponse response, IDirectResponseProtocolMessage message) { + protected virtual void OnReceivingDirectResponse(HttpResponseMessage response, IDirectResponseProtocolMessage message) { } /// <summary> /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The deserialized message, if one is found. Null otherwise.</returns> - protected virtual IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { + protected virtual async Task<IDirectedProtocolMessage> ReadFromRequestCoreAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); - Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.GetPublicFacingUrl().AbsoluteUri); + Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.Method, request.RequestUri.AbsoluteUri); + + var fields = new Dictionary<string, string>(); // Search Form data first, and if nothing is there search the QueryString - Assumes.True(request.Form != null && request.GetQueryStringBeforeRewriting() != null); - var fields = request.Form.ToDictionary(); - if (fields.Count == 0 && request.HttpMethod != "POST") { // OpenID 2.0 section 4.1.2 - fields = request.GetQueryStringBeforeRewriting().ToDictionary(); + fields.AddRange(await ParseUrlEncodedFormContentAsync(request, cancellationToken)); + + if (fields.Count == 0 && request.Method.Method != "POST") { // OpenID 2.0 section 4.1.2 + fields.AddRange(HttpUtility.ParseQueryString(request.RequestUri.Query).AsKeyValuePairs()); } MessageReceivingEndpoint recipient; @@ -827,7 +800,7 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <param name="message">The message to send.</param> /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> - protected virtual OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) { + protected virtual HttpResponseMessage PrepareIndirectResponse(IDirectedProtocolMessage message) { Requires.NotNull(message, "message"); Requires.That(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); Requires.That((message.HttpMethods & (HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest)) != 0, "message", "GET or POST expected."); @@ -837,7 +810,7 @@ namespace DotNetOpenAuth.Messaging { Assumes.True(message != null && message.Recipient != null); var fields = messageAccessor.Serialize(); - OutgoingWebResponse response = null; + HttpResponseMessage response = null; bool tooLargeForGet = false; if ((message.HttpMethods & HttpDeliveryMethods.GetRequest) == HttpDeliveryMethods.GetRequest) { bool payloadInFragment = false; @@ -849,7 +822,7 @@ namespace DotNetOpenAuth.Messaging { // First try creating a 301 redirect, and fallback to a form POST // if the message is too big. response = this.Create301RedirectResponse(message, fields, payloadInFragment); - tooLargeForGet = response.Headers[HttpResponseHeader.Location].Length > this.MaximumIndirectMessageUrlLength; + tooLargeForGet = response.Headers.Location.PathAndQuery.Length > this.MaximumIndirectMessageUrlLength; } // Make sure that if the message is too large for GET that POST is allowed. @@ -876,14 +849,13 @@ namespace DotNetOpenAuth.Messaging { /// <param name="payloadInFragment">if set to <c>true</c> the redirect will contain the message payload in the #fragment portion of the URL rather than the ?querystring.</param> /// <returns>The encoded HTTP response.</returns> [Pure] - protected virtual OutgoingWebResponse Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) { + protected virtual HttpResponseMessage Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) { Requires.NotNull(message, "message"); Requires.That(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); Requires.NotNull(fields, "fields"); // As part of this redirect, we include an HTML body in order to get passed some proxy filters // such as WebSense. - WebHeaderCollection headers = new WebHeaderCollection(); UriBuilder builder = new UriBuilder(message.Recipient); if (payloadInFragment) { builder.AppendFragmentArgs(fields); @@ -891,16 +863,14 @@ namespace DotNetOpenAuth.Messaging { builder.AppendQueryArgs(fields); } - headers.Add(HttpResponseHeader.Location, builder.Uri.AbsoluteUri); - headers.Add(HttpResponseHeader.ContentType, "text/html; charset=utf-8"); Logger.Http.DebugFormat("Redirecting to {0}", builder.Uri.AbsoluteUri); - OutgoingWebResponse response = new OutgoingWebResponse { - Status = HttpStatusCode.Redirect, - Headers = headers, - Body = string.Format(CultureInfo.InvariantCulture, RedirectResponseBodyFormat, builder.Uri.AbsoluteUri), - OriginalMessage = message + HttpResponseMessage response = new HttpResponseMessageWithOriginal(message) { + StatusCode = HttpStatusCode.Redirect, + Content = new StringContent(string.Format(CultureInfo.InvariantCulture, RedirectResponseBodyFormat, builder.Uri.AbsoluteUri)), }; + response.Headers.Location = builder.Uri; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html") { CharSet = "utf-8" }; return response; } @@ -912,13 +882,11 @@ namespace DotNetOpenAuth.Messaging { /// <param name="fields">The pre-serialized fields from the message.</param> /// <returns>The encoded HTTP response.</returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No apparent problem. False positive?")] - protected virtual OutgoingWebResponse CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) { + protected virtual HttpResponseMessage CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) { Requires.NotNull(message, "message"); Requires.That(message.Recipient != null, "message", MessagingStrings.DirectedMessageMissingRecipient); Requires.NotNull(fields, "fields"); - WebHeaderCollection headers = new WebHeaderCollection(); - headers.Add(HttpResponseHeader.ContentType, "text/html"); using (StringWriter bodyWriter = new StringWriter(CultureInfo.InvariantCulture)) { StringBuilder hiddenFields = new StringBuilder(); foreach (var field in fields) { @@ -932,12 +900,11 @@ namespace DotNetOpenAuth.Messaging { HttpUtility.HtmlEncode(message.Recipient.AbsoluteUri), hiddenFields); bodyWriter.Flush(); - OutgoingWebResponse response = new OutgoingWebResponse { - Status = HttpStatusCode.OK, - Headers = headers, - Body = bodyWriter.ToString(), - OriginalMessage = message + HttpResponseMessage response = new HttpResponseMessageWithOriginal(message) { + StatusCode = HttpStatusCode.OK, + Content = new StringContent(bodyWriter.ToString()), }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); return response; } @@ -947,9 +914,12 @@ namespace DotNetOpenAuth.Messaging { /// Gets the protocol message that may be in the given HTTP response. /// </summary> /// <param name="response">The response that is anticipated to contain an protocol message.</param> - /// <returns>The deserialized message parts, if found. Null otherwise.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The deserialized message parts, if found. Null otherwise. + /// </returns> /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> - protected abstract IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response); + protected abstract Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken); /// <summary> /// Prepares an HTTP request that carries a given message. @@ -957,10 +927,10 @@ namespace DotNetOpenAuth.Messaging { /// <param name="request">The message to send.</param> /// <returns>The <see cref="HttpWebRequest"/> prepared to send the request.</returns> /// <remarks> - /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method + /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCoreAsync"/> method /// is overridden and does not require this method. /// </remarks> - protected virtual HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { + protected virtual HttpRequestMessage CreateHttpRequest(IDirectedProtocolMessage request) { Requires.NotNull(request, "request"); Requires.That(request.Recipient != null, "request", MessagingStrings.DirectedMessageMissingRecipient); throw new NotImplementedException(); @@ -975,7 +945,7 @@ namespace DotNetOpenAuth.Messaging { /// <remarks> /// This method implements spec OAuth V1.0 section 5.3. /// </remarks> - protected abstract OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response); + protected abstract HttpResponseMessage PrepareDirectResponse(IProtocolMessage response); /// <summary> /// Serializes the given message as a JSON string. @@ -1005,15 +975,24 @@ namespace DotNetOpenAuth.Messaging { return dictionary; } + internal Action<IProtocolMessage> OutgoingMessageFilter { get; set; } + + internal Action<IProtocolMessage> IncomingMessageFilter { get; set; } + /// <summary> /// Prepares a message for transmit by applying signatures, nonces, etc. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + /// <exception cref="UnprotectedMessageException">Thrown if the message does not have the minimal required protections applied.</exception> /// <remarks> /// This method should NOT be called by derived types /// except when sending ONE WAY request messages. /// </remarks> - protected void ProcessOutgoingMessage(IProtocolMessage message) { + protected async Task ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { Requires.NotNull(message, "message"); Logger.Channel.DebugFormat("Preparing to send {0} ({1}) message.", message.GetType().Name, message.Version); @@ -1028,7 +1007,7 @@ namespace DotNetOpenAuth.Messaging { MessageProtections appliedProtection = MessageProtections.None; foreach (IChannelBindingElement bindingElement in this.outgoingBindingElements) { Assumes.True(bindingElement.Channel != null); - MessageProtections? elementProtection = bindingElement.ProcessOutgoingMessage(message); + MessageProtections? elementProtection = await bindingElement.ProcessOutgoingMessageAsync(message, cancellationToken); if (elementProtection.HasValue) { Logger.Bindings.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName); @@ -1049,6 +1028,10 @@ namespace DotNetOpenAuth.Messaging { this.EnsureValidMessageParts(message); message.EnsureValidMessage(); + if (this.OutgoingMessageFilter != null) { + this.OutgoingMessageFilter(message); + } + if (Logger.Channel.IsInfoEnabled) { var directedMessage = message as IDirectedProtocolMessage; string recipient = (directedMessage != null && directedMessage.Recipient != null) ? directedMessage.Recipient.AbsoluteUri : "<response>"; @@ -1072,7 +1055,7 @@ namespace DotNetOpenAuth.Messaging { /// This method is simply a standard HTTP Get request with the message parts serialized to the query string. /// This method satisfies OAuth 1.0 section 5.2, item #3. /// </remarks> - protected virtual HttpWebRequest InitializeRequestAsGet(IDirectedProtocolMessage requestMessage) { + protected virtual HttpRequestMessage InitializeRequestAsGet(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); Requires.That(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient); @@ -1081,7 +1064,7 @@ namespace DotNetOpenAuth.Messaging { UriBuilder builder = new UriBuilder(requestMessage.Recipient); MessagingUtilities.AppendQueryArgs(builder, fields); - HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(builder.Uri); + var httpRequest = new HttpRequestMessage(HttpMethod.Get, builder.Uri); this.PrepareHttpWebRequest(httpRequest); return httpRequest; @@ -1096,12 +1079,12 @@ namespace DotNetOpenAuth.Messaging { /// This method is simply a standard HTTP HEAD request with the message parts serialized to the query string. /// This method satisfies OAuth 1.0 section 5.2, item #3. /// </remarks> - protected virtual HttpWebRequest InitializeRequestAsHead(IDirectedProtocolMessage requestMessage) { + protected virtual HttpRequestMessage InitializeRequestAsHead(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); Requires.That(requestMessage.Recipient != null, "requestMessage", MessagingStrings.DirectedMessageMissingRecipient); - HttpWebRequest request = this.InitializeRequestAsGet(requestMessage); - request.Method = "HEAD"; + var request = this.InitializeRequestAsGet(requestMessage); + request.Method = HttpMethod.Head; return request; } @@ -1115,27 +1098,28 @@ namespace DotNetOpenAuth.Messaging { /// with the application/x-www-form-urlencoded content type /// This method satisfies OAuth 1.0 section 5.2, item #2 and OpenID 2.0 section 4.1.2. /// </remarks> - protected virtual HttpWebRequest InitializeRequestAsPost(IDirectedProtocolMessage requestMessage) { + protected virtual HttpRequestMessage InitializeRequestAsPost(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); var messageAccessor = this.MessageDescriptions.GetAccessor(requestMessage); var fields = messageAccessor.Serialize(); - var httpRequest = (HttpWebRequest)WebRequest.Create(requestMessage.Recipient); + var httpRequest = new HttpRequestMessage(HttpMethod.Post, requestMessage.Recipient); this.PrepareHttpWebRequest(httpRequest); - httpRequest.CachePolicy = this.CachePolicy; - httpRequest.Method = "POST"; var requestMessageWithBinaryData = requestMessage as IMessageWithBinaryData; if (requestMessageWithBinaryData != null && requestMessageWithBinaryData.SendAsMultipart) { - var multiPartFields = new List<MultipartPostPart>(requestMessageWithBinaryData.BinaryData); + var content = InitializeMultipartFormDataContent(requestMessageWithBinaryData); // When sending multi-part, all data gets send as multi-part -- even the non-binary data. - multiPartFields.AddRange(fields.Select(field => MultipartPostPart.CreateFormPart(field.Key, field.Value))); - this.SendParametersInEntityAsMultipart(httpRequest, multiPartFields); + foreach (var field in fields) { + content.Add(new StringContent(field.Value), field.Key); + } + + httpRequest.Content = content; } else { ErrorUtilities.VerifyProtocol(requestMessageWithBinaryData == null || requestMessageWithBinaryData.BinaryData.Count == 0, MessagingStrings.BinaryDataRequiresMultipart); - this.SendParametersInEntity(httpRequest, fields); + httpRequest.Content = new FormUrlEncodedContent(fields); } return httpRequest; @@ -1149,11 +1133,11 @@ namespace DotNetOpenAuth.Messaging { /// <remarks> /// This method is simply a standard HTTP PUT request with the message parts serialized to the query string. /// </remarks> - protected virtual HttpWebRequest InitializeRequestAsPut(IDirectedProtocolMessage requestMessage) { + protected virtual HttpRequestMessage InitializeRequestAsPut(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); - HttpWebRequest request = this.InitializeRequestAsGet(requestMessage); - request.Method = "PUT"; + var request = this.InitializeRequestAsGet(requestMessage); + request.Method = HttpMethod.Put; return request; } @@ -1165,66 +1149,26 @@ namespace DotNetOpenAuth.Messaging { /// <remarks> /// This method is simply a standard HTTP DELETE request with the message parts serialized to the query string. /// </remarks> - protected virtual HttpWebRequest InitializeRequestAsDelete(IDirectedProtocolMessage requestMessage) { + protected virtual HttpRequestMessage InitializeRequestAsDelete(IDirectedProtocolMessage requestMessage) { Requires.NotNull(requestMessage, "requestMessage"); - HttpWebRequest request = this.InitializeRequestAsGet(requestMessage); - request.Method = "DELETE"; + var request = this.InitializeRequestAsGet(requestMessage); + request.Method = HttpMethod.Delete; return request; } /// <summary> - /// Sends the given parameters in the entity stream of an HTTP request. - /// </summary> - /// <param name="httpRequest">The HTTP request.</param> - /// <param name="fields">The parameters to send.</param> - /// <remarks> - /// This method calls <see cref="HttpWebRequest.GetRequestStream()"/> and closes - /// the request stream, but does not call <see cref="HttpWebRequest.GetResponse"/>. - /// </remarks> - protected void SendParametersInEntity(HttpWebRequest httpRequest, IDictionary<string, string> fields) { - Requires.NotNull(httpRequest, "httpRequest"); - Requires.NotNull(fields, "fields"); - - string requestBody = MessagingUtilities.CreateQueryString(fields); - byte[] requestBytes = PostEntityEncoding.GetBytes(requestBody); - httpRequest.ContentType = HttpFormUrlEncodedContentType.ToString(); - httpRequest.ContentLength = requestBytes.Length; - Stream requestStream = this.WebRequestHandler.GetRequestStream(httpRequest); - try { - requestStream.Write(requestBytes, 0, requestBytes.Length); - } finally { - // We need to be sure to close the request stream... - // unless it is a MemoryStream, which is a clue that we're in - // a mock stream situation and closing it would preclude reading it later. - if (!(requestStream is MemoryStream)) { - requestStream.Dispose(); - } - } - } - - /// <summary> - /// Sends the given parameters in the entity stream of an HTTP request in multi-part format. - /// </summary> - /// <param name="httpRequest">The HTTP request.</param> - /// <param name="fields">The parameters to send.</param> - /// <remarks> - /// This method calls <see cref="HttpWebRequest.GetRequestStream()"/> and closes - /// the request stream, but does not call <see cref="HttpWebRequest.GetResponse"/>. - /// </remarks> - protected void SendParametersInEntityAsMultipart(HttpWebRequest httpRequest, IEnumerable<MultipartPostPart> fields) { - httpRequest.PostMultipartNoGetResponse(this.WebRequestHandler, fields); - } - - /// <summary> /// Verifies the integrity and applicability of an incoming message. /// </summary> /// <param name="message">The message just received.</param> - /// <exception cref="ProtocolException"> - /// Thrown when the message is somehow invalid. - /// This can be due to tampering, replay attack or expiration, among other things. - /// </exception> - protected virtual void ProcessIncomingMessage(IProtocolMessage message) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + /// <exception cref="UnprotectedMessageException">Thrown if the message does not have the minimal required protections applied.</exception> + /// <exception cref="ProtocolException">Thrown when the message is somehow invalid. + /// This can be due to tampering, replay attack or expiration, among other things.</exception> + protected virtual async Task ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { Requires.NotNull(message, "message"); if (Logger.Channel.IsInfoEnabled) { @@ -1237,10 +1181,14 @@ namespace DotNetOpenAuth.Messaging { messageAccessor.ToStringDeferred()); } + if (this.IncomingMessageFilter != null) { + this.IncomingMessageFilter(message); + } + MessageProtections appliedProtection = MessageProtections.None; foreach (IChannelBindingElement bindingElement in this.IncomingBindingElements) { Assumes.True(bindingElement.Channel != null); // CC bug: this.IncomingBindingElements ensures this... why must we assume it here? - MessageProtections? elementProtection = bindingElement.ProcessIncomingMessage(message); + MessageProtections? elementProtection = await bindingElement.ProcessIncomingMessageAsync(message, cancellationToken); if (elementProtection.HasValue) { Logger.Bindings.DebugFormat("Binding element {0} applied to message.", bindingElement.GetType().FullName); @@ -1301,7 +1249,7 @@ namespace DotNetOpenAuth.Messaging { /// Performs additional processing on an outgoing web request before it is sent to the remote server. /// </summary> /// <param name="request">The request.</param> - protected virtual void PrepareHttpWebRequest(HttpWebRequest request) { + protected virtual void PrepareHttpWebRequest(HttpRequestMessage request) { Requires.NotNull(request, "request"); } @@ -1386,18 +1334,6 @@ namespace DotNetOpenAuth.Messaging { return -((int)protection1).CompareTo((int)protection2); // descending flag ordinal order } -#if CONTRACTS_FULL - /// <summary> - /// Verifies conditions that should be true for any valid state of this object. - /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Called by code contracts.")] - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called by code contracts.")] - [ContractInvariantMethod] - private void ObjectInvariant() { - Contract.Invariant(this.MessageDescriptions != null); - } -#endif - /// <summary> /// Verifies that all required message parts are initialized to values /// prior to sending the message to a remote party. diff --git a/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs b/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs index f3a1ba8..924a3c2 100644 --- a/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs +++ b/src/DotNetOpenAuth.Core/Messaging/HttpRequestInfo.cs @@ -222,6 +222,58 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> + /// When overridden in a derived class, gets an array of client-supported MIME accept types. + /// </summary> + /// <returns>An array of client-supported MIME accept types.</returns> + public override string[] AcceptTypes { + get { + if (this.Headers["Accept"] != null) { + return this.headers["Accept"].Split(','); + } + + return new string[0]; + } + } + + /// <summary> + /// When overridden in a derived class, gets information about the URL of the client request that linked to the current URL. + /// </summary> + /// <returns>The URL of the page that linked to the current request.</returns> + public override Uri UrlReferrer { + get { + if (this.Headers["Referer"] != null) { // misspelled word intentional, per RFC + return new Uri(this.Headers["Referer"]); + } + + return null; + } + } + + /// <summary> + /// When overridden in a derived class, gets the length, in bytes, of content that was sent by the client. + /// </summary> + /// <returns>The length, in bytes, of content that was sent by the client.</returns> + public override int ContentLength { + get { + if (this.Headers["Content-Length"] != null) { + return int.Parse(this.headers["Content-Length"]); + } + + return 0; + } + } + + /// <summary> + /// When overridden in a derived class, gets or sets the MIME content type of the request. + /// </summary> + /// <returns>The MIME content type of the request, such as "text/html".</returns> + /// <exception cref="System.NotImplementedException"></exception> + public override string ContentType { + get { return this.Headers["Content-Type"]; } + set { throw new NotImplementedException(); } + } + + /// <summary> /// Creates an <see cref="HttpRequestBase"/> instance that describes the specified HTTP request. /// </summary> /// <param name="request">The request.</param> diff --git a/src/DotNetOpenAuth.Core/Messaging/HttpResponseMessageWithOriginal.cs b/src/DotNetOpenAuth.Core/Messaging/HttpResponseMessageWithOriginal.cs new file mode 100644 index 0000000..4db9f63 --- /dev/null +++ b/src/DotNetOpenAuth.Core/Messaging/HttpResponseMessageWithOriginal.cs @@ -0,0 +1,30 @@ +//----------------------------------------------------------------------- +// <copyright file="HttpResponseMessageWithOriginal.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System.Net; + using System.Net.Http; + + using Validation; + + internal class HttpResponseMessageWithOriginal : HttpResponseMessage { + /// <summary> + /// Initializes a new instance of the <see cref="HttpResponseMessageWithOriginal"/> class. + /// </summary> + /// <param name="originalMessage">The original message.</param> + /// <param name="statusCode">The status code.</param> + internal HttpResponseMessageWithOriginal(IMessage originalMessage, HttpStatusCode statusCode = HttpStatusCode.OK) + : base(statusCode) { + OriginalMessage = originalMessage; + Requires.NotNull(originalMessage, "originalMessage"); + } + + /// <summary> + /// Gets the original message. + /// </summary> + internal IMessage OriginalMessage { get; private set; } + } +} diff --git a/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs b/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs index fca46a0..fe2cf3d 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IChannelBindingElement.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.Messaging { using System; + using System.Threading; + using System.Threading.Tasks; using Validation; /// <summary> @@ -33,6 +35,7 @@ namespace DotNetOpenAuth.Messaging { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -41,13 +44,14 @@ namespace DotNetOpenAuth.Messaging { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - MessageProtections? ProcessOutgoingMessage(IProtocolMessage message); + Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken); /// <summary> /// Performs any transformation on an incoming message that may be necessary and/or /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -60,6 +64,6 @@ namespace DotNetOpenAuth.Messaging { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - MessageProtections? ProcessIncomingMessage(IProtocolMessage message); + Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken); } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs deleted file mode 100644 index f3975b3..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/IDirectWebRequestHandler.cs +++ /dev/null @@ -1,105 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="IDirectWebRequestHandler.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Collections.Generic; - using System.Diagnostics.Contracts; - using System.IO; - using System.Net; - using DotNetOpenAuth.Messaging; - using Validation; - - /// <summary> - /// A contract for <see cref="HttpWebRequest"/> handling. - /// </summary> - /// <remarks> - /// Implementations of this interface must be thread safe. - /// </remarks> - public interface IDirectWebRequestHandler { - /// <summary> - /// Determines whether this instance can support the specified options. - /// </summary> - /// <param name="options">The set of options that might be given in a subsequent web request.</param> - /// <returns> - /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>. - /// </returns> - [Pure] - bool CanSupport(DirectWebRequestOptions options); - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <returns> - /// The stream the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method. - /// Callers <i>must</i> close and dispose of the request stream when they are done - /// writing to it to avoid taking up the connection too long and causing long waits on - /// subsequent requests.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - Stream GetRequestStream(HttpWebRequest request); - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns> - /// The stream the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method. - /// Callers <i>must</i> close and dispose of the request stream when they are done - /// writing to it to avoid taking up the connection too long and causing long waits on - /// subsequent requests.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - Stream GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options); - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - IncomingWebResponse GetResponse(HttpWebRequest request); - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options); - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs index 7b26869..226102d 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IHttpDirectRequest.cs @@ -15,6 +15,6 @@ namespace DotNetOpenAuth.Messaging { /// Gets the HTTP headers of the request. /// </summary> /// <value>May be an empty collection, but must not be <c>null</c>.</value> - WebHeaderCollection Headers { get; } + System.Net.Http.Headers.HttpRequestHeaders Headers { get; } } } diff --git a/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs b/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs index 2992678..84a7760 100644 --- a/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs +++ b/src/DotNetOpenAuth.Core/Messaging/IMessageWithBinaryData.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text; /// <summary> @@ -19,7 +20,7 @@ namespace DotNetOpenAuth.Messaging { /// Gets the parts of the message that carry binary data. /// </summary> /// <value>A list of parts. Never null.</value> - IList<MultipartPostPart> BinaryData { get; } + IList<MultipartContentMember> BinaryData { get; } /// <summary> /// Gets a value indicating whether this message should be sent as multi-part POST. diff --git a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs deleted file mode 100644 index abb01a1..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/IncomingWebResponse.cs +++ /dev/null @@ -1,189 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="IncomingWebResponse.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Diagnostics.CodeAnalysis; - using System.Globalization; - using System.IO; - using System.Net; - using System.Net.Mime; - using System.Text; - using Validation; - - /// <summary> - /// Details on the incoming response from a direct web request to a remote party. - /// </summary> - public abstract class IncomingWebResponse : IDisposable { - /// <summary> - /// The encoding to use in reading a response that does not declare its own content encoding. - /// </summary> - private const string DefaultContentEncoding = "ISO-8859-1"; - - /// <summary> - /// Initializes a new instance of the <see cref="IncomingWebResponse"/> class. - /// </summary> - protected internal IncomingWebResponse() { - this.Status = HttpStatusCode.OK; - this.Headers = new WebHeaderCollection(); - } - - /// <summary> - /// Initializes a new instance of the <see cref="IncomingWebResponse"/> class. - /// </summary> - /// <param name="requestUri">The original request URI.</param> - /// <param name="response">The response to initialize from. The network stream is used by this class directly.</param> - protected IncomingWebResponse(Uri requestUri, HttpWebResponse response) { - Requires.NotNull(requestUri, "requestUri"); - Requires.NotNull(response, "response"); - - this.RequestUri = requestUri; - if (!string.IsNullOrEmpty(response.ContentType)) { - try { - this.ContentType = new ContentType(response.ContentType); - } catch (FormatException) { - Logger.Messaging.ErrorFormat("HTTP response to {0} included an invalid Content-Type header value: {1}", response.ResponseUri.AbsoluteUri, response.ContentType); - } - } - this.ContentEncoding = string.IsNullOrEmpty(response.ContentEncoding) ? DefaultContentEncoding : response.ContentEncoding; - this.FinalUri = response.ResponseUri; - this.Status = response.StatusCode; - this.Headers = response.Headers; - } - - /// <summary> - /// Initializes a new instance of the <see cref="IncomingWebResponse"/> class. - /// </summary> - /// <param name="requestUri">The request URI.</param> - /// <param name="responseUri">The final URI to respond to the request.</param> - /// <param name="headers">The headers.</param> - /// <param name="statusCode">The status code.</param> - /// <param name="contentType">Type of the content.</param> - /// <param name="contentEncoding">The content encoding.</param> - protected IncomingWebResponse(Uri requestUri, Uri responseUri, WebHeaderCollection headers, HttpStatusCode statusCode, string contentType, string contentEncoding) { - Requires.NotNull(requestUri, "requestUri"); - - this.RequestUri = requestUri; - this.Status = statusCode; - if (!string.IsNullOrEmpty(contentType)) { - try { - this.ContentType = new ContentType(contentType); - } catch (FormatException) { - Logger.Messaging.ErrorFormat("HTTP response to {0} included an invalid Content-Type header value: {1}", responseUri.AbsoluteUri, contentType); - } - } - this.ContentEncoding = string.IsNullOrEmpty(contentEncoding) ? DefaultContentEncoding : contentEncoding; - this.Headers = headers; - this.FinalUri = responseUri; - } - - /// <summary> - /// Gets the type of the content. - /// </summary> - public ContentType ContentType { get; private set; } - - /// <summary> - /// Gets the content encoding. - /// </summary> - public string ContentEncoding { get; private set; } - - /// <summary> - /// Gets the URI of the initial request. - /// </summary> - public Uri RequestUri { get; private set; } - - /// <summary> - /// Gets the URI that finally responded to the request. - /// </summary> - /// <remarks> - /// This can be different from the <see cref="RequestUri"/> in cases of - /// redirection during the request. - /// </remarks> - public Uri FinalUri { get; internal set; } - - /// <summary> - /// Gets the headers that must be included in the response to the user agent. - /// </summary> - /// <remarks> - /// The headers in this collection are not meant to be a comprehensive list - /// of exactly what should be sent, but are meant to augment whatever headers - /// are generally included in a typical response. - /// </remarks> - public WebHeaderCollection Headers { get; internal set; } - - /// <summary> - /// Gets the HTTP status code to use in the HTTP response. - /// </summary> - public HttpStatusCode Status { get; internal set; } - - /// <summary> - /// Gets the body of the HTTP response. - /// </summary> - public abstract Stream ResponseStream { get; } - - /// <summary> - /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. - /// </summary> - /// <returns> - /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. - /// </returns> - public override string ToString() { - StringBuilder sb = new StringBuilder(); - sb.AppendLine(string.Format(CultureInfo.CurrentCulture, "RequestUri = {0}", this.RequestUri)); - sb.AppendLine(string.Format(CultureInfo.CurrentCulture, "ResponseUri = {0}", this.FinalUri)); - sb.AppendLine(string.Format(CultureInfo.CurrentCulture, "StatusCode = {0}", this.Status)); - sb.AppendLine(string.Format(CultureInfo.CurrentCulture, "ContentType = {0}", this.ContentType)); - sb.AppendLine(string.Format(CultureInfo.CurrentCulture, "ContentEncoding = {0}", this.ContentEncoding)); - sb.AppendLine("Headers:"); - foreach (string header in this.Headers) { - sb.AppendLine(string.Format(CultureInfo.CurrentCulture, "\t{0}: {1}", header, this.Headers[header])); - } - - return sb.ToString(); - } - - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// <summary> - /// Creates a text reader for the response stream. - /// </summary> - /// <returns>The text reader, initialized for the proper encoding.</returns> - [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Costly operation")] - public abstract StreamReader GetResponseReader(); - - /// <summary> - /// Gets an offline snapshot version of this instance. - /// </summary> - /// <param name="maximumBytesToCache">The maximum bytes from the response stream to cache.</param> - /// <returns>A snapshot version of this instance.</returns> - /// <remarks> - /// If this instance is a <see cref="NetworkDirectWebResponse"/> creating a snapshot - /// will automatically close and dispose of the underlying response stream. - /// If this instance is a <see cref="CachedDirectWebResponse"/>, the result will - /// be the self same instance. - /// </remarks> - internal abstract CachedDirectWebResponse GetSnapshot(int maximumBytesToCache); - - /// <summary> - /// Releases unmanaged and - optionally - managed resources - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool disposing) { - if (disposing) { - Stream responseStream = this.ResponseStream; - if (responseStream != null) { - responseStream.Dispose(); - } - } - } - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/MessageProtectionTasks.cs b/src/DotNetOpenAuth.Core/Messaging/MessageProtectionTasks.cs new file mode 100644 index 0000000..37c86ca --- /dev/null +++ b/src/DotNetOpenAuth.Core/Messaging/MessageProtectionTasks.cs @@ -0,0 +1,41 @@ +//----------------------------------------------------------------------- +// <copyright file="MessageProtectionTasks.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + /// <summary> + /// Reusable pre-completed tasks that may be returned multiple times to reduce GC pressure. + /// </summary> + internal static class MessageProtectionTasks { + /// <summary> + /// A task whose result is <c>null</c> + /// </summary> + internal static readonly Task<MessageProtections?> Null = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A task whose result is <see cref="MessageProtections.None"/> + /// </summary> + internal static readonly Task<MessageProtections?> None = + Task.FromResult<MessageProtections?>(MessageProtections.None); + + /// <summary> + /// A task whose result is <see cref="MessageProtections.TamperProtection"/> + /// </summary> + internal static readonly Task<MessageProtections?> TamperProtection = + Task.FromResult<MessageProtections?>(MessageProtections.TamperProtection); + + /// <summary> + /// A task whose result is <see cref="MessageProtections.ReplayProtection"/> + /// </summary> + internal static readonly Task<MessageProtections?> ReplayProtection = + Task.FromResult<MessageProtections?>(MessageProtections.ReplayProtection); + } +} diff --git a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs index 221a29c..df11a16 100644 --- a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs +++ b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs @@ -15,12 +15,14 @@ namespace DotNetOpenAuth.Messaging { using System.Linq; using System.Net; using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; using System.Runtime.Serialization.Json; using System.Security; using System.Security.Cryptography; using System.Text; using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Xml; @@ -86,6 +88,11 @@ namespace DotNetOpenAuth.Messaging { private const int SymmetricSecretHandleLength = 4; /// <summary> + /// A pre-completed task. + /// </summary> + private static readonly Task CompletedTaskField = Task.FromResult<object>(null); + + /// <summary> /// The default lifetime of a private secret. /// </summary> private static readonly TimeSpan SymmetricSecretKeyLifespan = Configuration.DotNetOpenAuthSection.Messaging.PrivateSecretMaximumAge; @@ -149,41 +156,17 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> - /// Gets a random number generator for use on the current thread only. + /// Gets a pre-completed task. /// </summary> - internal static Random NonCryptoRandomDataGenerator { - get { return ThreadSafeRandom.RandomNumberGenerator; } - } - - /// <summary> - /// Transforms an OutgoingWebResponse to an MVC-friendly ActionResult. - /// </summary> - /// <param name="response">The response to send to the user agent.</param> - /// <returns>The <see cref="ActionResult"/> instance to be returned by the Controller's action method.</returns> - public static ActionResult AsActionResult(this OutgoingWebResponse response) { - Requires.NotNull(response, "response"); - return new OutgoingWebResponseActionResult(response); + internal static Task CompletedTask { + get { return CompletedTaskField; } } /// <summary> - /// Transforms an OutgoingWebResponse to a Web API-friendly HttpResponseMessage. + /// Gets a random number generator for use on the current thread only. /// </summary> - /// <param name="outgoingResponse">The response to send to the user agent.</param> - /// <returns>The <see cref="HttpResponseMessage"/> instance to be returned by the Web API method.</returns> - public static HttpResponseMessage AsHttpResponseMessage(this OutgoingWebResponse outgoingResponse) { - HttpResponseMessage response = new HttpResponseMessage(outgoingResponse.Status); - if (outgoingResponse.ResponseStream != null) { - response.Content = new StreamContent(outgoingResponse.ResponseStream); - } - - var responseHeaders = outgoingResponse.Headers; - foreach (var header in responseHeaders.AllKeys) { - if (!response.Headers.TryAddWithoutValidation(header, responseHeaders[header])) { - response.Content.Headers.TryAddWithoutValidation(header, responseHeaders[header]); - } - } - - return response; + internal static Random NonCryptoRandomDataGenerator { + get { return ThreadSafeRandom.RandomNumberGenerator; } } /// <summary> @@ -223,22 +206,6 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> - /// Sends a multipart HTTP POST request (useful for posting files). - /// </summary> - /// <param name="request">The HTTP request.</param> - /// <param name="requestHandler">The request handler.</param> - /// <param name="parts">The parts to include in the POST entity.</param> - /// <returns>The HTTP response.</returns> - public static IncomingWebResponse PostMultipart(this HttpWebRequest request, IDirectWebRequestHandler requestHandler, IEnumerable<MultipartPostPart> parts) { - Requires.NotNull(request, "request"); - Requires.NotNull(requestHandler, "requestHandler"); - Requires.NotNull(parts, "parts"); - - PostMultipartNoGetResponse(request, requestHandler, parts); - return requestHandler.GetResponse(request); - } - - /// <summary> /// Assembles a message comprised of the message on a given exception and all inner exceptions. /// </summary> /// <param name="exception">The exception.</param> @@ -393,7 +360,15 @@ namespace DotNetOpenAuth.Messaging { // HttpRequest.Url gives us the internal URL in a cloud environment, // So we use a variable that (at least from what I can tell) gives us // the public URL: - if (serverVariables["HTTP_HOST"] != null) { + string httpHost; + try { + httpHost = serverVariables["HTTP_HOST"]; + } catch (NullReferenceException) { + // The VS dev web server can throw this. :( + httpHost = null; + } + + if (httpHost != null) { ErrorUtilities.VerifySupported(request.Url.Scheme == Uri.UriSchemeHttps || request.Url.Scheme == Uri.UriSchemeHttp, "Only HTTP and HTTPS are supported protocols."); string scheme = serverVariables["HTTP_X_FORWARDED_PROTO"] ?? request.Url.Scheme; Uri hostAndPort = new Uri(scheme + Uri.SchemeDelimiter + serverVariables["HTTP_HOST"]); @@ -426,6 +401,115 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> + /// Gets the public facing URL for the given incoming HTTP request. + /// </summary> + /// <returns>The URI that the outside world used to create this request.</returns> + public static Uri GetPublicFacingUrl() { + ErrorUtilities.VerifyHttpContext(); + return GetPublicFacingUrl(new HttpRequestWrapper(HttpContext.Current.Request)); + } + + /// <summary> + /// Wraps a response message as an MVC <see cref="ActionResult"/> so it can be conveniently returned from an MVC controller's action method. + /// </summary> + /// <param name="response">The response message.</param> + /// <returns>An <see cref="ActionResult"/> instance.</returns> + public static ActionResult AsActionResult(this HttpResponseMessage response) { + Requires.NotNull(response, "response"); + return new HttpResponseMessageActionResult(response); + } + + /// <summary> + /// Wraps an instance of <see cref="HttpRequestBase"/> as an <see cref="HttpRequestMessage"/> instance. + /// </summary> + /// <param name="request">The request.</param> + /// <returns>An instance of <see cref="HttpRequestMessage"/></returns> + public static HttpRequestMessage AsHttpRequestMessage(this HttpRequestBase request) { + Requires.NotNull(request, "request"); + + Uri publicFacingUrl = request.GetPublicFacingUrl(); + var httpRequest = new HttpRequestMessage(new HttpMethod(request.HttpMethod), publicFacingUrl); + + if (request.Form != null) { + // Avoid a request message that will try to read the request stream twice for already parsed data. + httpRequest.Content = new FormUrlEncodedContent(request.Form.AsKeyValuePairs()); + } else if (request.InputStream != null) { + httpRequest.Content = new StreamContent(request.InputStream); + } + + httpRequest.CopyHeadersFrom(request); + return httpRequest; + } + + /// <summary> + /// Sends a response message to the HTTP client. + /// </summary> + /// <param name="response">The response message.</param> + /// <param name="context">The HTTP context to send the response with.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public static async Task SendAsync(this HttpResponseMessage response, HttpContextBase context = null, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(response, "response"); + if (context == null) { + ErrorUtilities.VerifyHttpContext(); + context = new HttpContextWrapper(HttpContext.Current); + } + + var responseContext = context.Response; + responseContext.StatusCode = (int)response.StatusCode; + responseContext.StatusDescription = response.ReasonPhrase; + foreach (var header in response.Headers) { + foreach (var value in header.Value) { + responseContext.AddHeader(header.Key, value); + } + } + + if (response.Content != null) { + await response.Content.CopyToAsync(responseContext.OutputStream).ConfigureAwait(false); + } + } + + /// <summary> + /// Disposes a value if it is not null. + /// </summary> + /// <param name="disposable">The disposable value.</param> + internal static void DisposeIfNotNull(this IDisposable disposable) { + if (disposable != null) { + disposable.Dispose(); + } + } + + /// <summary> + /// Clones the specified <see cref="HttpRequestMessage"/> so it can be re-sent. + /// </summary> + /// <param name="original">The original message.</param> + /// <returns>The cloned message</returns> + /// <remarks> + /// This is useful when an HTTP request fails, and after a little tweaking should be resent. + /// Since <see cref="HttpRequestMessage"/> remembers it was already sent, it will not permit being + /// sent a second time. This method clones the message so its contents are identical but allows + /// re-sending. + /// </remarks> + internal static HttpRequestMessage Clone(this HttpRequestMessage original) { + Requires.NotNull(original, "original"); + + var clone = new HttpRequestMessage(original.Method, original.RequestUri); + clone.Content = original.Content; + foreach (var header in original.Headers) { + clone.Headers.Add(header.Key, header.Value); + } + + foreach (var property in original.Properties) { + clone.Properties[property.Key] = property.Value; + } + + clone.Version = original.Version; + return clone; + } + + /// <summary> /// Gets the URL to the root of a web site, which may include a virtual directory path. /// </summary> /// <returns>An absolute URI.</returns> @@ -496,71 +580,16 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> - /// Sends a multipart HTTP POST request (useful for posting files) but doesn't call GetResponse on it. - /// </summary> - /// <param name="request">The HTTP request.</param> - /// <param name="requestHandler">The request handler.</param> - /// <param name="parts">The parts to include in the POST entity.</param> - internal static void PostMultipartNoGetResponse(this HttpWebRequest request, IDirectWebRequestHandler requestHandler, IEnumerable<MultipartPostPart> parts) { - Requires.NotNull(request, "request"); - Requires.NotNull(requestHandler, "requestHandler"); - Requires.NotNull(parts, "parts"); - - Reporting.RecordFeatureUse("MessagingUtilities.PostMultipart"); - parts = parts.CacheGeneratedResults(); - string boundary = Guid.NewGuid().ToString(); - string initialPartLeadingBoundary = string.Format(CultureInfo.InvariantCulture, "--{0}\r\n", boundary); - string partLeadingBoundary = string.Format(CultureInfo.InvariantCulture, "\r\n--{0}\r\n", boundary); - string finalTrailingBoundary = string.Format(CultureInfo.InvariantCulture, "\r\n--{0}--\r\n", boundary); - var contentType = new ContentType("multipart/form-data") { - Boundary = boundary, - CharSet = Channel.PostEntityEncoding.WebName, - }; - - request.Method = "POST"; - request.ContentType = contentType.ToString(); - long contentLength = parts.Sum(p => partLeadingBoundary.Length + p.Length) + finalTrailingBoundary.Length; - if (parts.Any()) { - contentLength -= 2; // the initial part leading boundary has no leading \r\n - } - request.ContentLength = contentLength; - - var requestStream = requestHandler.GetRequestStream(request); - try { - StreamWriter writer = new StreamWriter(requestStream, Channel.PostEntityEncoding); - bool firstPart = true; - foreach (var part in parts) { - writer.Write(firstPart ? initialPartLeadingBoundary : partLeadingBoundary); - firstPart = false; - part.Serialize(writer); - part.Dispose(); - } - - writer.Write(finalTrailingBoundary); - writer.Flush(); - } finally { - // We need to be sure to close the request stream... - // unless it is a MemoryStream, which is a clue that we're in - // a mock stream situation and closing it would preclude reading it later. - if (!(requestStream is MemoryStream)) { - requestStream.Dispose(); - } - } - } - - /// <summary> /// Assembles the content of the HTTP Authorization or WWW-Authenticate header. /// </summary> - /// <param name="scheme">The scheme.</param> /// <param name="fields">The fields to include.</param> - /// <returns>A value prepared for an HTTP header.</returns> - internal static string AssembleAuthorizationHeader(string scheme, IEnumerable<KeyValuePair<string, string>> fields) { - Requires.NotNullOrEmpty(scheme, "scheme"); + /// <returns> + /// A value prepared for an HTTP header. + /// </returns> + internal static string AssembleAuthorizationHeader(IEnumerable<KeyValuePair<string, string>> fields) { Requires.NotNull(fields, "fields"); var authorization = new StringBuilder(); - authorization.Append(scheme); - authorization.Append(" "); foreach (var pair in fields) { string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key); string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value); @@ -579,24 +608,15 @@ namespace DotNetOpenAuth.Messaging { /// <param name="scheme">The scheme. Must not be null or empty.</param> /// <param name="authorizationHeader">The authorization header. May be null or empty.</param> /// <returns>A sequence of key=value pairs discovered in the header. Never null, but may be empty.</returns> - internal static IEnumerable<KeyValuePair<string, string>> ParseAuthorizationHeader(string scheme, string authorizationHeader) { + internal static IEnumerable<KeyValuePair<string, string>> ParseAuthorizationHeader(string scheme, AuthenticationHeaderValue authorizationHeader) { Requires.NotNullOrEmpty(scheme, "scheme"); - string prefix = scheme + " "; - if (authorizationHeader != null) { - // The authorization header may have multiple sections. Look for the appropriate one. - string[] authorizationSections = new string[] { authorizationHeader }; // what is the right delimiter, if any? - foreach (string authorization in authorizationSections) { - string trimmedAuth = authorization.Trim(); - if (trimmedAuth.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { // RFC 2617 says this is case INsensitive - string data = trimmedAuth.Substring(prefix.Length); - return from element in data.Split(CommaArray) - let parts = element.Trim().Split(EqualsArray, 2) - let key = Uri.UnescapeDataString(parts[0]) - let value = Uri.UnescapeDataString(parts[1].Trim(QuoteArray)) - select new KeyValuePair<string, string>(key, value); - } - } + if (authorizationHeader != null && authorizationHeader.Scheme.Equals(scheme, StringComparison.OrdinalIgnoreCase)) { // RFC 2617 says this is case INsensitive + return from element in authorizationHeader.Parameter.Split(CommaArray) + let parts = element.Trim().Split(EqualsArray, 2) + let key = Uri.UnescapeDataString(parts[0]) + let value = Uri.UnescapeDataString(parts[1].Trim(QuoteArray)) + select new KeyValuePair<string, string>(key, value); } return Enumerable.Empty<KeyValuePair<string, string>>(); @@ -1104,31 +1124,6 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> - /// Adds a set of HTTP headers to an <see cref="HttpResponse"/> instance, - /// taking care to set some headers to the appropriate properties of - /// <see cref="HttpResponse" /> - /// </summary> - /// <param name="headers">The headers to add.</param> - /// <param name="response">The <see cref="HttpListenerResponse"/> instance to set the appropriate values to.</param> - internal static void ApplyHeadersToResponse(WebHeaderCollection headers, HttpListenerResponse response) { - Requires.NotNull(headers, "headers"); - Requires.NotNull(response, "response"); - - foreach (string headerName in headers) { - switch (headerName) { - case "Content-Type": - response.ContentType = headers[HttpResponseHeader.ContentType]; - break; - - // Add more special cases here as necessary. - default: - response.AddHeader(headerName, headers[headerName]); - break; - } - } - } - - /// <summary> /// Copies the contents of one stream to another. /// </summary> /// <param name="copyFrom">The stream to copy from, at the position where copying should begin.</param> @@ -1179,80 +1174,20 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> - /// Clones an <see cref="HttpWebRequest"/> in order to send it again. - /// </summary> - /// <param name="request">The request to clone.</param> - /// <returns>The newly created instance.</returns> - internal static HttpWebRequest Clone(this HttpWebRequest request) { - Requires.NotNull(request, "request"); - Requires.That(request.RequestUri != null, "request", "request.RequestUri cannot be null."); - return Clone(request, request.RequestUri); - } - - /// <summary> - /// Clones an <see cref="HttpWebRequest"/> in order to send it again. + /// Clones an <see cref="HttpWebRequest" /> in order to send it again. /// </summary> - /// <param name="request">The request to clone.</param> - /// <param name="newRequestUri">The new recipient of the request.</param> - /// <returns>The newly created instance.</returns> - internal static HttpWebRequest Clone(this HttpWebRequest request, Uri newRequestUri) { + /// <param name="message">The message to set headers on.</param> + /// <param name="request">The request with headers to clone.</param> + internal static void CopyHeadersFrom(this HttpRequestMessage message, HttpRequestBase request) { Requires.NotNull(request, "request"); - Requires.NotNull(newRequestUri, "newRequestUri"); - - var newRequest = (HttpWebRequest)WebRequest.Create(newRequestUri); + Requires.NotNull(message, "message"); - // First copy headers. Only set those that are explicitly set on the original request, - // because some properties (like IfModifiedSince) activate special behavior when set, - // even when set to their "original" values. foreach (string headerName in request.Headers) { - switch (headerName) { - case "Accept": newRequest.Accept = request.Accept; break; - case "Connection": break; // Keep-Alive controls this - case "Content-Length": newRequest.ContentLength = request.ContentLength; break; - case "Content-Type": newRequest.ContentType = request.ContentType; break; - case "Expect": newRequest.Expect = request.Expect; break; - case "Host": break; // implicitly copied as part of the RequestUri - case "If-Modified-Since": newRequest.IfModifiedSince = request.IfModifiedSince; break; - case "Keep-Alive": newRequest.KeepAlive = request.KeepAlive; break; - case "Proxy-Connection": break; // no property equivalent? - case "Referer": newRequest.Referer = request.Referer; break; - case "Transfer-Encoding": newRequest.TransferEncoding = request.TransferEncoding; break; - case "User-Agent": newRequest.UserAgent = request.UserAgent; break; - default: newRequest.Headers[headerName] = request.Headers[headerName]; break; + string[] headerValues = request.Headers.GetValues(headerName); + if (!message.Headers.TryAddWithoutValidation(headerName, headerValues)) { + message.Content.Headers.TryAddWithoutValidation(headerName, headerValues); } } - - newRequest.AllowAutoRedirect = request.AllowAutoRedirect; - newRequest.AllowWriteStreamBuffering = request.AllowWriteStreamBuffering; - newRequest.AuthenticationLevel = request.AuthenticationLevel; - newRequest.AutomaticDecompression = request.AutomaticDecompression; - newRequest.CachePolicy = request.CachePolicy; - newRequest.ClientCertificates = request.ClientCertificates; - newRequest.ConnectionGroupName = request.ConnectionGroupName; - newRequest.ContinueDelegate = request.ContinueDelegate; - newRequest.CookieContainer = request.CookieContainer; - newRequest.Credentials = request.Credentials; - newRequest.ImpersonationLevel = request.ImpersonationLevel; - newRequest.MaximumAutomaticRedirections = request.MaximumAutomaticRedirections; - newRequest.MaximumResponseHeadersLength = request.MaximumResponseHeadersLength; - newRequest.MediaType = request.MediaType; - newRequest.Method = request.Method; - newRequest.Pipelined = request.Pipelined; - newRequest.PreAuthenticate = request.PreAuthenticate; - newRequest.ProtocolVersion = request.ProtocolVersion; - newRequest.ReadWriteTimeout = request.ReadWriteTimeout; - newRequest.SendChunked = request.SendChunked; - newRequest.Timeout = request.Timeout; - newRequest.UseDefaultCredentials = request.UseDefaultCredentials; - - try { - newRequest.Proxy = request.Proxy; - newRequest.UnsafeAuthenticatedConnectionSharing = request.UnsafeAuthenticatedConnectionSharing; - } catch (SecurityException) { - Logger.Messaging.Warn("Unable to clone some HttpWebRequest properties due to partial trust."); - } - - return newRequest; } /// <summary> @@ -1503,8 +1438,8 @@ namespace DotNetOpenAuth.Messaging { /// <param name="request">The request to get recipient information from.</param> /// <returns>The recipient.</returns> /// <exception cref="ArgumentException">Thrown if the HTTP request is something we can't handle.</exception> - internal static MessageReceivingEndpoint GetRecipient(this HttpRequestBase request) { - return new MessageReceivingEndpoint(request.GetPublicFacingUrl(), GetHttpDeliveryMethod(request.HttpMethod)); + internal static MessageReceivingEndpoint GetRecipient(this HttpRequestMessage request) { + return new MessageReceivingEndpoint(request.RequestUri, GetHttpDeliveryMethod(request.Method.Method)); } /// <summary> @@ -1538,23 +1473,23 @@ namespace DotNetOpenAuth.Messaging { /// </summary> /// <param name="httpMethod">The HTTP method.</param> /// <returns>An HTTP verb, such as GET, POST, PUT, DELETE, PATCH, or OPTION.</returns> - internal static string GetHttpVerb(HttpDeliveryMethods httpMethod) { + internal static HttpMethod GetHttpVerb(HttpDeliveryMethods httpMethod) { if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.GetRequest) { - return "GET"; + return HttpMethod.Get; } else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.PostRequest) { - return "POST"; + return HttpMethod.Post; } else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.PutRequest) { - return "PUT"; + return HttpMethod.Put; } else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.DeleteRequest) { - return "DELETE"; + return HttpMethod.Delete; } else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.HeadRequest) { - return "HEAD"; + return HttpMethod.Head; } else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.PatchRequest) { - return "PATCH"; + return new HttpMethod("PATCH"); } else if ((httpMethod & HttpDeliveryMethods.HttpVerbMask) == HttpDeliveryMethods.OptionsRequest) { - return "OPTIONS"; + return HttpMethod.Options; } else if ((httpMethod & HttpDeliveryMethods.AuthorizationHeaderRequest) != 0) { - return "GET"; // if AuthorizationHeaderRequest is specified without an explicit HTTP verb, assume GET. + return HttpMethod.Get; // if AuthorizationHeaderRequest is specified without an explicit HTTP verb, assume GET. } else { throw ErrorUtilities.ThrowArgumentNamed("httpMethod", MessagingStrings.UnsupportedHttpVerb, httpMethod); } @@ -1580,6 +1515,29 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> + /// Gets the URI that contains the entire payload that would be sent by the browser for the specified redirect-based request message. + /// </summary> + /// <param name="response">The redirecting response message.</param> + /// <returns>The absolute URI that could be retrieved to send the same message the browser would.</returns> + /// <exception cref="System.NotSupportedException">Thrown if the message is not a redirect message.</exception> + internal static Uri GetDirectUriRequest(this HttpResponseMessage response) { + Requires.NotNull(response, "response"); + Requires.Argument( + response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.RedirectKeepVerb + || response.StatusCode == HttpStatusCode.RedirectMethod || response.StatusCode == HttpStatusCode.TemporaryRedirect, + "response", + "Redirecting response expected."); + + if (response.Headers.Location != null) { + return response.Headers.Location; + } else { + // Some responses are so large that they're HTML/JS self-posting pages. + // We can't create long URLs for those, at present. + throw new NotSupportedException(); + } + } + + /// <summary> /// Collects a sequence of key=value pairs into a dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> @@ -1592,6 +1550,21 @@ namespace DotNetOpenAuth.Messaging { } /// <summary> + /// Enumerates all members of the collection as key=value pairs. + /// </summary> + /// <param name="nvc">The collection to enumerate.</param> + /// <returns>A sequence of pairs.</returns> + internal static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection nvc) { + Requires.NotNull(nvc, "nvc"); + + foreach (string key in nvc) { + foreach (string value in nvc.GetValues(key)) { + yield return new KeyValuePair<string, string>(key, value); + } + } + } + + /// <summary> /// Converts a <see cref="NameValueCollection"/> to an IDictionary<string, string>. /// </summary> /// <param name="nvc">The NameValueCollection to convert. May be null.</param> @@ -1862,6 +1835,11 @@ namespace DotNetOpenAuth.Messaging { internal static string EscapeUriDataStringRfc3986(string value) { Requires.NotNull(value, "value"); + // fast path for empty values. + if (value.Length == 0) { + return value; + } + // Start with RFC 2396 escaping by calling the .NET method to do the work. // This MAY sometimes exhibit RFC 3986 behavior (according to the documentation). // If it does, the escaping we do that follows it will be a no-op since the @@ -2039,5 +2017,33 @@ namespace DotNetOpenAuth.Messaging { #endregion } + + /// <summary> + /// An MVC <see cref="ActionResult"/> that wraps an <see cref="HttpResponseMessage"/> + /// </summary> + private class HttpResponseMessageActionResult : ActionResult { + /// <summary> + /// The wrapped response. + /// </summary> + private readonly HttpResponseMessage response; + + /// <summary> + /// Initializes a new instance of the <see cref="HttpResponseMessageActionResult"/> class. + /// </summary> + /// <param name="response">The response.</param> + internal HttpResponseMessageActionResult(HttpResponseMessage response) { + Requires.NotNull(response, "response"); + this.response = response; + } + + /// <summary> + /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult" /> class. + /// </summary> + /// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param> + public override void ExecuteResult(ControllerContext context) { + // TODO: fix this to be asynchronous. + this.response.SendAsync(context.HttpContext).GetAwaiter().GetResult(); + } + } } } diff --git a/src/DotNetOpenAuth.Core/Messaging/MultipartContentMember.cs b/src/DotNetOpenAuth.Core/Messaging/MultipartContentMember.cs new file mode 100644 index 0000000..fd5bfb5 --- /dev/null +++ b/src/DotNetOpenAuth.Core/Messaging/MultipartContentMember.cs @@ -0,0 +1,56 @@ +//----------------------------------------------------------------------- +// <copyright file="MultipartContentMember.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Messaging { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + + /// <summary> + /// Describes a part from a multi-part POST. + /// </summary> + public struct MultipartContentMember { + /// <summary> + /// Initializes a new instance of the <see cref="MultipartContentMember"/> struct. + /// </summary> + /// <param name="content">The content.</param> + /// <param name="name">The name of this part as it may come from an HTML form.</param> + /// <param name="fileName">Name of the file.</param> + public MultipartContentMember(HttpContent content, string name = null, string fileName = null) + : this() { + this.Content = content; + this.Name = name; + this.FileName = fileName; + } + + /// <summary> + /// Gets or sets the content. + /// </summary> + /// <value> + /// The content. + /// </value> + public HttpContent Content { get; set; } + + /// <summary> + /// Gets or sets the HTML form name. + /// </summary> + /// <value> + /// The name. + /// </value> + public string Name { get; set; } + + /// <summary> + /// Gets or sets the name of the file. + /// </summary> + /// <value> + /// The name of the file. + /// </value> + public string FileName { get; set; } + } +} diff --git a/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs b/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs deleted file mode 100644 index b4a0968..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/MultipartPostPart.cs +++ /dev/null @@ -1,223 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="MultipartPostPart.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using System.IO; - using System.Net; - using System.Text; - using Validation; - - /// <summary> - /// Represents a single part in a HTTP multipart POST request. - /// </summary> - public class MultipartPostPart : IDisposable { - /// <summary> - /// The "Content-Disposition" string. - /// </summary> - private const string ContentDispositionHeader = "Content-Disposition"; - - /// <summary> - /// The two-character \r\n newline character sequence to use. - /// </summary> - private const string NewLine = "\r\n"; - - /// <summary> - /// Initializes a new instance of the <see cref="MultipartPostPart"/> class. - /// </summary> - /// <param name="contentDisposition">The content disposition of the part.</param> - public MultipartPostPart(string contentDisposition) { - Requires.NotNullOrEmpty(contentDisposition, "contentDisposition"); - - this.ContentDisposition = contentDisposition; - this.ContentAttributes = new Dictionary<string, string>(); - this.PartHeaders = new WebHeaderCollection(); - } - - /// <summary> - /// Gets or sets the content disposition. - /// </summary> - /// <value>The content disposition.</value> - public string ContentDisposition { get; set; } - - /// <summary> - /// Gets the key=value attributes that appear on the same line as the Content-Disposition. - /// </summary> - /// <value>The content attributes.</value> - public IDictionary<string, string> ContentAttributes { get; private set; } - - /// <summary> - /// Gets the headers that appear on subsequent lines after the Content-Disposition. - /// </summary> - public WebHeaderCollection PartHeaders { get; private set; } - - /// <summary> - /// Gets or sets the content of the part. - /// </summary> - public Stream Content { get; set; } - - /// <summary> - /// Gets the length of this entire part. - /// </summary> - /// <remarks>Useful for calculating the ContentLength HTTP header to send before actually serializing the content.</remarks> - public long Length { - get { - ErrorUtilities.VerifyOperation(this.Content != null && this.Content.Length >= 0, MessagingStrings.StreamMustHaveKnownLength); - - long length = 0; - length += ContentDispositionHeader.Length; - length += ": ".Length; - length += this.ContentDisposition.Length; - foreach (var pair in this.ContentAttributes) { - length += "; ".Length + pair.Key.Length + "=\"".Length + pair.Value.Length + "\"".Length; - } - - length += NewLine.Length; - foreach (string headerName in this.PartHeaders) { - length += headerName.Length; - length += ": ".Length; - length += this.PartHeaders[headerName].Length; - length += NewLine.Length; - } - - length += NewLine.Length; - length += this.Content.Length; - - return length; - } - } - - /// <summary> - /// Creates a part that represents a simple form field. - /// </summary> - /// <param name="name">The name of the form field.</param> - /// <param name="value">The value.</param> - /// <returns>The constructed part.</returns> - public static MultipartPostPart CreateFormPart(string name, string value) { - Requires.NotNullOrEmpty(name, "name"); - Requires.NotNull(value, "value"); - - var part = new MultipartPostPart("form-data"); - try { - part.ContentAttributes["name"] = name; - part.Content = new MemoryStream(Encoding.UTF8.GetBytes(value)); - return part; - } catch { - part.Dispose(); - throw; - } - } - - /// <summary> - /// Creates a part that represents a file attachment. - /// </summary> - /// <param name="name">The name of the form field.</param> - /// <param name="filePath">The path to the file to send.</param> - /// <param name="contentType">Type of the content in HTTP Content-Type format.</param> - /// <returns>The constructed part.</returns> - public static MultipartPostPart CreateFormFilePart(string name, string filePath, string contentType) { - Requires.NotNullOrEmpty(name, "name"); - Requires.NotNullOrEmpty(filePath, "filePath"); - Requires.NotNullOrEmpty(contentType, "contentType"); - - string fileName = Path.GetFileName(filePath); - var fileStream = File.OpenRead(filePath); - try { - return CreateFormFilePart(name, fileName, contentType, fileStream); - } catch { - fileStream.Dispose(); - throw; - } - } - - /// <summary> - /// Creates a part that represents a file attachment. - /// </summary> - /// <param name="name">The name of the form field.</param> - /// <param name="fileName">Name of the file as the server should see it.</param> - /// <param name="contentType">Type of the content in HTTP Content-Type format.</param> - /// <param name="content">The content of the file.</param> - /// <returns>The constructed part.</returns> - public static MultipartPostPart CreateFormFilePart(string name, string fileName, string contentType, Stream content) { - Requires.NotNullOrEmpty(name, "name"); - Requires.NotNullOrEmpty(fileName, "fileName"); - Requires.NotNullOrEmpty(contentType, "contentType"); - Requires.NotNull(content, "content"); - - var part = new MultipartPostPart("file"); - try { - part.ContentAttributes["name"] = name; - part.ContentAttributes["filename"] = fileName; - part.PartHeaders[HttpRequestHeader.ContentType] = contentType; - if (!contentType.StartsWith("text/", StringComparison.Ordinal)) { - part.PartHeaders["Content-Transfer-Encoding"] = "binary"; - } - - part.Content = content; - return part; - } catch { - part.Dispose(); - throw; - } - } - - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// <summary> - /// Serializes the part to a stream. - /// </summary> - /// <param name="streamWriter">The stream writer.</param> - internal void Serialize(StreamWriter streamWriter) { - // VERY IMPORTANT: any changes at all made to this must be kept in sync with the - // Length property which calculates exactly how many bytes this method will write. - streamWriter.NewLine = NewLine; - streamWriter.Write("{0}: {1}", ContentDispositionHeader, this.ContentDisposition); - foreach (var pair in this.ContentAttributes) { - streamWriter.Write("; {0}=\"{1}\"", pair.Key, pair.Value); - } - - streamWriter.WriteLine(); - foreach (string headerName in this.PartHeaders) { - streamWriter.WriteLine("{0}: {1}", headerName, this.PartHeaders[headerName]); - } - - streamWriter.WriteLine(); - streamWriter.Flush(); - this.Content.CopyTo(streamWriter.BaseStream); - } - - /// <summary> - /// Releases unmanaged and - optionally - managed resources - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool disposing) { - if (disposing) { - this.Content.Dispose(); - } - } - -#if CONTRACTS_FULL - /// <summary> - /// Verifies conditions that should be true for any valid state of this object. - /// </summary> - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called by code contracts.")] - [ContractInvariantMethod] - private void Invariant() { - Contract.Invariant(!string.IsNullOrEmpty(this.ContentDisposition)); - Contract.Invariant(this.PartHeaders != null); - Contract.Invariant(this.ContentAttributes != null); - } -#endif - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs deleted file mode 100644 index 754d71d..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/NetworkDirectWebResponse.cs +++ /dev/null @@ -1,115 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="NetworkDirectWebResponse.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Diagnostics; - using System.IO; - using System.Net; - using System.Text; - using Validation; - - /// <summary> - /// A live network HTTP response - /// </summary> - [DebuggerDisplay("{Status} {ContentType.MediaType}")] - internal class NetworkDirectWebResponse : IncomingWebResponse, IDisposable { - /// <summary> - /// The network response object, used to initialize this instance, that still needs - /// to be closed if applicable. - /// </summary> - private HttpWebResponse httpWebResponse; - - /// <summary> - /// The incoming network response stream. - /// </summary> - private Stream responseStream; - - /// <summary> - /// A value indicating whether a stream reader has already been - /// created on this instance. - /// </summary> - private bool streamReadBegun; - - /// <summary> - /// Initializes a new instance of the <see cref="NetworkDirectWebResponse"/> class. - /// </summary> - /// <param name="requestUri">The request URI.</param> - /// <param name="response">The response.</param> - internal NetworkDirectWebResponse(Uri requestUri, HttpWebResponse response) - : base(requestUri, response) { - Requires.NotNull(requestUri, "requestUri"); - Requires.NotNull(response, "response"); - this.httpWebResponse = response; - this.responseStream = response.GetResponseStream(); - } - - /// <summary> - /// Gets the body of the HTTP response. - /// </summary> - public override Stream ResponseStream { - get { return this.responseStream; } - } - - /// <summary> - /// Creates a text reader for the response stream. - /// </summary> - /// <returns>The text reader, initialized for the proper encoding.</returns> - public override StreamReader GetResponseReader() { - this.streamReadBegun = true; - if (this.responseStream == null) { - throw new ObjectDisposedException(GetType().Name); - } - - string contentEncoding = this.Headers[HttpResponseHeader.ContentEncoding]; - if (string.IsNullOrEmpty(contentEncoding)) { - return new StreamReader(this.ResponseStream); - } else { - return new StreamReader(this.ResponseStream, Encoding.GetEncoding(contentEncoding)); - } - } - - /// <summary> - /// Gets an offline snapshot version of this instance. - /// </summary> - /// <param name="maximumBytesToCache">The maximum bytes from the response stream to cache.</param> - /// <returns>A snapshot version of this instance.</returns> - /// <remarks> - /// If this instance is a <see cref="NetworkDirectWebResponse"/> creating a snapshot - /// will automatically close and dispose of the underlying response stream. - /// If this instance is a <see cref="CachedDirectWebResponse"/>, the result will - /// be the self same instance. - /// </remarks> - internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) { - ErrorUtilities.VerifyOperation(!this.streamReadBegun, "Network stream reading has already begun."); - ErrorUtilities.VerifyOperation(this.httpWebResponse != null, "httpWebResponse != null"); - - this.streamReadBegun = true; - var result = new CachedDirectWebResponse(this.RequestUri, this.httpWebResponse, maximumBytesToCache); - this.Dispose(); - return result; - } - - /// <summary> - /// Releases unmanaged and - optionally - managed resources - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected override void Dispose(bool disposing) { - if (disposing) { - if (this.responseStream != null) { - this.responseStream.Dispose(); - this.responseStream = null; - } - if (this.httpWebResponse != null) { - this.httpWebResponse.Close(); - this.httpWebResponse = null; - } - } - - base.Dispose(disposing); - } - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs deleted file mode 100644 index be7774f..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponse.cs +++ /dev/null @@ -1,385 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OutgoingWebResponse.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.ComponentModel; - using System.Diagnostics.CodeAnalysis; - using System.IO; - using System.Net; - using System.Net.Mime; - using System.ServiceModel.Web; - using System.Text; - using System.Threading; - using System.Web; - using Validation; - - /// <summary> - /// A protocol message (request or response) that passes from this - /// to a remote party via the user agent using a redirect or form - /// POST submission, OR a direct message response. - /// </summary> - /// <remarks> - /// <para>An instance of this type describes the HTTP response that must be sent - /// in response to the current HTTP request.</para> - /// <para>It is important that this response make up the entire HTTP response. - /// A hosting ASPX page should not be allowed to render its normal HTML output - /// after this response is sent. The normal rendered output of an ASPX page - /// can be canceled by calling <see cref="HttpResponse.End"/> after this message - /// is sent on the response stream.</para> - /// </remarks> - public class OutgoingWebResponse { - /// <summary> - /// The encoder to use for serializing the response body. - /// </summary> - private static Encoding bodyStringEncoder = new UTF8Encoding(false); - - /// <summary> - /// Initializes a new instance of the <see cref="OutgoingWebResponse"/> class. - /// </summary> - internal OutgoingWebResponse() { - this.Status = HttpStatusCode.OK; - this.Headers = new WebHeaderCollection(); - this.Cookies = new HttpCookieCollection(); - } - - /// <summary> - /// Initializes a new instance of the <see cref="OutgoingWebResponse"/> class - /// based on the contents of an <see cref="HttpWebResponse"/>. - /// </summary> - /// <param name="response">The <see cref="HttpWebResponse"/> to clone.</param> - /// <param name="maximumBytesToRead">The maximum bytes to read from the response stream.</param> - protected internal OutgoingWebResponse(HttpWebResponse response, int maximumBytesToRead) { - Requires.NotNull(response, "response"); - - this.Status = response.StatusCode; - this.Headers = response.Headers; - this.Cookies = new HttpCookieCollection(); - this.ResponseStream = new MemoryStream(response.ContentLength < 0 ? 4 * 1024 : (int)response.ContentLength); - using (Stream responseStream = response.GetResponseStream()) { - // BUGBUG: strictly speaking, is the response were exactly the limit, we'd report it as truncated here. - this.IsResponseTruncated = responseStream.CopyUpTo(this.ResponseStream, maximumBytesToRead) == maximumBytesToRead; - this.ResponseStream.Seek(0, SeekOrigin.Begin); - } - } - - /// <summary> - /// Gets the headers that must be included in the response to the user agent. - /// </summary> - /// <remarks> - /// The headers in this collection are not meant to be a comprehensive list - /// of exactly what should be sent, but are meant to augment whatever headers - /// are generally included in a typical response. - /// </remarks> - public WebHeaderCollection Headers { get; internal set; } - - /// <summary> - /// Gets the body of the HTTP response. - /// </summary> - public Stream ResponseStream { get; internal set; } - - /// <summary> - /// Gets a value indicating whether the response stream is incomplete due - /// to a length limitation imposed by the HttpWebRequest or calling method. - /// </summary> - public bool IsResponseTruncated { get; internal set; } - - /// <summary> - /// Gets the cookies collection to add as headers to the HTTP response. - /// </summary> - public HttpCookieCollection Cookies { get; internal set; } - - /// <summary> - /// Gets or sets the body of the response as a string. - /// </summary> - public string Body { - get { return this.ResponseStream != null ? this.GetResponseReader().ReadToEnd() : null; } - set { this.SetResponse(value, null); } - } - - /// <summary> - /// Gets the HTTP status code to use in the HTTP response. - /// </summary> - public HttpStatusCode Status { get; internal set; } - - /// <summary> - /// Gets or sets a reference to the actual protocol message that - /// is being sent via the user agent. - /// </summary> - internal IProtocolMessage OriginalMessage { get; set; } - - /// <summary> - /// Creates a text reader for the response stream. - /// </summary> - /// <returns>The text reader, initialized for the proper encoding.</returns> - [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Costly operation")] - public StreamReader GetResponseReader() { - this.ResponseStream.Seek(0, SeekOrigin.Begin); - string contentEncoding = this.Headers[HttpResponseHeader.ContentEncoding]; - if (string.IsNullOrEmpty(contentEncoding)) { - return new StreamReader(this.ResponseStream); - } else { - return new StreamReader(this.ResponseStream, Encoding.GetEncoding(contentEncoding)); - } - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and ends execution on the current page or handler. - /// </summary> - /// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception> - /// <remarks> - /// Requires a current HttpContext. - /// </remarks> - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void Send() { - RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - - this.Send(HttpContext.Current); - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and ends execution on the current page or handler. - /// </summary> - /// <param name="context">The context of the HTTP request whose response should be set. - /// Typically this is <see cref="HttpContext.Current"/>.</param> - /// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception> - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void Send(HttpContext context) { - this.Respond(new HttpContextWrapper(context), true); - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and ends execution on the current page or handler. - /// </summary> - /// <param name="context">The context of the HTTP request whose response should be set. - /// Typically this is <see cref="HttpContext.Current"/>.</param> - /// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception> - [EditorBrowsable(EditorBrowsableState.Never)] - public virtual void Send(HttpContextBase context) { - this.Respond(context, true); - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and signals ASP.NET to short-circuit the page execution pipeline - /// now that the response has been completed. - /// Not safe to call from ASP.NET web forms. - /// </summary> - /// <remarks> - /// Requires a current HttpContext. - /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because - /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response. - /// Use the <see cref="Send()"/> method instead for web forms. - /// </remarks> - public virtual void Respond() { - RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - - this.Respond(HttpContext.Current); - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and signals ASP.NET to short-circuit the page execution pipeline - /// now that the response has been completed. - /// Not safe to call from ASP.NET web forms. - /// </summary> - /// <param name="context">The context of the HTTP request whose response should be set. - /// Typically this is <see cref="HttpContext.Current"/>.</param> - /// <remarks> - /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because - /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response. - /// Use the <see cref="Send()"/> method instead for web forms. - /// </remarks> - public void Respond(HttpContext context) { - Requires.NotNull(context, "context"); - this.Respond(new HttpContextWrapper(context)); - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and signals ASP.NET to short-circuit the page execution pipeline - /// now that the response has been completed. - /// Not safe to call from ASP.NET web forms. - /// </summary> - /// <param name="context">The context of the HTTP request whose response should be set. - /// Typically this is <see cref="HttpContext.Current"/>.</param> - /// <remarks> - /// This call is not safe to make from an ASP.NET web form (.aspx file or code-behind) because - /// ASP.NET will render HTML after the protocol message has been sent, which will corrupt the response. - /// Use the <see cref="Send()"/> method instead for web forms. - /// </remarks> - public virtual void Respond(HttpContextBase context) { - Requires.NotNull(context, "context"); - - this.Respond(context, false); - } - - /// <summary> - /// Submits this response to a WCF response context. Only available when no response body is included. - /// </summary> - /// <param name="responseContext">The response context to apply the response to.</param> - public virtual void Respond(OutgoingWebResponseContext responseContext) { - Requires.NotNull(responseContext, "responseContext"); - if (this.ResponseStream != null) { - throw new NotSupportedException(Strings.ResponseBodyNotSupported); - } - - responseContext.StatusCode = this.Status; - responseContext.SuppressEntityBody = true; - foreach (string header in this.Headers) { - responseContext.Headers[header] = this.Headers[header]; - } - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent. - /// </summary> - /// <param name="response">The response to set to this message.</param> - public virtual void Send(HttpListenerResponse response) { - Requires.NotNull(response, "response"); - - response.StatusCode = (int)this.Status; - MessagingUtilities.ApplyHeadersToResponse(this.Headers, response); - foreach (HttpCookie httpCookie in this.Cookies) { - var cookie = new Cookie(httpCookie.Name, httpCookie.Value) { - Expires = httpCookie.Expires, - Path = httpCookie.Path, - HttpOnly = httpCookie.HttpOnly, - Secure = httpCookie.Secure, - Domain = httpCookie.Domain, - }; - response.AppendCookie(cookie); - } - - if (this.ResponseStream != null) { - response.ContentLength64 = this.ResponseStream.Length; - this.ResponseStream.CopyTo(response.OutputStream); - } - - response.OutputStream.Close(); - } - - /// <summary> - /// Gets the URI that, when requested with an HTTP GET request, - /// would transmit the message that normally would be transmitted via a user agent redirect. - /// </summary> - /// <param name="channel">The channel to use for encoding.</param> - /// <returns> - /// The URL that would transmit the original message. This URL may exceed the normal 2K limit, - /// and should therefore be broken up manually and POSTed as form fields when it exceeds this length. - /// </returns> - /// <remarks> - /// This is useful for desktop applications that will spawn a user agent to transmit the message - /// rather than cause a redirect. - /// </remarks> - internal Uri GetDirectUriRequest(Channel channel) { - Requires.NotNull(channel, "channel"); - - var message = this.OriginalMessage as IDirectedProtocolMessage; - if (message == null) { - throw new InvalidOperationException(); // this only makes sense for directed messages (indirect responses) - } - - var fields = channel.MessageDescriptions.GetAccessor(message).Serialize(); - UriBuilder builder = new UriBuilder(message.Recipient); - MessagingUtilities.AppendQueryArgs(builder, fields); - return builder.Uri; - } - - /// <summary> - /// Sets the response to some string, encoded as UTF-8. - /// </summary> - /// <param name="body">The string to set the response to.</param> - /// <param name="contentType">Type of the content. May be null.</param> - internal void SetResponse(string body, ContentType contentType) { - if (body == null) { - this.ResponseStream = null; - return; - } - - if (contentType == null) { - contentType = new ContentType("text/html"); - contentType.CharSet = bodyStringEncoder.WebName; - } else if (contentType.CharSet != bodyStringEncoder.WebName) { - // clone the original so we're not tampering with our inputs if it came as a parameter. - contentType = new ContentType(contentType.ToString()); - contentType.CharSet = bodyStringEncoder.WebName; - } - - this.Headers[HttpResponseHeader.ContentType] = contentType.ToString(); - this.ResponseStream = new MemoryStream(); - StreamWriter writer = new StreamWriter(this.ResponseStream, bodyStringEncoder); - writer.Write(body); - writer.Flush(); - this.ResponseStream.Seek(0, SeekOrigin.Begin); - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and signals ASP.NET to short-circuit the page execution pipeline - /// now that the response has been completed. - /// </summary> - /// <param name="context">The context of the HTTP request whose response should be set. - /// Typically this is <see cref="HttpContext.Current"/>.</param> - /// <param name="endRequest">If set to <c>false</c>, this method calls - /// <see cref="HttpApplication.CompleteRequest"/> rather than <see cref="HttpResponse.End"/> - /// to avoid a <see cref="ThreadAbortException"/>.</param> - protected internal void Respond(HttpContext context, bool endRequest) { - this.Respond(new HttpContextWrapper(context), endRequest); - } - - /// <summary> - /// Automatically sends the appropriate response to the user agent - /// and signals ASP.NET to short-circuit the page execution pipeline - /// now that the response has been completed. - /// </summary> - /// <param name="context">The context of the HTTP request whose response should be set. - /// Typically this is <see cref="HttpContext.Current"/>.</param> - /// <param name="endRequest">If set to <c>false</c>, this method calls - /// <see cref="HttpApplication.CompleteRequest"/> rather than <see cref="HttpResponse.End"/> - /// to avoid a <see cref="ThreadAbortException"/>.</param> - protected internal virtual void Respond(HttpContextBase context, bool endRequest) { - Requires.NotNull(context, "context"); - - context.Response.Clear(); - context.Response.StatusCode = (int)this.Status; - MessagingUtilities.ApplyHeadersToResponse(this.Headers, context.Response); - if (this.ResponseStream != null) { - try { - this.ResponseStream.CopyTo(context.Response.OutputStream); - } catch (HttpException ex) { - if (ex.ErrorCode == -2147467259 && context.Response.Output != null) { - // Test scenarios can generate this, since the stream is being spoofed: - // System.Web.HttpException: OutputStream is not available when a custom TextWriter is used. - context.Response.Output.Write(this.Body); - } else { - throw; - } - } - } - - foreach (string cookieName in this.Cookies) { - var cookie = this.Cookies[cookieName]; - context.Response.AppendCookie(cookie); - } - - if (endRequest) { - // This approach throws an exception in order that - // no more code is executed in the calling page. - // Microsoft no longer recommends this approach. - context.Response.End(); - } else if (context.ApplicationInstance != null) { - // This approach doesn't throw an exception, but - // still tells ASP.NET to short-circuit most of the - // request handling pipeline to speed things up. - context.ApplicationInstance.CompleteRequest(); - } - } - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs b/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs deleted file mode 100644 index bc2f985..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/OutgoingWebResponseActionResult.cs +++ /dev/null @@ -1,45 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OutgoingWebResponseActionResult.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Web.Mvc; - using DotNetOpenAuth.Messaging; - using Validation; - - /// <summary> - /// An ASP.NET MVC structure to represent the response to send - /// to the user agent when the controller has finished its work. - /// </summary> - internal class OutgoingWebResponseActionResult : ActionResult { - /// <summary> - /// The outgoing web response to send when the ActionResult is executed. - /// </summary> - private readonly OutgoingWebResponse response; - - /// <summary> - /// Initializes a new instance of the <see cref="OutgoingWebResponseActionResult"/> class. - /// </summary> - /// <param name="response">The response.</param> - internal OutgoingWebResponseActionResult(OutgoingWebResponse response) { - Requires.NotNull(response, "response"); - this.response = response; - } - - /// <summary> - /// Enables processing of the result of an action method by a custom type that inherits from <see cref="T:System.Web.Mvc.ActionResult"/>. - /// </summary> - /// <param name="context">The context in which to set the response.</param> - public override void ExecuteResult(ControllerContext context) { - this.response.Respond(context.HttpContext); - - // MVC likes to muck with our response. For example, when returning contrived 401 Unauthorized responses - // MVC will rewrite our response and turn it into a redirect, which breaks OAuth 2 authorization server token endpoints. - // It turns out we can prevent this unwanted behavior by flushing the response before returning from this method. - context.HttpContext.Response.Flush(); - } - } -} diff --git a/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs b/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs index 4d5c418..b5cab3b 100644 --- a/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs +++ b/src/DotNetOpenAuth.Core/Messaging/ProtocolFaultResponseException.cs @@ -8,7 +8,10 @@ namespace DotNetOpenAuth.Messaging { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using Validation; /// <summary> @@ -61,10 +64,12 @@ namespace DotNetOpenAuth.Messaging { /// <summary> /// Creates the HTTP response to forward to the client to report the error. /// </summary> - /// <returns>The HTTP response.</returns> - public OutgoingWebResponse CreateErrorResponse() { - var response = this.channel.PrepareResponse(this.ErrorResponseMessage); - return response; + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The HTTP response. + /// </returns> + public Task<HttpResponseMessage> CreateErrorResponseAsync(CancellationToken cancellationToken) { + return this.channel.PrepareResponseAsync(this.ErrorResponseMessage, cancellationToken); } } } diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs index 9cb80b0..413d0ad 100644 --- a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs +++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs @@ -27,16 +27,15 @@ namespace DotNetOpenAuth.Messaging { private readonly ICollection<Version> versions; /// <summary> - /// Initializes a new instance of the <see cref="StandardMessageFactoryChannel"/> class. + /// Initializes a new instance of the <see cref="StandardMessageFactoryChannel" /> class. /// </summary> /// <param name="messageTypes">The message types that might be encountered.</param> /// <param name="versions">All the possible message versions that might be encountered.</param> - /// <param name="bindingElements"> - /// The binding elements to use in sending and receiving messages. - /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages. - /// </param> - protected StandardMessageFactoryChannel(ICollection<Type> messageTypes, ICollection<Version> versions, params IChannelBindingElement[] bindingElements) - : base(new StandardMessageFactory(), bindingElements) { + /// <param name="hostFactories">The host factories.</param> + /// <param name="bindingElements">The binding elements to use in sending and receiving messages. + /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages.</param> + protected StandardMessageFactoryChannel(ICollection<Type> messageTypes, ICollection<Version> versions, IHostFactories hostFactories, IChannelBindingElement[] bindingElements = null) + : base(new StandardMessageFactory(), bindingElements ?? new IChannelBindingElement[0], hostFactories) { Requires.NotNull(messageTypes, "messageTypes"); Requires.NotNull(versions, "versions"); diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs b/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs deleted file mode 100644 index 2383a5b..0000000 --- a/src/DotNetOpenAuth.Core/Messaging/StandardWebRequestHandler.cs +++ /dev/null @@ -1,261 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="StandardWebRequestHandler.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Messaging { - using System; - using System.Diagnostics; - using System.Diagnostics.Contracts; - using System.IO; - using System.Net; - using System.Net.Sockets; - using System.Reflection; - using DotNetOpenAuth.Messaging; - using Validation; - - /// <summary> - /// The default handler for transmitting <see cref="HttpWebRequest"/> instances - /// and returning the responses. - /// </summary> - public class StandardWebRequestHandler : IDirectWebRequestHandler { - /// <summary> - /// The set of options this web request handler supports. - /// </summary> - private const DirectWebRequestOptions SupportedOptions = DirectWebRequestOptions.AcceptAllHttpResponses; - - /// <summary> - /// The value to use for the User-Agent HTTP header. - /// </summary> - private static string userAgentValue = Assembly.GetExecutingAssembly().GetName().Name + "/" + Util.AssemblyFileVersion; - - #region IWebRequestHandler Members - - /// <summary> - /// Determines whether this instance can support the specified options. - /// </summary> - /// <param name="options">The set of options that might be given in a subsequent web request.</param> - /// <returns> - /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>. - /// </returns> - [Pure] - public bool CanSupport(DirectWebRequestOptions options) { - return (options & ~SupportedOptions) == 0; - } - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <returns> - /// The writer the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - public Stream GetRequestStream(HttpWebRequest request) { - return this.GetRequestStream(request, DirectWebRequestOptions.None); - } - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns> - /// The writer the caller should write out the entity data to. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - public Stream GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) { - return GetRequestStreamCore(request); - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <returns> - /// An instance of <see cref="IncomingWebResponse"/> describing the response. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - public IncomingWebResponse GetResponse(HttpWebRequest request) { - return this.GetResponse(request, DirectWebRequestOptions.None); - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <param name="options">The options to apply to this web request.</param> - /// <returns> - /// An instance of <see cref="IncomingWebResponse"/> describing the response. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - public IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options) { - // This request MAY have already been prepared by GetRequestStream, but - // we have no guarantee, so do it just to be safe. - PrepareRequest(request, false); - - try { - Logger.Http.DebugFormat("HTTP {0} {1}", request.Method, request.RequestUri); - HttpWebResponse response = (HttpWebResponse)request.GetResponse(); - return new NetworkDirectWebResponse(request.RequestUri, response); - } catch (WebException ex) { - HttpWebResponse response = (HttpWebResponse)ex.Response; - if (response != null && response.StatusCode == HttpStatusCode.ExpectationFailed && - request.ServicePoint.Expect100Continue) { - // Some OpenID servers doesn't understand the Expect header and send 417 error back. - // If this server just failed from that, alter the ServicePoint for this server - // so that we don't send that header again next time (whenever that is). - // "Expect: 100-Continue" HTTP header. (see Google Code Issue 72) - // We don't want to blindly set all ServicePoints to not use the Expect header - // as that would be a security hole allowing any visitor to a web site change - // the web site's global behavior when calling that host. - Logger.Http.InfoFormat("HTTP POST to {0} resulted in 417 Expectation Failed. Changing ServicePoint to not use Expect: Continue next time.", request.RequestUri); - request.ServicePoint.Expect100Continue = false; // TODO: investigate that CAS may throw here - - // An alternative to ServicePoint if we don't have permission to set that, - // but we'd have to set it BEFORE each request. - ////request.Expect = ""; - } - - if ((options & DirectWebRequestOptions.AcceptAllHttpResponses) != 0 && response != null && - response.StatusCode != HttpStatusCode.ExpectationFailed) { - Logger.Http.InfoFormat("The HTTP error code {0} {1} is being accepted because the {2} flag is set.", (int)response.StatusCode, response.StatusCode, DirectWebRequestOptions.AcceptAllHttpResponses); - return new NetworkDirectWebResponse(request.RequestUri, response); - } - - if (response != null) { - Logger.Http.ErrorFormat( - "{0} returned {1} {2}: {3}", - response.ResponseUri, - (int)response.StatusCode, - response.StatusCode, - response.StatusDescription); - - if (Logger.Http.IsDebugEnabled) { - using (var reader = new StreamReader(ex.Response.GetResponseStream())) { - Logger.Http.DebugFormat( - "WebException from {0}: {1}{2}", ex.Response.ResponseUri, Environment.NewLine, reader.ReadToEnd()); - } - } - } else { - Logger.Http.ErrorFormat( - "{0} connecting to {0}", - ex.Status, - request.RequestUri); - } - - // Be sure to close the response stream to conserve resources and avoid - // filling up all our incoming pipes and denying future requests. - // If in the future, some callers actually want to read this response - // we'll need to figure out how to reliably call Close on exception - // responses at all callers. - if (response != null) { - response.Close(); - } - - throw ErrorUtilities.Wrap(ex, MessagingStrings.ErrorInRequestReplyMessage); - } - } - - #endregion - - /// <summary> - /// Determines whether an exception was thrown because of the remote HTTP server returning HTTP 417 Expectation Failed. - /// </summary> - /// <param name="ex">The caught exception.</param> - /// <returns> - /// <c>true</c> if the failure was originally caused by a 417 Exceptation Failed error; otherwise, <c>false</c>. - /// </returns> - internal static bool IsExceptionFrom417ExpectationFailed(Exception ex) { - while (ex != null) { - WebException webEx = ex as WebException; - if (webEx != null) { - HttpWebResponse response = webEx.Response as HttpWebResponse; - if (response != null) { - if (response.StatusCode == HttpStatusCode.ExpectationFailed) { - return true; - } - } - } - - ex = ex.InnerException; - } - - return false; - } - - /// <summary> - /// Initiates a POST request and prepares for sending data. - /// </summary> - /// <param name="request">The HTTP request with information about the remote party to contact.</param> - /// <returns> - /// The stream where the POST entity can be written. - /// </returns> - private static Stream GetRequestStreamCore(HttpWebRequest request) { - PrepareRequest(request, true); - - try { - return request.GetRequestStream(); - } catch (SocketException ex) { - throw ErrorUtilities.Wrap(ex, MessagingStrings.WebRequestFailed, request.RequestUri); - } catch (WebException ex) { - throw ErrorUtilities.Wrap(ex, MessagingStrings.WebRequestFailed, request.RequestUri); - } - } - - /// <summary> - /// Prepares an HTTP request. - /// </summary> - /// <param name="request">The request.</param> - /// <param name="preparingPost"><c>true</c> if this is a POST request whose headers have not yet been sent out; <c>false</c> otherwise.</param> - private static void PrepareRequest(HttpWebRequest request, bool preparingPost) { - Requires.NotNull(request, "request"); - - // Be careful to not try to change the HTTP headers that have already gone out. - if (preparingPost || request.Method == "GET") { - // Set/override a few properties of the request to apply our policies for requests. - if (Debugger.IsAttached) { - // Since a debugger is attached, requests may be MUCH slower, - // so give ourselves huge timeouts. - request.ReadWriteTimeout = (int)TimeSpan.FromHours(1).TotalMilliseconds; - request.Timeout = (int)TimeSpan.FromHours(1).TotalMilliseconds; - } - - // Some sites, such as Technorati, return 403 Forbidden on identity - // pages unless a User-Agent header is included. - if (string.IsNullOrEmpty(request.UserAgent)) { - request.UserAgent = userAgentValue; - } - } - } - } -} diff --git a/src/DotNetOpenAuth.Core/Reporting.cs b/src/DotNetOpenAuth.Core/Reporting.cs index f902fd6..432a833 100644 --- a/src/DotNetOpenAuth.Core/Reporting.cs +++ b/src/DotNetOpenAuth.Core/Reporting.cs @@ -14,10 +14,13 @@ namespace DotNetOpenAuth { using System.IO.IsolatedStorage; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Reflection; using System.Security; using System.Text; using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; @@ -71,11 +74,6 @@ namespace DotNetOpenAuth { private static Uri wellKnownPostLocation = new Uri("https://reports.dotnetopenauth.net/ReportingPost.ashx"); /// <summary> - /// The outgoing HTTP request handler to use for publishing reports. - /// </summary> - private static IDirectWebRequestHandler webRequestHandler; - - /// <summary> /// A few HTTP request hosts and paths we've seen. /// </summary> private static PersistentHashSet observedRequests; @@ -330,7 +328,7 @@ namespace DotNetOpenAuth { lock (publishingConsiderationLock) { if (DateTime.Now - lastPublished > Configuration.MinimumReportingInterval) { lastPublished = DateTime.Now; - SendStatsAsync(); + var fireAndForget = SendStatsAsync(); } } } @@ -346,7 +344,6 @@ namespace DotNetOpenAuth { file = GetIsolatedStorage(); reportOriginIdentity = GetOrCreateOriginIdentity(); - webRequestHandler = new StandardWebRequestHandler(); observations.Add(observedRequests = new PersistentHashSet(file, "requests.txt", 3)); observations.Add(observedCultures = new PersistentHashSet(file, "cultures.txt", 20)); observations.Add(observedFeatures = new PersistentHashSet(file, "features.txt", int.MaxValue)); @@ -371,6 +368,18 @@ namespace DotNetOpenAuth { } /// <summary> + /// Creates an HTTP client that can be used for outbound HTTP requests. + /// </summary> + /// <returns>The HTTP client to use.</returns> + private static HttpClient CreateHttpClient() { + var channel = new HttpClientHandler(); + channel.AllowAutoRedirect = false; + var webRequestHandler = new HttpClient(channel); + webRequestHandler.DefaultRequestHeaders.UserAgent.Add(Util.LibraryVersionHeader); + return webRequestHandler; + } + + /// <summary> /// Assembles a report for submission. /// </summary> /// <returns>A stream that contains the report.</returns> @@ -426,30 +435,24 @@ namespace DotNetOpenAuth { /// Sends the usage reports to the library authors. /// </summary> /// <returns>A value indicating whether submitting the report was successful.</returns> - private static bool SendStats() { + private static async Task<bool> SendStatsAsync() { try { - var request = (HttpWebRequest)WebRequest.Create(wellKnownPostLocation); - request.UserAgent = Util.LibraryVersion; - request.AllowAutoRedirect = false; - request.Method = "POST"; - request.ContentType = "text/dnoa-report1"; Stream report = GetReport(); - request.ContentLength = report.Length; - using (var requestStream = webRequestHandler.GetRequestStream(request)) { - report.CopyTo(requestStream); - } - - using (var response = webRequestHandler.GetResponse(request)) { - Logger.Library.Info("Statistical report submitted successfully."); - - // The response stream may contain a message for the webmaster. - // Since as part of the report we submit the library version number, - // the report receiving service may have alerts such as: - // "You're using an obsolete version with exploitable security vulnerabilities." - using (var responseReader = response.GetResponseReader()) { - string line = responseReader.ReadLine(); - if (line != null) { - DemuxLogMessage(line); + var content = new StreamContent(report); + content.Headers.ContentType = new MediaTypeHeaderValue("text/dnoa-report1"); + using (var webRequestHandler = CreateHttpClient()) { + using (var response = await webRequestHandler.PostAsync(wellKnownPostLocation, content)) { + Logger.Library.Info("Statistical report submitted successfully."); + + // The response stream may contain a message for the webmaster. + // Since as part of the report we submit the library version number, + // the report receiving service may have alerts such as: + // "You're using an obsolete version with exploitable security vulnerabilities." + using (var responseReader = new StreamReader(await response.Content.ReadAsStreamAsync())) { + string line = await responseReader.ReadLineAsync(); + if (line != null) { + DemuxLogMessage(line); + } } } } @@ -508,28 +511,6 @@ namespace DotNetOpenAuth { } /// <summary> - /// Sends the stats report asynchronously, and careful to not throw any unhandled exceptions. - /// </summary> - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Unhandled exceptions MUST NOT be thrown from here.")] - private static void SendStatsAsync() { - // Do it on a background thread since it could take a while and we - // don't want to slow down this request we're borrowing. - ThreadPool.QueueUserWorkItem(state => { - try { - SendStats(); - } catch (Exception ex) { - // Something bad and unexpected happened. Just deactivate to avoid more trouble. - try { - broken = true; - Logger.Library.Error("Error while trying to submit statistical report.", ex); - } catch (Exception) { - // swallow exceptions to prevent a crash. - } - } - }); - } - - /// <summary> /// Gets the isolated storage to use for reporting. /// </summary> /// <returns>An isolated storage location appropriate for our host.</returns> diff --git a/src/DotNetOpenAuth.Core/Strings.Designer.cs b/src/DotNetOpenAuth.Core/Strings.Designer.cs index b0e66d2..b96f68a 100644 --- a/src/DotNetOpenAuth.Core/Strings.Designer.cs +++ b/src/DotNetOpenAuth.Core/Strings.Designer.cs @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. -// Runtime Version:4.0.30319.17622 +// Runtime Version:4.0.30319.18033 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -97,6 +97,24 @@ namespace DotNetOpenAuth { } /// <summary> + /// Looks up a localized string similar to The provided data could not be decrypted. If the current application is deployed in a web farm configuration, ensure that the 'decryptionKey' and 'validationKey' attributes are explicitly specified in the <machineKey> configuration section.. + /// </summary> + internal static string Generic_CryptoFailure { + get { + return ResourceManager.GetString("Generic_CryptoFailure", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The HostFactories property must be set first.. + /// </summary> + internal static string HostFactoriesRequired { + get { + return ResourceManager.GetString("HostFactoriesRequired", resourceCulture); + } + } + + /// <summary> /// Looks up a localized string similar to The argument has an unexpected value.. /// </summary> internal static string InvalidArgument { diff --git a/src/DotNetOpenAuth.Core/Strings.resx b/src/DotNetOpenAuth.Core/Strings.resx index f4d61d1..1c2aee2 100644 --- a/src/DotNetOpenAuth.Core/Strings.resx +++ b/src/DotNetOpenAuth.Core/Strings.resx @@ -141,4 +141,10 @@ <data name="ResponseBodyNotSupported" xml:space="preserve"> <value>This object contains a response body, which is not supported.</value> </data> + <data name="HostFactoriesRequired" xml:space="preserve"> + <value>The HostFactories property must be set first.</value> + </data> + <data name="Generic_CryptoFailure" xml:space="preserve"> + <value>The provided data could not be decrypted. If the current application is deployed in a web farm configuration, ensure that the 'decryptionKey' and 'validationKey' attributes are explicitly specified in the <machineKey> configuration section.</value> + </data> </root>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Core/Util.cs b/src/DotNetOpenAuth.Core/Util.cs index ec28c50..00d033f 100644 --- a/src/DotNetOpenAuth.Core/Util.cs +++ b/src/DotNetOpenAuth.Core/Util.cs @@ -7,12 +7,14 @@ namespace DotNetOpenAuth { using System; using System.Collections.Generic; using System.Globalization; + using System.Linq; using System.Net; + using System.Net.Http.Headers; using System.Reflection; using System.Text; + using System.Threading.Tasks; using System.Web; using System.Web.UI; - using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; @@ -28,24 +30,44 @@ namespace DotNetOpenAuth { internal const string DefaultNamespace = "DotNetOpenAuth"; /// <summary> + /// A lazily-assembled string that describes the version of the library. + /// </summary> + private static readonly Lazy<string> libraryVersionLazy = new Lazy<string>(delegate { + var assembly = Assembly.GetExecutingAssembly(); + string assemblyFullName = assembly.FullName; + bool official = assemblyFullName.Contains("PublicKeyToken=2780ccd10d57b246"); + assemblyFullName = assemblyFullName.Replace(assembly.GetName().Version.ToString(), AssemblyFileVersion); + + // We use InvariantCulture since this is used for logging. + return string.Format(CultureInfo.InvariantCulture, "{0} ({1})", assemblyFullName, official ? "official" : "private"); + }); + + /// <summary> + /// A lazily-assembled string that describes the version of the library. + /// </summary> + private static readonly Lazy<ProductInfoHeaderValue> libraryVersionHeaderLazy = new Lazy<ProductInfoHeaderValue>(delegate { + var assemblyName = Assembly.GetExecutingAssembly().GetName(); + return new ProductInfoHeaderValue(assemblyName.Name, AssemblyFileVersion); + }); + + /// <summary> /// The web.config file-specified provider of web resource URLs. /// </summary> - private static IEmbeddedResourceRetrieval embeddedResourceRetrieval = MessagingElement.Configuration.EmbeddedResourceRetrievalProvider.CreateInstance(null, false); + private static IEmbeddedResourceRetrieval embeddedResourceRetrieval = MessagingElement.Configuration.EmbeddedResourceRetrievalProvider.CreateInstance(null, false, null); /// <summary> /// Gets a human-readable description of the library name and version, including /// whether the build is an official or private one. /// </summary> internal static string LibraryVersion { - get { - var assembly = Assembly.GetExecutingAssembly(); - string assemblyFullName = assembly.FullName; - bool official = assemblyFullName.Contains("PublicKeyToken=2780ccd10d57b246"); - assemblyFullName = assemblyFullName.Replace(assembly.GetName().Version.ToString(), AssemblyFileVersion); + get { return libraryVersionLazy.Value; } + } - // We use InvariantCulture since this is used for logging. - return string.Format(CultureInfo.InvariantCulture, "{0} ({1})", assemblyFullName, official ? "official" : "private"); - } + /// <summary> + /// Gets an HTTP header that can be included in outbound requests. + /// </summary> + internal static ProductInfoHeaderValue LibraryVersionHeader { + get { return libraryVersionHeaderLazy.Value; } } /// <summary> @@ -109,7 +131,7 @@ namespace DotNetOpenAuth { foreach (var pair in pairs) { var key = pair.Key.ToString(); string value = pair.Value.ToString(); - if (messageDictionary != null && messageDictionary.Description.Mapping[key].IsSecuritySensitive) { + if (messageDictionary != null && messageDictionary.Description.Mapping.ContainsKey(key) && messageDictionary.Description.Mapping[key].IsSecuritySensitive) { value = "********"; } @@ -212,6 +234,22 @@ namespace DotNetOpenAuth { } /// <summary> + /// Creates a dictionary of a sequence of elements and the result of an asynchronous transform, + /// allowing the async work to proceed concurrently. + /// </summary> + /// <typeparam name="TSource">The type of the source.</typeparam> + /// <typeparam name="TResult">The type of the result.</typeparam> + /// <param name="source">The source.</param> + /// <param name="transform">The transform.</param> + /// <returns>A dictionary populated with the results of the transforms.</returns> + internal static async Task<Dictionary<TSource, TResult>> ToDictionaryAsync<TSource, TResult>( + this IEnumerable<TSource> source, Func<TSource, Task<TResult>> transform) { + var taskResults = source.ToDictionary(s => s, transform); + await Task.WhenAll(taskResults.Values); + return taskResults.ToDictionary(p => p.Key, p => p.Value.Result); + } + + /// <summary> /// Manages an individual deferred ToString call. /// </summary> /// <typeparam name="T">The type of object to be serialized as a string.</typeparam> diff --git a/src/DotNetOpenAuth.Core/packages.config b/src/DotNetOpenAuth.Core/packages.config index 1cf617d..6d6cb3b 100644 --- a/src/DotNetOpenAuth.Core/packages.config +++ b/src/DotNetOpenAuth.Core/packages.config @@ -1,10 +1,10 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> - <package id="Microsoft.AspNet.Mvc" version="3.0.20105.1" targetFramework="net45" /> - <package id="Microsoft.AspNet.Razor" version="1.0.20105.408" targetFramework="net45" /> - <package id="Microsoft.AspNet.WebPages" version="1.0.20105.408" targetFramework="net45" /> + <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Razor" version="2.0.20715.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" /> <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj b/src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj index 5f486ad..3e8fcf9 100644 --- a/src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj +++ b/src/DotNetOpenAuth.InfoCard.UI/DotNetOpenAuth.InfoCard.UI.csproj @@ -64,9 +64,9 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.InfoCard.UI/packages.config b/src/DotNetOpenAuth.InfoCard.UI/packages.config index 58890d8..e3309bc 100644 --- a/src/DotNetOpenAuth.InfoCard.UI/packages.config +++ b/src/DotNetOpenAuth.InfoCard.UI/packages.config @@ -1,4 +1,4 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj b/src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj index 5eacee7..b4fce7a 100644 --- a/src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj +++ b/src/DotNetOpenAuth.InfoCard/DotNetOpenAuth.InfoCard.csproj @@ -48,9 +48,9 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.InfoCard/packages.config b/src/DotNetOpenAuth.InfoCard/packages.config index 58890d8..e3309bc 100644 --- a/src/DotNetOpenAuth.InfoCard/packages.config +++ b/src/DotNetOpenAuth.InfoCard/packages.config @@ -1,4 +1,4 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth.Common/DotNetOpenAuth.OAuth.Common.csproj b/src/DotNetOpenAuth.OAuth.Common/DotNetOpenAuth.OAuth.Common.csproj index f60d9fa..95549fe 100644 --- a/src/DotNetOpenAuth.OAuth.Common/DotNetOpenAuth.OAuth.Common.csproj +++ b/src/DotNetOpenAuth.OAuth.Common/DotNetOpenAuth.OAuth.Common.csproj @@ -21,8 +21,8 @@ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> </PropertyGroup> <ItemGroup> - <Compile Include="OAuth\ChannelElements\OAuthIdentity.cs" /> <Compile Include="OAuth\ChannelElements\OAuthPrincipal.cs" /> + <Compile Include="OAuth\DefaultOAuthHostFactories.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> @@ -32,9 +32,11 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OAuth.Common/OAuth/ChannelElements/OAuthIdentity.cs b/src/DotNetOpenAuth.OAuth.Common/OAuth/ChannelElements/OAuthIdentity.cs deleted file mode 100644 index 28e0333..0000000 --- a/src/DotNetOpenAuth.OAuth.Common/OAuth/ChannelElements/OAuthIdentity.cs +++ /dev/null @@ -1,64 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OAuthIdentity.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth.ChannelElements { - using System; - using System.Diagnostics.CodeAnalysis; - using System.Runtime.InteropServices; - using System.Security.Principal; - using DotNetOpenAuth.Messaging; - using Validation; - - /// <summary> - /// Represents an OAuth consumer that is impersonating a known user on the system. - /// </summary> - [SuppressMessage("Microsoft.Interoperability", "CA1409:ComVisibleTypesShouldBeCreatable", Justification = "Not cocreatable.")] - [Serializable] - [ComVisible(true)] - public class OAuthIdentity : IIdentity { - /// <summary> - /// Initializes a new instance of the <see cref="OAuthIdentity"/> class. - /// </summary> - /// <param name="username">The username.</param> - internal OAuthIdentity(string username) { - Requires.NotNullOrEmpty(username, "username"); - this.Name = username; - } - - #region IIdentity Members - - /// <summary> - /// Gets the type of authentication used. - /// </summary> - /// <value>The constant "OAuth"</value> - /// <returns> - /// The type of authentication used to identify the user. - /// </returns> - public string AuthenticationType { - get { return "OAuth"; } - } - - /// <summary> - /// Gets a value indicating whether the user has been authenticated. - /// </summary> - /// <value>The value <c>true</c></value> - /// <returns>true if the user was authenticated; otherwise, false. - /// </returns> - public bool IsAuthenticated { - get { return true; } - } - - /// <summary> - /// Gets the name of the user who authorized the OAuth token the consumer is using for authorization. - /// </summary> - /// <returns> - /// The name of the user on whose behalf the code is running. - /// </returns> - public string Name { get; private set; } - - #endregion - } -} diff --git a/src/DotNetOpenAuth.OAuth.Common/OAuth/ChannelElements/OAuthPrincipal.cs b/src/DotNetOpenAuth.OAuth.Common/OAuth/ChannelElements/OAuthPrincipal.cs index 65d7042..988d727 100644 --- a/src/DotNetOpenAuth.OAuth.Common/OAuth/ChannelElements/OAuthPrincipal.cs +++ b/src/DotNetOpenAuth.OAuth.Common/OAuth/ChannelElements/OAuthPrincipal.cs @@ -1,6 +1,6 @@ //----------------------------------------------------------------------- -// <copyright file="OAuthPrincipal.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. +// <copyright file="OAuthPrincipal.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. // </copyright> //----------------------------------------------------------------------- @@ -11,87 +11,35 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; + using System.Security.Claims; using System.Security.Principal; + using Validation; + /// <summary> - /// Represents an OAuth consumer that is impersonating a known user on the system. + /// Utilities for dealing with OAuth claims and principals. /// </summary> - [SuppressMessage("Microsoft.Interoperability", "CA1409:ComVisibleTypesShouldBeCreatable", Justification = "Not cocreatable.")] - [Serializable] - [ComVisible(true)] - public class OAuthPrincipal : IPrincipal { - /// <summary> - /// The roles this user belongs to. - /// </summary> - private ICollection<string> roles; - - /// <summary> - /// Initializes a new instance of the <see cref="OAuthPrincipal"/> class. - /// </summary> - /// <param name="userName">The username.</param> - /// <param name="roles">The roles this user belongs to.</param> - public OAuthPrincipal(string userName, string[] roles) - : this(new OAuthIdentity(userName), roles) { - } - - /// <summary> - /// Initializes a new instance of the <see cref="OAuthPrincipal"/> class. - /// </summary> - /// <param name="identity">The identity.</param> - /// <param name="roles">The roles this user belongs to.</param> - internal OAuthPrincipal(OAuthIdentity identity, string[] roles) { - this.Identity = identity; - this.roles = roles; - } - - /// <summary> - /// Gets or sets the access token used to create this principal. - /// </summary> - /// <value>A non-empty string.</value> - public string AccessToken { get; protected set; } - + internal static class OAuthPrincipal { /// <summary> - /// Gets the roles that this principal has as a ReadOnlyCollection. + /// Creates a new instance of ClaimsPrincipal. /// </summary> - public ReadOnlyCollection<string> Roles - { - get { return new ReadOnlyCollection<string>(this.roles.ToList()); } - } - - #region IPrincipal Members - - /// <summary> - /// Gets the identity of the current principal. - /// </summary> - /// <value></value> + /// <param name="userName">Name of the user.</param> + /// <param name="roles">The roles.</param> /// <returns> - /// The <see cref="T:System.Security.Principal.IIdentity"/> object associated with the current principal. + /// A new instance of GenericPrincipal with a GenericIdentity, having the same username and roles as this OAuthPrincipal and OAuthIdentity /// </returns> - public IIdentity Identity { get; private set; } - - /// <summary> - /// Determines whether the current principal belongs to the specified role. - /// </summary> - /// <param name="role">The name of the role for which to check membership.</param> - /// <returns> - /// true if the current principal is a member of the specified role; otherwise, false. - /// </returns> - /// <remarks> - /// The role membership check uses <see cref="StringComparer.OrdinalIgnoreCase"/>. - /// </remarks> - public bool IsInRole(string role) { - return this.roles.Contains(role, StringComparer.OrdinalIgnoreCase); - } - - #endregion - - /// <summary> - /// Creates a new instance of GenericPrincipal based on this OAuthPrincipal. - /// </summary> - /// <returns>A new instance of GenericPrincipal with a GenericIdentity, having the same username and roles as this OAuthPrincipal and OAuthIdentity</returns> - public GenericPrincipal CreateGenericPrincipal() - { - return new GenericPrincipal(new GenericIdentity(this.Identity.Name), this.roles.ToArray()); + internal static ClaimsPrincipal CreatePrincipal(string userName, IEnumerable<string> roles = null) { + Requires.NotNullOrEmpty(userName, "userName"); + + var claims = new List<Claim>(); + claims.Add(new Claim(ClaimsIdentity.DefaultNameClaimType, userName)); + if (roles != null) { + claims.AddRange(roles.Select(scope => new Claim(ClaimsIdentity.DefaultRoleClaimType, scope))); + } + + var claimsIdentity = new ClaimsIdentity(claims, "OAuth 2 Bearer"); + var principal = new ClaimsPrincipal(claimsIdentity); + return principal; } } } diff --git a/src/DotNetOpenAuth.OAuth.Common/OAuth/DefaultOAuthHostFactories.cs b/src/DotNetOpenAuth.OAuth.Common/OAuth/DefaultOAuthHostFactories.cs new file mode 100644 index 0000000..33d06b2 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Common/OAuth/DefaultOAuthHostFactories.cs @@ -0,0 +1,50 @@ +//----------------------------------------------------------------------- +// <copyright file="DefaultOAuthHostFactories.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Cache; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + + /// <summary> + /// Creates default instances of required dependencies. + /// </summary> + public class DefaultOAuthHostFactories : IHostFactories { + /// <summary> + /// Initializes a new instance of a concrete derivation of <see cref="HttpMessageHandler" /> + /// to be used for outbound HTTP traffic. + /// </summary> + /// <returns>An instance of <see cref="HttpMessageHandler"/>.</returns> + /// <remarks> + /// An instance of <see cref="WebRequestHandler" /> is recommended where available; + /// otherwise an instance of <see cref="HttpClientHandler" /> is recommended. + /// </remarks> + public virtual HttpMessageHandler CreateHttpMessageHandler() { + var handler = new HttpClientHandler(); + return handler; + } + + /// <summary> + /// Initializes a new instance of the <see cref="HttpClient" /> class + /// to be used for outbound HTTP traffic. + /// </summary> + /// <param name="handler">The handler to pass to the <see cref="HttpClient" /> constructor. + /// May be null to use the default that would be provided by <see cref="CreateHttpMessageHandler" />.</param> + /// <returns> + /// An instance of <see cref="HttpClient" />. + /// </returns> + public HttpClient CreateHttpClient(HttpMessageHandler handler) { + handler = handler ?? this.CreateHttpMessageHandler(); + var client = new HttpClient(handler); + client.DefaultRequestHeaders.UserAgent.Add(Util.LibraryVersionHeader); + return client; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Common/Properties/AssemblyInfo.cs b/src/DotNetOpenAuth.OAuth.Common/Properties/AssemblyInfo.cs index a3afcd7..ee7b802 100644 --- a/src/DotNetOpenAuth.OAuth.Common/Properties/AssemblyInfo.cs +++ b/src/DotNetOpenAuth.OAuth.Common/Properties/AssemblyInfo.cs @@ -35,9 +35,13 @@ using System.Web.UI; // keep this assembly from being useful to shared host (medium trust) web sites. [assembly: AllowPartiallyTrustedCallers] +[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] +[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] [assembly: InternalsVisibleTo("DotNetOpenAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100AD093C3765257C89A7010E853F2C7C741FF92FA8ACE06D7B8254702CAD5CF99104447F63AB05F8BB6F51CE0D81C8C93D2FCE8C20AAFF7042E721CBA16EAAE98778611DED11C0ABC8900DC5667F99B50A9DADEC24DBD8F2C91E3E8AD300EF64F1B4B9536CEB16FB440AF939F57624A9B486F867807C649AE4830EAB88C6C03998")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] #else +[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth2.ResourceServer")] +[assembly: InternalsVisibleTo("DotNetOpenAuth.OAuth.ServiceProvider")] [assembly: InternalsVisibleTo("DotNetOpenAuth.Test")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] #endif diff --git a/src/DotNetOpenAuth.OAuth.Common/packages.config b/src/DotNetOpenAuth.OAuth.Common/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth.Common/packages.config +++ b/src/DotNetOpenAuth.OAuth.Common/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj b/src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj index de2402f..173bb3e 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj +++ b/src/DotNetOpenAuth.OAuth.Consumer/DotNetOpenAuth.OAuth.Consumer.csproj @@ -19,13 +19,17 @@ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> </PropertyGroup> <ItemGroup> - <Compile Include="OAuth\ChannelElements\IConsumerTokenManager.cs" /> - <Compile Include="OAuth\ChannelElements\OAuthConsumerChannel.cs" /> - <Compile Include="OAuth\ChannelElements\OAuthConsumerMessageFactory.cs" /> - <Compile Include="OAuth\ChannelElements\RsaSha1ConsumerSigningBindingElement.cs" /> - <Compile Include="OAuth\ConsumerBase.cs" /> - <Compile Include="OAuth\DesktopConsumer.cs" /> - <Compile Include="OAuth\WebConsumer.cs" /> + <Compile Include="OAuth\AccessToken.cs" /> + <Compile Include="OAuth\AccessTokenResponse.cs" /> + <Compile Include="OAuth\ITemporaryCredentialStorage.cs" /> + <Compile Include="OAuth\Consumer.cs" /> + <Compile Include="OAuth\CookieTemporaryCredentialStorage.cs" /> + <Compile Include="OAuth\MemoryTemporaryCredentialStorage.cs" /> + <Compile Include="OAuth\OAuth1HmacSha1HttpMessageHandler.cs" /> + <Compile Include="OAuth\OAuth1HttpMessageHandlerBase.cs" /> + <Compile Include="OAuth\OAuth1PlainTextMessageHandler.cs" /> + <Compile Include="OAuth\OAuth1RsaSha1HttpMessageHandler.cs" /> + <Compile Include="OAuth\ServiceProviderDescription.cs" /> <Compile Include="Properties\AssemblyInfo.cs"> <SubType> </SubType> @@ -36,15 +40,21 @@ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project> <Name>DotNetOpenAuth.Core</Name> </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OAuth.Common\DotNetOpenAuth.OAuth.Common.csproj"> + <Project>{115217c5-22cd-415c-a292-0dd0238cdd89}</Project> + <Name>DotNetOpenAuth.OAuth.Common</Name> + </ProjectReference> <ProjectReference Include="..\DotNetOpenAuth.OAuth\DotNetOpenAuth.OAuth.csproj"> <Project>{A288FCC8-6FCF-46DA-A45E-5F9281556361}</Project> <Name>DotNetOpenAuth.OAuth</Name> </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/AccessToken.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/AccessToken.cs new file mode 100644 index 0000000..20e3ec4 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/AccessToken.cs @@ -0,0 +1,39 @@ +//----------------------------------------------------------------------- +// <copyright file="AccessToken.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + /// <summary> + /// An OAuth 1.0 access token and secret. + /// </summary> + public struct AccessToken { + /// <summary> + /// Initializes a new instance of the <see cref="AccessToken"/> struct. + /// </summary> + /// <param name="token">The token.</param> + /// <param name="secret">The secret.</param> + public AccessToken(string token, string secret) + : this() { + this.Token = token; + this.Secret = secret; + } + + /// <summary> + /// Gets or sets the token. + /// </summary> + /// <value> + /// The token. + /// </value> + public string Token { get; set; } + + /// <summary> + /// Gets or sets the token secret. + /// </summary> + /// <value> + /// The secret. + /// </value> + public string Secret { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/AccessTokenResponse.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/AccessTokenResponse.cs new file mode 100644 index 0000000..dd35400 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/AccessTokenResponse.cs @@ -0,0 +1,19 @@ +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + public class AccessTokenResponse { + public AccessTokenResponse(string accessToken, string tokenSecret, NameValueCollection extraData) { + this.AccessToken = new AccessToken(accessToken, tokenSecret); + this.ExtraData = extraData; + } + + public AccessToken AccessToken { get; set; } + + public NameValueCollection ExtraData { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/IConsumerTokenManager.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/IConsumerTokenManager.cs deleted file mode 100644 index 74ec3be..0000000 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/IConsumerTokenManager.cs +++ /dev/null @@ -1,25 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="IConsumerTokenManager.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth.ChannelElements { - /// <summary> - /// A token manager for use by a web site in its role as a consumer of - /// an individual ServiceProvider. - /// </summary> - public interface IConsumerTokenManager : ITokenManager { - /// <summary> - /// Gets the consumer key. - /// </summary> - /// <value>The consumer key.</value> - string ConsumerKey { get; } - - /// <summary> - /// Gets the consumer secret. - /// </summary> - /// <value>The consumer secret.</value> - string ConsumerSecret { get; } - } -} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs deleted file mode 100644 index 89ce187..0000000 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerChannel.cs +++ /dev/null @@ -1,65 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OAuthConsumerChannel.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth.ChannelElements { - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using System.Linq; - using System.Text; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Bindings; - using Validation; - - /// <summary> - /// The messaging channel for OAuth 1.0(a) Consumers. - /// </summary> - internal class OAuthConsumerChannel : OAuthChannel { - /// <summary> - /// Initializes a new instance of the <see cref="OAuthConsumerChannel"/> class. - /// </summary> - /// <param name="signingBindingElement">The binding element to use for signing.</param> - /// <param name="store">The web application store to use for nonces.</param> - /// <param name="tokenManager">The token manager instance to use.</param> - /// <param name="securitySettings">The security settings.</param> - /// <param name="messageFactory">The message factory.</param> - [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")] - internal OAuthConsumerChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, IConsumerTokenManager tokenManager, ConsumerSecuritySettings securitySettings, IMessageFactory messageFactory = null) - : base( - signingBindingElement, - tokenManager, - securitySettings, - messageFactory ?? new OAuthConsumerMessageFactory(), - InitializeBindingElements(signingBindingElement, store)) { - Requires.NotNull(tokenManager, "tokenManager"); - Requires.NotNull(securitySettings, "securitySettings"); - Requires.NotNull(signingBindingElement, "signingBindingElement"); - } - - /// <summary> - /// Gets the consumer secret for a given consumer key. - /// </summary> - /// <param name="consumerKey">The consumer key.</param> - /// <returns>The consumer secret.</returns> - protected override string GetConsumerSecret(string consumerKey) { - var consumerTokenManager = (IConsumerTokenManager)this.TokenManager; - ErrorUtilities.VerifyInternal(consumerKey == consumerTokenManager.ConsumerKey, "The token manager consumer key and the consumer key set earlier do not match!"); - return consumerTokenManager.ConsumerSecret; - } - - /// <summary> - /// Initializes the binding elements for the OAuth channel. - /// </summary> - /// <param name="signingBindingElement">The signing binding element.</param> - /// <param name="store">The nonce store.</param> - /// <returns> - /// An array of binding elements used to initialize the channel. - /// </returns> - private static new IChannelBindingElement[] InitializeBindingElements(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store) { - return OAuthChannel.InitializeBindingElements(signingBindingElement, store).ToArray(); - } - } -} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs deleted file mode 100644 index e79749f..0000000 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/OAuthConsumerMessageFactory.cs +++ /dev/null @@ -1,108 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OAuthConsumerMessageFactory.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth.ChannelElements { - using System; - using System.Collections.Generic; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth.Messages; - - /// <summary> - /// An OAuth-protocol specific implementation of the <see cref="IMessageFactory"/> - /// interface. - /// </summary> - public class OAuthConsumerMessageFactory : IMessageFactory { - /// <summary> - /// Initializes a new instance of the <see cref="OAuthConsumerMessageFactory"/> class. - /// </summary> - protected internal OAuthConsumerMessageFactory() { - } - - #region IMessageFactory Members - - /// <summary> - /// Analyzes an incoming request message payload to discover what kind of - /// message is embedded in it and returns the type, or null if no match is found. - /// </summary> - /// <param name="recipient">The intended or actual recipient of the request message.</param> - /// <param name="fields">The name/value pairs that make up the message payload.</param> - /// <returns> - /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can - /// deserialize to. Null if the request isn't recognized as a valid protocol message. - /// </returns> - /// <remarks> - /// The request messages are: - /// UserAuthorizationResponse - /// </remarks> - public virtual IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) { - MessageBase message = null; - - if (fields.ContainsKey("oauth_token")) { - Protocol protocol = fields.ContainsKey("oauth_verifier") ? Protocol.V10a : Protocol.V10; - message = new UserAuthorizationResponse(recipient.Location, protocol.Version); - } - - if (message != null) { - message.SetAsIncoming(); - } - - return message; - } - - /// <summary> - /// Analyzes an incoming request message payload to discover what kind of - /// message is embedded in it and returns the type, or null if no match is found. - /// </summary> - /// <param name="request"> - /// The message that was sent as a request that resulted in the response. - /// Null on a Consumer site that is receiving an indirect message from the Service Provider. - /// </param> - /// <param name="fields">The name/value pairs that make up the message payload.</param> - /// <returns> - /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can - /// deserialize to. Null if the request isn't recognized as a valid protocol message. - /// </returns> - /// <remarks> - /// The response messages are: - /// UnauthorizedTokenResponse - /// AuthorizedTokenResponse - /// </remarks> - public virtual IDirectResponseProtocolMessage GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) { - MessageBase message = null; - - // All response messages have the oauth_token field. - if (!fields.ContainsKey("oauth_token")) { - return null; - } - - // All direct message responses should have the oauth_token_secret field. - if (!fields.ContainsKey("oauth_token_secret")) { - Logger.OAuth.Error("An OAuth message was expected to contain an oauth_token_secret but didn't."); - return null; - } - - var unauthorizedTokenRequest = request as UnauthorizedTokenRequest; - var authorizedTokenRequest = request as AuthorizedTokenRequest; - if (unauthorizedTokenRequest != null) { - Protocol protocol = fields.ContainsKey("oauth_callback_confirmed") ? Protocol.V10a : Protocol.V10; - message = new UnauthorizedTokenResponse(unauthorizedTokenRequest, protocol.Version); - } else if (authorizedTokenRequest != null) { - message = new AuthorizedTokenResponse(authorizedTokenRequest); - } else { - Logger.OAuth.ErrorFormat("Unexpected response message given the request type {0}", request.GetType().Name); - throw new ProtocolException(OAuthStrings.InvalidIncomingMessage); - } - - if (message != null) { - message.SetAsIncoming(); - } - - return message; - } - - #endregion - } -} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs deleted file mode 100644 index d492e33..0000000 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ChannelElements/RsaSha1ConsumerSigningBindingElement.cs +++ /dev/null @@ -1,76 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="RsaSha1ConsumerSigningBindingElement.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth.ChannelElements { - using System; - using System.Diagnostics.CodeAnalysis; - using System.Security.Cryptography; - using System.Security.Cryptography.X509Certificates; - using System.Text; - using DotNetOpenAuth.Messaging; - using Validation; - - /// <summary> - /// A binding element that signs outgoing messages and verifies the signature on incoming messages. - /// </summary> - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sha", Justification = "Acronym")] - public class RsaSha1ConsumerSigningBindingElement : RsaSha1SigningBindingElement { - /// <summary> - /// Initializes a new instance of the <see cref="RsaSha1ConsumerSigningBindingElement"/> class. - /// </summary> - /// <param name="signingCertificate">The certificate used to sign outgoing messages.</param> - public RsaSha1ConsumerSigningBindingElement(X509Certificate2 signingCertificate) { - Requires.NotNull(signingCertificate, "signingCertificate"); - - this.SigningCertificate = signingCertificate; - } - - /// <summary> - /// Gets or sets the certificate used to sign outgoing messages. Used only by Consumers. - /// </summary> - public X509Certificate2 SigningCertificate { get; set; } - - /// <summary> - /// Determines whether the signature on some message is valid. - /// </summary> - /// <param name="message">The message to check the signature on.</param> - /// <returns> - /// <c>true</c> if the signature on the message is valid; otherwise, <c>false</c>. - /// </returns> - protected override bool IsSignatureValid(ITamperResistantOAuthMessage message) { - throw new NotImplementedException(); - } - - /// <summary> - /// Calculates a signature for a given message. - /// </summary> - /// <param name="message">The message to sign.</param> - /// <returns>The signature for the message.</returns> - /// <remarks> - /// This method signs the message per OAuth 1.0 section 9.3. - /// </remarks> - protected override string GetSignature(ITamperResistantOAuthMessage message) { - ErrorUtilities.VerifyOperation(this.SigningCertificate != null, OAuthStrings.X509CertificateNotProvidedForSigning); - - string signatureBaseString = ConstructSignatureBaseString(message, this.Channel.MessageDescriptions.GetAccessor(message)); - byte[] data = Encoding.ASCII.GetBytes(signatureBaseString); - var provider = (RSACryptoServiceProvider)this.SigningCertificate.PrivateKey; - byte[] binarySignature = provider.SignData(data, "SHA1"); - string base64Signature = Convert.ToBase64String(binarySignature); - return base64Signature; - } - - /// <summary> - /// Creates a new object that is a copy of the current instance. - /// </summary> - /// <returns> - /// A new object that is a copy of this instance. - /// </returns> - protected override ITamperProtectionChannelBindingElement Clone() { - return new RsaSha1ConsumerSigningBindingElement(this.SigningCertificate); - } - } -} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/Consumer.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/Consumer.cs new file mode 100644 index 0000000..93fbaac --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/Consumer.cs @@ -0,0 +1,339 @@ +//----------------------------------------------------------------------- +// <copyright file="Consumer.cs" company="Outercurve Foundation"> +// Copyright (c) Outercurve Foundation. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Security.Cryptography.X509Certificates; + using System.Threading; + using System.Threading.Tasks; + using System.Web; + using DotNetOpenAuth.Configuration; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + using Validation; + + /// <summary> + /// Base class for <see cref="WebConsumer"/> and <see cref="DesktopConsumer"/> types. + /// </summary> + public class Consumer { + /// <summary> + /// The host factories. + /// </summary> + private IHostFactories hostFactories; + + /// <summary> + /// Initializes a new instance of the <see cref="Consumer"/> class. + /// </summary> + public Consumer() { + this.HostFactories = new DefaultOAuthHostFactories(); + } + + /// <summary> + /// Initializes a new instance of the <see cref="Consumer" /> class. + /// </summary> + /// <param name="consumerKey">The consumer key.</param> + /// <param name="consumerSecret">The consumer secret.</param> + /// <param name="serviceProvider">The service provider.</param> + /// <param name="temporaryCredentialStorage">The temporary credential storage.</param> + /// <param name="hostFactories">The host factories.</param> + public Consumer( + string consumerKey, + string consumerSecret, + ServiceProviderDescription serviceProvider, + ITemporaryCredentialStorage temporaryCredentialStorage, + IHostFactories hostFactories = null) { + this.ConsumerKey = consumerKey; + this.ConsumerSecret = consumerSecret; + this.ServiceProvider = serviceProvider; + this.TemporaryCredentialStorage = temporaryCredentialStorage; + this.HostFactories = hostFactories ?? new DefaultOAuthHostFactories(); + } + + /// <summary> + /// Gets or sets the object with factories for host-customizable services. + /// </summary> + public IHostFactories HostFactories { + get { + return this.hostFactories; + } + + set { + Requires.NotNull(value, "value"); + this.hostFactories = value; + } + } + + /// <summary> + /// Gets the Consumer Key used to communicate with the Service Provider. + /// </summary> + public string ConsumerKey { get; set; } + + /// <summary> + /// Gets or sets the consumer secret. + /// </summary> + /// <value> + /// The consumer secret. + /// </value> + public string ConsumerSecret { get; set; } + + /// <summary> + /// Gets or sets the consumer certificate. + /// </summary> + /// <value> + /// The consumer certificate. + /// </value> + /// <remarks> + /// If set, this causes all outgoing messages to be signed with the certificate instead of the consumer secret. + /// </remarks> + public X509Certificate2 ConsumerCertificate { get; set; } + + /// <summary> + /// Gets or sets the Service Provider that will be accessed. + /// </summary> + public ServiceProviderDescription ServiceProvider { get; set; } + + /// <summary> + /// Gets the persistence store for tokens and secrets. + /// </summary> + public ITemporaryCredentialStorage TemporaryCredentialStorage { get; set; } + + /// <summary> + /// Obtains an access token for a new account at the Service Provider via 2-legged OAuth. + /// </summary> + /// <param name="requestParameters">Any applicable parameters to include in the query string of the token request.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The access token.</returns> + public async Task<AccessTokenResponse> RequestNewClientAccountAsync(IEnumerable<KeyValuePair<string, string>> requestParameters = null, CancellationToken cancellationToken = default(CancellationToken)) { + Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey"); + Verify.Operation(this.ServiceProvider != null, Strings.RequiredPropertyNotYetPreset, "ServiceProvider"); + + using (var handler = this.CreateMessageHandler()) { + using (var client = this.CreateHttpClient(handler)) { + string identifier, secret; + + var requestUri = new UriBuilder(this.ServiceProvider.TemporaryCredentialsRequestEndpoint); + requestUri.AppendQueryArgument(Protocol.CallbackParameter, "oob"); + requestUri.AppendQueryArgs(requestParameters); + var request = new HttpRequestMessage(this.ServiceProvider.TemporaryCredentialsRequestEndpointMethod, requestUri.Uri); + using (var response = await client.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); + cancellationToken.ThrowIfCancellationRequested(); + + // Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec. + string content = await response.Content.ReadAsStringAsync(); + var responseData = HttpUtility.ParseQueryString(content); + identifier = responseData[Protocol.TokenParameter]; + secret = responseData[Protocol.TokenSecretParameter]; + ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(identifier), MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenParameter); + ErrorUtilities.VerifyProtocol(secret != null, MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenSecretParameter); + } + + // Immediately exchange the temporary credential for an access token. + handler.AccessToken = identifier; + handler.AccessTokenSecret = secret; + request = new HttpRequestMessage(this.ServiceProvider.TokenRequestEndpointMethod, this.ServiceProvider.TokenRequestEndpoint); + using (var response = await client.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); + + // Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec. + string content = await response.Content.ReadAsStringAsync(); + var responseData = HttpUtility.ParseQueryString(content); + string accessToken = responseData[Protocol.TokenParameter]; + string tokenSecret = responseData[Protocol.TokenSecretParameter]; + ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenParameter); + ErrorUtilities.VerifyProtocol(tokenSecret != null, MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenSecretParameter); + + responseData.Remove(Protocol.TokenParameter); + responseData.Remove(Protocol.TokenSecretParameter); + return new AccessTokenResponse(accessToken, tokenSecret, responseData); + } + } + } + } + + /// <summary> + /// Prepares an OAuth message that begins an authorization request that will + /// redirect the user to the Service Provider to provide that authorization. + /// </summary> + /// <param name="callback">The absolute URI that the Service Provider should redirect the + /// User Agent to upon successful authorization, or <c>null</c> to signify an out of band return.</param> + /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The URL to direct the user agent to for user authorization. + /// </returns> + public async Task<Uri> RequestUserAuthorizationAsync(Uri callback = null, IEnumerable<KeyValuePair<string, string>> requestParameters = null, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(callback, "callback"); + Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey"); + Verify.Operation(this.TemporaryCredentialStorage != null, Strings.RequiredPropertyNotYetPreset, "TemporaryCredentialStorage"); + Verify.Operation(this.ServiceProvider != null, Strings.RequiredPropertyNotYetPreset, "ServiceProvider"); + + // Obtain temporary credentials before the redirect. + using (var client = this.CreateHttpClient(new AccessToken())) { + var requestUri = new UriBuilder(this.ServiceProvider.TemporaryCredentialsRequestEndpoint); + requestUri.AppendQueryArgument(Protocol.CallbackParameter, callback != null ? callback.AbsoluteUri : "oob"); + requestUri.AppendQueryArgs(requestParameters); + var request = new HttpRequestMessage(this.ServiceProvider.TemporaryCredentialsRequestEndpointMethod, requestUri.Uri); + using (var response = await client.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); + cancellationToken.ThrowIfCancellationRequested(); + + // Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec. + string content = await response.Content.ReadAsStringAsync(); + var responseData = HttpUtility.ParseQueryString(content); + ErrorUtilities.VerifyProtocol(string.Equals(responseData[Protocol.CallbackConfirmedParameter], "true", StringComparison.Ordinal), MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.CallbackConfirmedParameter); + string identifier = responseData[Protocol.TokenParameter]; + string secret = responseData[Protocol.TokenSecretParameter]; + ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(identifier), MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenParameter); + ErrorUtilities.VerifyProtocol(secret != null, MessagingStrings.RequiredParametersMissing, typeof(UnauthorizedTokenResponse).Name, Protocol.TokenSecretParameter); + + // Save the temporary credential we received so that after user authorization + // we can use it to obtain the access token. + cancellationToken.ThrowIfCancellationRequested(); + this.TemporaryCredentialStorage.SaveTemporaryCredential(identifier, secret); + + // Construct the user authorization URL so our caller can direct a browser to it. + var authorizationEndpoint = new UriBuilder(this.ServiceProvider.ResourceOwnerAuthorizationEndpoint); + authorizationEndpoint.AppendQueryArgument(Protocol.TokenParameter, identifier); + return authorizationEndpoint.Uri; + } + } + } + + /// <summary> + /// Obtains an access token after a successful user authorization. + /// </summary> + /// <param name="authorizationCompleteUri">The URI used to redirect back to the consumer that contains a message from the service provider.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The access token assigned by the Service Provider, or <c>null</c> if no response was detected in the specified URL. + /// </returns> + public async Task<AccessTokenResponse> ProcessUserAuthorizationAsync(Uri authorizationCompleteUri, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(authorizationCompleteUri, "authorizationCompleteUri"); + Verify.Operation(this.TemporaryCredentialStorage != null, Strings.RequiredPropertyNotYetPreset, "TemporaryCredentialStorage"); + + // Parse the response and verify that it meets spec requirements. + var queryString = HttpUtility.ParseQueryString(authorizationCompleteUri.Query); + string identifier = queryString[Protocol.TokenParameter]; + string verifier = queryString[Protocol.VerifierParameter]; + + if (identifier == null) { + // We assume there is no response message here at all, and return null to indicate that. + return null; + } + + ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(identifier), MessagingStrings.RequiredNonEmptyParameterWasEmpty, typeof(UserAuthorizationResponse).Name, Protocol.TokenParameter); + ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(verifier), MessagingStrings.RequiredNonEmptyParameterWasEmpty, typeof(UserAuthorizationResponse).Name, Protocol.VerifierParameter); + + var temporaryCredential = this.TemporaryCredentialStorage.RetrieveTemporaryCredential(); + Verify.Operation(string.Equals(temporaryCredential.Key, identifier, StringComparison.Ordinal), "Temporary credential identifiers do not match."); + + return await this.ProcessUserAuthorizationAsync(verifier, cancellationToken); + } + + /// <summary> + /// Obtains an access token after a successful user authorization. + /// </summary> + /// <param name="verifier">The verifier.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The access token assigned by the Service Provider. + /// </returns> + public async Task<AccessTokenResponse> ProcessUserAuthorizationAsync(string verifier, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(verifier, "verifier"); + Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey"); + Verify.Operation(this.TemporaryCredentialStorage != null, Strings.RequiredPropertyNotYetPreset, "TemporaryCredentialStorage"); + Verify.Operation(this.ServiceProvider != null, Strings.RequiredPropertyNotYetPreset, "ServiceProvider"); + + var temporaryCredential = this.TemporaryCredentialStorage.RetrieveTemporaryCredential(); + + using (var client = this.CreateHttpClient(new AccessToken(temporaryCredential.Key, temporaryCredential.Value))) { + var requestUri = new UriBuilder(this.ServiceProvider.TokenRequestEndpoint); + requestUri.AppendQueryArgument(Protocol.VerifierParameter, verifier); + var request = new HttpRequestMessage(this.ServiceProvider.TokenRequestEndpointMethod, requestUri.Uri); + using (var response = await client.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); + + // Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec. + string content = await response.Content.ReadAsStringAsync(); + var responseData = HttpUtility.ParseQueryString(content); + string accessToken = responseData[Protocol.TokenParameter]; + string tokenSecret = responseData[Protocol.TokenSecretParameter]; + ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenParameter); + ErrorUtilities.VerifyProtocol(tokenSecret != null, MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenSecretParameter); + + responseData.Remove(Protocol.TokenParameter); + responseData.Remove(Protocol.TokenSecretParameter); + return new AccessTokenResponse(accessToken, tokenSecret, responseData); + } + } + } + + /// <summary> + /// Creates a message handler that signs outbound requests with a previously obtained authorization. + /// </summary> + /// <param name="accessToken">The access token to authorize outbound HTTP requests with.</param> + /// <param name="innerHandler">The inner handler that actually sends the HTTP message on the network.</param> + /// <returns> + /// A message handler. + /// </returns> + /// <remarks> + /// Overrides of this method may allow various derived types of handlers to be returned, + /// enabling consumers that use RSA or other signing methods. + /// </remarks> + public virtual OAuth1HttpMessageHandlerBase CreateMessageHandler(AccessToken accessToken = default(AccessToken), HttpMessageHandler innerHandler = null) { + Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey"); + + innerHandler = innerHandler ?? this.HostFactories.CreateHttpMessageHandler(); + OAuth1HttpMessageHandlerBase handler; + if (this.ConsumerCertificate != null) { + handler = new OAuth1RsaSha1HttpMessageHandler(innerHandler) { + SigningCertificate = this.ConsumerCertificate, + }; + } else { + handler = new OAuth1HmacSha1HttpMessageHandler(innerHandler); + } + + handler.ConsumerKey = this.ConsumerKey; + handler.ConsumerSecret = this.ConsumerSecret; + handler.AccessToken = accessToken.Token; + handler.AccessTokenSecret = accessToken.Secret; + + return handler; + } + + /// <summary> + /// Creates the HTTP client. + /// </summary> + /// <param name="accessToken">The access token to authorize outbound HTTP requests with.</param> + /// <param name="innerHandler">The inner handler that actually sends the HTTP message on the network.</param> + /// <returns>The HttpClient to use.</returns> + public HttpClient CreateHttpClient(AccessToken accessToken, HttpMessageHandler innerHandler = null) { + var handler = this.CreateMessageHandler(accessToken, innerHandler); + var client = this.HostFactories.CreateHttpClient(handler); + return client; + } + + /// <summary> + /// Creates the HTTP client. + /// </summary> + /// <param name="innerHandler">The inner handler that actually sends the HTTP message on the network.</param> + /// <returns>The HttpClient to use.</returns> + public HttpClient CreateHttpClient(OAuth1HttpMessageHandlerBase innerHandler) { + Requires.NotNull(innerHandler, "innerHandler"); + + var client = this.HostFactories.CreateHttpClient(innerHandler); + return client; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs deleted file mode 100644 index 0d2da87..0000000 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs +++ /dev/null @@ -1,302 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="ConsumerBase.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth { - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using System.Linq; - using System.Net; - using DotNetOpenAuth.Configuration; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Bindings; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - using Validation; - - /// <summary> - /// Base class for <see cref="WebConsumer"/> and <see cref="DesktopConsumer"/> types. - /// </summary> - public class ConsumerBase : IDisposable { - /// <summary> - /// Initializes a new instance of the <see cref="ConsumerBase"/> class. - /// </summary> - /// <param name="serviceDescription">The endpoints and behavior of the Service Provider.</param> - /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> - protected ConsumerBase(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) { - Requires.NotNull(serviceDescription, "serviceDescription"); - Requires.NotNull(tokenManager, "tokenManager"); - - ITamperProtectionChannelBindingElement signingElement = serviceDescription.CreateTamperProtectionElement(); - INonceStore store = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge); - this.SecuritySettings = OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings(); - this.OAuthChannel = new OAuthConsumerChannel(signingElement, store, tokenManager, this.SecuritySettings); - this.ServiceProvider = serviceDescription; - - OAuthReporting.RecordFeatureAndDependencyUse(this, serviceDescription, tokenManager, null); - } - - /// <summary> - /// Gets the Consumer Key used to communicate with the Service Provider. - /// </summary> - public string ConsumerKey { - get { return this.TokenManager.ConsumerKey; } - } - - /// <summary> - /// Gets the Service Provider that will be accessed. - /// </summary> - public ServiceProviderDescription ServiceProvider { get; private set; } - - /// <summary> - /// Gets the persistence store for tokens and secrets. - /// </summary> - public IConsumerTokenManager TokenManager { - get { return (IConsumerTokenManager)this.OAuthChannel.TokenManager; } - } - - /// <summary> - /// Gets the channel to use for sending/receiving messages. - /// </summary> - public Channel Channel { - get { return this.OAuthChannel; } - } - - /// <summary> - /// Gets the security settings for this consumer. - /// </summary> - internal ConsumerSecuritySettings SecuritySettings { get; private set; } - - /// <summary> - /// Gets or sets the channel to use for sending/receiving messages. - /// </summary> - internal OAuthChannel OAuthChannel { get; set; } - - /// <summary> - /// Obtains an access token for a new account at the Service Provider via 2-legged OAuth. - /// </summary> - /// <param name="requestParameters">Any applicable parameters to include in the query string of the token request.</param> - /// <returns>The access token.</returns> - /// <remarks> - /// The token secret is stored in the <see cref="TokenManager"/>. - /// </remarks> - public string RequestNewClientAccount(IDictionary<string, string> requestParameters = null) { - // Obtain an unauthorized request token. Force use of OAuth 1.0 (not 1.0a) so that - // we are not expected to provide an oauth_verifier which doesn't apply in 2-legged OAuth. - var token = new UnauthorizedTokenRequest(this.ServiceProvider.RequestTokenEndpoint, Protocol.V10.Version) { - ConsumerKey = this.ConsumerKey, - }; - var tokenAccessor = this.Channel.MessageDescriptions.GetAccessor(token); - tokenAccessor.AddExtraParameters(requestParameters); - var requestTokenResponse = this.Channel.Request<UnauthorizedTokenResponse>(token); - this.TokenManager.StoreNewRequestToken(token, requestTokenResponse); - - var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint, Protocol.V10.Version) { - RequestToken = requestTokenResponse.RequestToken, - ConsumerKey = this.ConsumerKey, - }; - var grantAccess = this.Channel.Request<AuthorizedTokenResponse>(requestAccess); - this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(this.ConsumerKey, requestTokenResponse.RequestToken, grantAccess.AccessToken, grantAccess.TokenSecret); - return grantAccess.AccessToken; - } - - /// <summary> - /// Creates a web request prepared with OAuth authorization - /// that may be further tailored by adding parameters by the caller. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <returns>The initialized WebRequest object.</returns> - public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken) { - Requires.NotNull(endpoint, "endpoint"); - Requires.NotNullOrEmpty(accessToken, "accessToken"); - - return this.PrepareAuthorizedRequest(endpoint, accessToken, EmptyDictionary<string, string>.Instance); - } - - /// <summary> - /// Creates a web request prepared with OAuth authorization - /// that may be further tailored by adding parameters by the caller. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <param name="extraData">Extra parameters to include in the message. Must not be null, but may be empty.</param> - /// <returns>The initialized WebRequest object.</returns> - public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken, IDictionary<string, string> extraData) { - Requires.NotNull(endpoint, "endpoint"); - Requires.NotNullOrEmpty(accessToken, "accessToken"); - Requires.NotNull(extraData, "extraData"); - - IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); - foreach (var pair in extraData) { - message.ExtraData.Add(pair); - } - - HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message); - return wr; - } - - /// <summary> - /// Prepares an authorized request that carries an HTTP multi-part POST, allowing for binary data. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <param name="binaryData">Extra parameters to include in the message. Must not be null, but may be empty.</param> - /// <returns>The initialized WebRequest object.</returns> - public HttpWebRequest PrepareAuthorizedRequest(MessageReceivingEndpoint endpoint, string accessToken, IEnumerable<MultipartPostPart> binaryData) { - Requires.NotNull(endpoint, "endpoint"); - Requires.NotNullOrEmpty(accessToken, "accessToken"); - Requires.NotNull(binaryData, "binaryData"); - - AccessProtectedResourceRequest message = this.CreateAuthorizingMessage(endpoint, accessToken); - foreach (MultipartPostPart part in binaryData) { - message.BinaryData.Add(part); - } - - HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message); - return wr; - } - - /// <summary> - /// Prepares an HTTP request that has OAuth authorization already attached to it. - /// </summary> - /// <param name="message">The OAuth authorization message to attach to the HTTP request.</param> - /// <returns> - /// The HttpWebRequest that can be used to send the HTTP request to the remote service provider. - /// </returns> - /// <remarks> - /// If <see cref="IDirectedProtocolMessage.HttpMethods"/> property on the - /// <paramref name="message"/> has the - /// <see cref="HttpDeliveryMethods.AuthorizationHeaderRequest"/> flag set and - /// <see cref="ITamperResistantOAuthMessage.HttpMethod"/> is set to an HTTP method - /// that includes an entity body, the request stream is automatically sent - /// if and only if the <see cref="IMessage.ExtraData"/> dictionary is non-empty. - /// </remarks> - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Type of parameter forces the method to apply only to specific scenario.")] - public HttpWebRequest PrepareAuthorizedRequest(AccessProtectedResourceRequest message) { - Requires.NotNull(message, "message"); - return this.OAuthChannel.InitializeRequest(message); - } - - /// <summary> - /// Creates a web request prepared with OAuth authorization - /// that may be further tailored by adding parameters by the caller. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <returns>The initialized WebRequest object.</returns> - /// <exception cref="WebException">Thrown if the request fails for any reason after it is sent to the Service Provider.</exception> - public IncomingWebResponse PrepareAuthorizedRequestAndSend(MessageReceivingEndpoint endpoint, string accessToken) { - IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); - HttpWebRequest wr = this.OAuthChannel.InitializeRequest(message); - return this.Channel.WebRequestHandler.GetResponse(wr); - } - - #region IDisposable Members - - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - #endregion - - /// <summary> - /// Creates a web request prepared with OAuth authorization - /// that may be further tailored by adding parameters by the caller. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <returns>The initialized WebRequest object.</returns> - protected internal AccessProtectedResourceRequest CreateAuthorizingMessage(MessageReceivingEndpoint endpoint, string accessToken) { - Requires.NotNull(endpoint, "endpoint"); - Requires.NotNullOrEmpty(accessToken, "accessToken"); - - AccessProtectedResourceRequest message = new AccessProtectedResourceRequest(endpoint, this.ServiceProvider.Version) { - AccessToken = accessToken, - ConsumerKey = this.ConsumerKey, - }; - - return message; - } - - /// <summary> - /// Prepares an OAuth message that begins an authorization request that will - /// redirect the user to the Service Provider to provide that authorization. - /// </summary> - /// <param name="callback"> - /// An optional Consumer URL that the Service Provider should redirect the - /// User Agent to upon successful authorization. - /// </param> - /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param> - /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param> - /// <param name="requestToken">The request token that must be exchanged for an access token after the user has provided authorization.</param> - /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> - [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "3#", Justification = "Two results")] - protected internal UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters, out string requestToken) { - // Obtain an unauthorized request token. Assume the OAuth version given in the service description. - var token = new UnauthorizedTokenRequest(this.ServiceProvider.RequestTokenEndpoint, this.ServiceProvider.Version) { - ConsumerKey = this.ConsumerKey, - Callback = callback, - }; - var tokenAccessor = this.Channel.MessageDescriptions.GetAccessor(token); - tokenAccessor.AddExtraParameters(requestParameters); - var requestTokenResponse = this.Channel.Request<UnauthorizedTokenResponse>(token); - this.TokenManager.StoreNewRequestToken(token, requestTokenResponse); - - // Fine-tune our understanding of the SP's supported OAuth version if it's wrong. - if (this.ServiceProvider.Version != requestTokenResponse.Version) { - Logger.OAuth.WarnFormat("Expected OAuth service provider at endpoint {0} to use OAuth {1} but {2} was detected. Adjusting service description to new version.", this.ServiceProvider.RequestTokenEndpoint.Location, this.ServiceProvider.Version, requestTokenResponse.Version); - this.ServiceProvider.ProtocolVersion = Protocol.Lookup(requestTokenResponse.Version).ProtocolVersion; - } - - // Request user authorization. The OAuth version will automatically include - // or drop the callback that we're setting here. - ITokenContainingMessage assignedRequestToken = requestTokenResponse; - var requestAuthorization = new UserAuthorizationRequest(this.ServiceProvider.UserAuthorizationEndpoint, assignedRequestToken.Token, requestTokenResponse.Version) { - Callback = callback, - }; - var requestAuthorizationAccessor = this.Channel.MessageDescriptions.GetAccessor(requestAuthorization); - requestAuthorizationAccessor.AddExtraParameters(redirectParameters); - requestToken = requestAuthorization.RequestToken; - return requestAuthorization; - } - - /// <summary> - /// Exchanges a given request token for access token. - /// </summary> - /// <param name="requestToken">The request token that the user has authorized.</param> - /// <param name="verifier">The verifier code.</param> - /// <returns> - /// The access token assigned by the Service Provider. - /// </returns> - protected AuthorizedTokenResponse ProcessUserAuthorization(string requestToken, string verifier) { - Requires.NotNullOrEmpty(requestToken, "requestToken"); - - var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint, this.ServiceProvider.Version) { - RequestToken = requestToken, - VerificationCode = verifier, - ConsumerKey = this.ConsumerKey, - }; - var grantAccess = this.Channel.Request<AuthorizedTokenResponse>(requestAccess); - this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(this.ConsumerKey, requestToken, grantAccess.AccessToken, grantAccess.TokenSecret); - return grantAccess; - } - - /// <summary> - /// Releases unmanaged and - optionally - managed resources - /// </summary> - /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool disposing) { - if (disposing) { - this.Channel.Dispose(); - } - } - } -} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/CookieTemporaryCredentialStorage.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/CookieTemporaryCredentialStorage.cs new file mode 100644 index 0000000..25941e6 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/CookieTemporaryCredentialStorage.cs @@ -0,0 +1,130 @@ +//----------------------------------------------------------------------- +// <copyright file="CookieTemporaryCredentialStorage.cs" company="Microsoft"> +// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using System.Web; + using System.Web.Security; + using Validation; + + /// <summary> + /// Provides temporary credential storage by persisting them in a protected cookie on the + /// user agent (i.e. browser). + /// </summary> + public class CookieTemporaryCredentialStorage : ITemporaryCredentialStorage { + /// <summary> + /// Key used for token cookie + /// </summary> + protected const string TokenCookieKey = "DNOAOAuth1TempCredential"; + + /// <summary> + /// Primary request context. + /// </summary> + private readonly HttpContextBase httpContext; + + /// <summary> + /// Initializes a new instance of the <see cref="CookieTemporaryCredentialsStorage"/> class + /// using <see cref="HttpContext.Current"/> as the source for the context to read and write cookies to. + /// </summary> + public CookieTemporaryCredentialStorage() + : this(new HttpContextWrapper(HttpContext.Current)) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="CookieTemporaryCredentialsStorage"/> class. + /// </summary> + /// <param name="httpContext">The HTTP context from and to which to access cookies.</param> + public CookieTemporaryCredentialStorage(HttpContextBase httpContext) { + Requires.NotNull(httpContext, "httpContext"); + this.httpContext = httpContext; + } + + #region ITemporaryCredentialsStorage Members + + /// <summary> + /// Saves the temporary credential. + /// </summary> + /// <param name="identifier">The identifier.</param> + /// <param name="secret">The secret.</param> + public void SaveTemporaryCredential(string identifier, string secret) { + var cookie = new HttpCookie(TokenCookieKey) { + HttpOnly = true + }; + + if (FormsAuthentication.RequireSSL) { + cookie.Secure = true; + } + + var encryptedToken = ProtectAndEncodeToken(identifier, secret); + cookie.Values[identifier] = encryptedToken; + + this.httpContext.Response.Cookies.Set(cookie); + } + + /// <summary> + /// Obtains the temporary credential identifier and secret, if available. + /// </summary> + /// <returns> + /// An initialized key value pair if credentials are available; otherwise both key and value are <c>null</c>. + /// </returns> + /// <exception cref="System.NotImplementedException"></exception> + public KeyValuePair<string, string> RetrieveTemporaryCredential() { + HttpCookie cookie = this.httpContext.Request.Cookies[TokenCookieKey]; + if (cookie == null || cookie.Values.Count == 0) { + return new KeyValuePair<string, string>(); + } + + string identifier = cookie.Values.GetKey(0); + string secret = DecodeAndUnprotectToken(identifier, cookie.Values[identifier]); + return new KeyValuePair<string, string>(identifier, secret); + } + + /// <summary> + /// Clears the temporary credentials from storage. + /// </summary> + /// <remarks> + /// DotNetOpenAuth calls this when the credentials are no longer needed. + /// </remarks> + public void ClearTemporaryCredential() { + var cookie = new HttpCookie(TokenCookieKey) { + Value = string.Empty, + Expires = DateTime.UtcNow.AddDays(-5), + }; + this.httpContext.Response.Cookies.Set(cookie); + } + + #endregion + + /// <summary> + /// Protect and url-encode the specified token secret. + /// </summary> + /// <param name="token">The token to be used as a key.</param> + /// <param name="tokenSecret">The token secret to be protected</param> + /// <returns>The encrypted and protected string.</returns> + protected static string ProtectAndEncodeToken(string token, string tokenSecret) { + byte[] cookieBytes = Encoding.UTF8.GetBytes(tokenSecret); + var secretBytes = MachineKeyUtil.Protect(cookieBytes, TokenCookieKey, "Token:" + token); + return HttpServerUtility.UrlTokenEncode(secretBytes); + } + + /// <summary> + /// Url-decode and unprotect the specified encrypted token string. + /// </summary> + /// <param name="token">The token to be used as a key.</param> + /// <param name="encryptedToken">The encrypted token to be decrypted</param> + /// <returns>The original token secret</returns> + protected static string DecodeAndUnprotectToken(string token, string encryptedToken) { + byte[] cookieBytes = HttpServerUtility.UrlTokenDecode(encryptedToken); + byte[] clearBytes = MachineKeyUtil.Unprotect(cookieBytes, TokenCookieKey, "Token:" + token); + return Encoding.UTF8.GetString(clearBytes); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/DesktopConsumer.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/DesktopConsumer.cs deleted file mode 100644 index fe6020e..0000000 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/DesktopConsumer.cs +++ /dev/null @@ -1,73 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="DesktopConsumer.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth { - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - - /// <summary> - /// Used by a desktop application to use OAuth to access the Service Provider on behalf of the User. - /// </summary> - /// <remarks> - /// The methods on this class are thread-safe. Provided the properties are set and not changed - /// afterward, a single instance of this class may be used by an entire desktop application safely. - /// </remarks> - public class DesktopConsumer : ConsumerBase { - /// <summary> - /// Initializes a new instance of the <see cref="DesktopConsumer"/> class. - /// </summary> - /// <param name="serviceDescription">The endpoints and behavior of the Service Provider.</param> - /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> - public DesktopConsumer(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) - : base(serviceDescription, tokenManager) { - } - - /// <summary> - /// Begins an OAuth authorization request. - /// </summary> - /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param> - /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param> - /// <param name="requestToken">The request token that must be exchanged for an access token after the user has provided authorization.</param> - /// <returns>The URL to open a browser window to allow the user to provide authorization.</returns> - [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Two results")] - public Uri RequestUserAuthorization(IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters, out string requestToken) { - var message = this.PrepareRequestUserAuthorization(null, requestParameters, redirectParameters, out requestToken); - OutgoingWebResponse response = this.Channel.PrepareResponse(message); - return response.GetDirectUriRequest(this.Channel); - } - - /// <summary> - /// Exchanges a given request token for access token. - /// </summary> - /// <param name="requestToken">The request token that the user has authorized.</param> - /// <returns>The access token assigned by the Service Provider.</returns> - [Obsolete("Use the ProcessUserAuthorization method that takes a verifier parameter instead.")] - public AuthorizedTokenResponse ProcessUserAuthorization(string requestToken) { - return this.ProcessUserAuthorization(requestToken, null); - } - - /// <summary> - /// Exchanges a given request token for access token. - /// </summary> - /// <param name="requestToken">The request token that the user has authorized.</param> - /// <param name="verifier">The verifier code typed in by the user. Must not be <c>Null</c> for OAuth 1.0a service providers and later.</param> - /// <returns> - /// The access token assigned by the Service Provider. - /// </returns> - public new AuthorizedTokenResponse ProcessUserAuthorization(string requestToken, string verifier) { - if (this.ServiceProvider.Version >= Protocol.V10a.Version) { - ErrorUtilities.VerifyNonZeroLength(verifier, "verifier"); - } - - return base.ProcessUserAuthorization(requestToken, verifier); - } - } -} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ITemporaryCredentialStorage.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ITemporaryCredentialStorage.cs new file mode 100644 index 0000000..428749a --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ITemporaryCredentialStorage.cs @@ -0,0 +1,40 @@ +//----------------------------------------------------------------------- +// <copyright file="ITemporaryCredentialStorage.cs" company="Outercurve Foundation"> +// Copyright (c) Outercurve Foundation. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System.Collections.Generic; + + /// <summary> + /// A token manager for use by an OAuth Consumer to store a temporary credential + /// (previously known as "unauthorized request token and secret"). + /// </summary> + /// <remarks> + /// The credentials stored here are obtained as described in: + /// http://tools.ietf.org/html/rfc5849#section-2.1 + /// </remarks> + public interface ITemporaryCredentialStorage { + /// <summary> + /// Saves the specified temporary credential for later retrieval. + /// </summary> + /// <param name="identifier">The identifier.</param> + /// <param name="secret">The secret.</param> + void SaveTemporaryCredential(string identifier, string secret); + + /// <summary> + /// Obtains a temporary credential secret, if available. + /// </summary> + /// <returns>The temporary credential identifier secret if available; otherwise a key value pair whose strings are left in their uninitialized <c>null</c> state.</returns> + KeyValuePair<string, string> RetrieveTemporaryCredential(); + + /// <summary> + /// Clears the temporary credentials from storage. + /// </summary> + /// <remarks> + /// DotNetOpenAuth calls this when the credentials are no longer needed. + /// </remarks> + void ClearTemporaryCredential(); + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/MemoryTemporaryCredentialStorage.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/MemoryTemporaryCredentialStorage.cs new file mode 100644 index 0000000..832084d --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/MemoryTemporaryCredentialStorage.cs @@ -0,0 +1,65 @@ +//----------------------------------------------------------------------- +// <copyright file="MemoryTemporaryCredentialStorage.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + /// <summary> + /// Non-persistent memory storage for temporary credentials. + /// Useful for installed apps (not redirection based web apps). + /// </summary> + public class MemoryTemporaryCredentialStorage : ITemporaryCredentialStorage { + /// <summary> + /// The identifier. + /// </summary> + private string identifier; + + /// <summary> + /// The secret. + /// </summary> + private string secret; + + #region ITemporaryCredentialStorage Members + + /// <summary> + /// Saves the specified temporary credential for later retrieval. + /// </summary> + /// <param name="identifier">The identifier.</param> + /// <param name="secret">The secret.</param> + public void SaveTemporaryCredential(string identifier, string secret) { + this.identifier = identifier; + this.secret = secret; + } + + /// <summary> + /// Obtains a temporary credential secret, if available. + /// </summary> + /// <returns> + /// The temporary credential secret if available; otherwise <c>null</c>. + /// </returns> + public KeyValuePair<string, string> RetrieveTemporaryCredential() { + return new KeyValuePair<string, string>(this.identifier, this.secret); + } + + /// <summary> + /// Clears the temporary credentials from storage. + /// </summary> + /// <param name="identifier">The identifier of the credentials to clear.</param> + /// <remarks> + /// DotNetOpenAuth calls this when the credentials are no longer needed. + /// </remarks> + public void ClearTemporaryCredential() { + this.identifier = null; + this.secret = null; + } + + #endregion + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HmacSha1HttpMessageHandler.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HmacSha1HttpMessageHandler.cs new file mode 100644 index 0000000..91a3b76 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HmacSha1HttpMessageHandler.cs @@ -0,0 +1,59 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth1HmacSha1HttpMessageHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Security.Cryptography; + using System.Text; + using System.Threading.Tasks; + + /// <summary> + /// A delegating HTTP handler that signs outgoing HTTP requests + /// with an HMAC-SHA1 signature. + /// </summary> + public class OAuth1HmacSha1HttpMessageHandler : OAuth1HttpMessageHandlerBase { + /// <summary> + /// Initializes a new instance of the <see cref="OAuth1HmacSha1HttpMessageHandler"/> class. + /// </summary> + public OAuth1HmacSha1HttpMessageHandler() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="OAuth1HmacSha1HttpMessageHandler"/> class. + /// </summary> + /// <param name="innerHandler">The inner handler which is responsible for processing the HTTP response messages.</param> + public OAuth1HmacSha1HttpMessageHandler(HttpMessageHandler innerHandler) + : base(innerHandler) { + } + + /// <summary> + /// Gets the signature method to include in the oauth_signature_method parameter. + /// </summary> + /// <value> + /// The signature method. + /// </value> + protected override string SignatureMethod { + get { return "HMAC-SHA1"; } + } + + /// <summary> + /// Calculates the signature for the specified buffer. + /// </summary> + /// <param name="signedPayload">The payload to calculate the signature for.</param> + /// <returns> + /// The signature. + /// </returns> + protected override byte[] Sign(byte[] signedPayload) { + using (var algorithm = HMACSHA1.Create()) { + algorithm.Key = Encoding.ASCII.GetBytes(this.GetConsumerAndTokenSecretString()); + return algorithm.ComputeHash(signedPayload); + } + } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HttpMessageHandlerBase.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HttpMessageHandlerBase.cs new file mode 100644 index 0000000..aa462f3 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HttpMessageHandlerBase.cs @@ -0,0 +1,398 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth1HttpMessageHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Globalization; + using System.Linq; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using System.Web; + using DotNetOpenAuth.Messaging; + using Validation; + + /// <summary> + /// A base class for delegating <see cref="HttpMessageHandler" />s that sign + /// outgoing HTTP requests per the OAuth 1.0 "3.4 Signature" in RFC 5849. + /// </summary> + /// <remarks> + /// http://tools.ietf.org/html/rfc5849#section-3.4 + /// </remarks> + public abstract class OAuth1HttpMessageHandlerBase : DelegatingHandler { + /// <summary> + /// These are the characters that may be chosen from when forming a random nonce. + /// </summary> + private const string AllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + /// <summary> + /// The default nonce length. + /// </summary> + private const int DefaultNonceLength = 8; + + /// <summary> + /// The default parameters location. + /// </summary> + private const OAuthParametersLocation DefaultParametersLocation = OAuthParametersLocation.AuthorizationHttpHeader; + + /// <summary> + /// The reference date and time for calculating time stamps. + /// </summary> + private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + /// <summary> + /// An array containing simply the amperstand character. + /// </summary> + private static readonly char[] ParameterSeparatorAsArray = new char[] { '&' }; + + /// <summary> + /// Initializes a new instance of the <see cref="OAuth1HttpMessageHandlerBase"/> class. + /// </summary> + protected OAuth1HttpMessageHandlerBase() { + this.NonceLength = DefaultNonceLength; + this.Location = DefaultParametersLocation; + } + + /// <summary> + /// Initializes a new instance of the <see cref="OAuth1HttpMessageHandlerBase"/> class. + /// </summary> + /// <param name="innerHandler">The inner handler which is responsible for processing the HTTP response messages.</param> + protected OAuth1HttpMessageHandlerBase(HttpMessageHandler innerHandler) + : base(innerHandler) { + this.NonceLength = DefaultNonceLength; + this.Location = DefaultParametersLocation; + } + + /// <summary> + /// The locations that oauth parameters may be added to HTTP requests. + /// </summary> + public enum OAuthParametersLocation { + /// <summary> + /// The oauth parameters are added to the query string in the URL. + /// </summary> + QueryString, + + /// <summary> + /// An HTTP Authorization header is added with the OAuth scheme. + /// </summary> + AuthorizationHttpHeader, + } + + /// <summary> + /// Gets or sets the location to add OAuth parameters to outbound HTTP requests. + /// </summary> + public OAuthParametersLocation Location { get; set; } + + /// <summary> + /// Gets or sets the consumer key. + /// </summary> + /// <value> + /// The consumer key. + /// </value> + public string ConsumerKey { get; set; } + + /// <summary> + /// Gets or sets the consumer secret. + /// </summary> + /// <value> + /// The consumer secret. + /// </value> + public string ConsumerSecret { get; set; } + + /// <summary> + /// Gets or sets the access token. + /// </summary> + /// <value> + /// The access token. + /// </value> + public string AccessToken { get; set; } + + /// <summary> + /// Gets or sets the access token secret. + /// </summary> + /// <value> + /// The access token secret. + /// </value> + public string AccessTokenSecret { get; set; } + + /// <summary> + /// Gets or sets the length of the nonce. + /// </summary> + /// <value> + /// The length of the nonce. + /// </value> + public int NonceLength { get; set; } + + /// <summary> + /// Gets the signature method to include in the oauth_signature_method parameter. + /// </summary> + /// <value> + /// The signature method. + /// </value> + protected abstract string SignatureMethod { get; } + + /// <summary> + /// Applies OAuth authorization to the specified request. + /// This method is applied automatically to outbound requests that use this message handler instance. + /// However this method may be useful for obtaining the OAuth 1.0 signature without actually sending the request. + /// </summary> + /// <param name="request">The request.</param> + public void ApplyAuthorization(HttpRequestMessage request) { + Requires.NotNull(request, "request"); + + var oauthParameters = this.GetOAuthParameters(); + string signature = this.GetSignature(request, oauthParameters); + oauthParameters.Add("oauth_signature", signature); + + // Add parameters and signature to request. + switch (this.Location) { + case OAuthParametersLocation.AuthorizationHttpHeader: + // Some oauth parameters may have been put in the query string of the original message. + // We want to move any that we find into the authorization header. + oauthParameters.Add(ExtractOAuthParametersFromQueryString(request)); + + request.Headers.Authorization = new AuthenticationHeaderValue(Protocol.AuthorizationHeaderScheme, MessagingUtilities.AssembleAuthorizationHeader(oauthParameters.AsKeyValuePairs())); + break; + case OAuthParametersLocation.QueryString: + var uriBuilder = new UriBuilder(request.RequestUri); + uriBuilder.AppendQueryArgs(oauthParameters.AsKeyValuePairs()); + request.RequestUri = uriBuilder.Uri; + break; + } + } + + /// <summary> + /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. + /// </summary> + /// <param name="request">The HTTP request message to send to the server.</param> + /// <param name="cancellationToken">A cancellation token to cancel operation.</param> + /// <returns> + /// Returns <see cref="T:System.Threading.Tasks.Task`1" />. The task object representing the asynchronous operation. + /// </returns> + protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + Requires.NotNull(request, "request"); + cancellationToken.ThrowIfCancellationRequested(); + this.ApplyAuthorization(request); + return base.SendAsync(request, cancellationToken); + } + + /// <summary> + /// Calculates the signature for the specified buffer. + /// </summary> + /// <param name="signedPayload">The payload to calculate the signature for.</param> + /// <returns>The signature.</returns> + protected abstract byte[] Sign(byte[] signedPayload); + + /// <summary> + /// Gets the OAuth 1.0 signature to apply to the specified request. + /// </summary> + /// <param name="request">The outbound HTTP request.</param> + /// <param name="oauthParameters">The oauth parameters.</param> + /// <returns> + /// The value for the "oauth_signature" parameter. + /// </returns> + protected virtual string GetSignature(HttpRequestMessage request, NameValueCollection oauthParameters) { + Requires.NotNull(request, "request"); + Requires.NotNull(oauthParameters, "oauthParameters"); + + string signatureBaseString = this.ConstructSignatureBaseString(request, oauthParameters); + byte[] signatureBaseStringBytes = Encoding.ASCII.GetBytes(signatureBaseString); + byte[] signatureBytes = this.Sign(signatureBaseStringBytes); + string signatureString = Convert.ToBase64String(signatureBytes); + return signatureString; + } + + /// <summary> + /// Gets the "ConsumerSecret&AccessTokenSecret" string, allowing either property to be empty or null. + /// </summary> + /// <returns>The concatenated string.</returns> + /// <remarks> + /// This is useful in the PLAINTEXT and HMAC-SHA1 signature algorithms. + /// </remarks> + protected string GetConsumerAndTokenSecretString() { + var builder = new StringBuilder(); + builder.Append(UrlEscape(this.ConsumerSecret ?? string.Empty)); + builder.Append("&"); + builder.Append(UrlEscape(this.AccessTokenSecret ?? string.Empty)); + return builder.ToString(); + } + + /// <summary> + /// Escapes a value for transport in a URI, per RFC 3986. + /// </summary> + /// <param name="value">The value to escape. Null and empty strings are OK.</param> + /// <returns>The escaped value. Never null.</returns> + private static string UrlEscape(string value) { + return MessagingUtilities.EscapeUriDataStringRfc3986(value ?? string.Empty); + } + + /// <summary> + /// Returns the OAuth 1.0 timestamp for the current time. + /// </summary> + /// <param name="dateTime">The date time.</param> + /// <returns>A string representation of the number of seconds since "the epoch".</returns> + private static string ToTimeStamp(DateTime dateTime) { + Requires.Argument(dateTime.Kind == DateTimeKind.Utc, "dateTime", "UTC time required"); + TimeSpan ts = dateTime - epoch; + long secondsSinceEpoch = (long)ts.TotalSeconds; + return secondsSinceEpoch.ToString(CultureInfo.InvariantCulture); + } + + /// <summary> + /// Constructs the "Base String URI" as described in http://tools.ietf.org/html/rfc5849#section-3.4.1.2 + /// </summary> + /// <param name="requestUri">The request URI.</param> + /// <returns> + /// The string to include in the signature base string. + /// </returns> + private static string GetBaseStringUri(Uri requestUri) { + Requires.NotNull(requestUri, "requestUri"); + + var endpoint = new UriBuilder(requestUri); + endpoint.Query = null; + endpoint.Fragment = null; + return endpoint.Uri.AbsoluteUri; + } + + /// <summary> + /// Collects and removes all query string parameters beginning with "oauth_" from the specified request, + /// and returns them as a collection. + /// </summary> + /// <param name="request">The request whose query string should be searched for "oauth_" parameters.</param> + /// <returns>The collection of parameters that were removed from the query string.</returns> + private static NameValueCollection ExtractOAuthParametersFromQueryString(HttpRequestMessage request) { + Requires.NotNull(request, "request"); + + var extracted = new NameValueCollection(); + if (!string.IsNullOrEmpty(request.RequestUri.Query)) { + var queryString = HttpUtility.ParseQueryString(request.RequestUri.Query); + foreach (var pair in queryString.AsKeyValuePairs()) { + if (pair.Key.StartsWith(Protocol.ParameterPrefix, StringComparison.Ordinal)) { + extracted.Add(pair.Key, pair.Value); + } + } + + if (extracted.Count > 0) { + foreach (string key in extracted) { + queryString.Remove(key); + } + + var modifiedRequestUri = new UriBuilder(request.RequestUri); + modifiedRequestUri.Query = MessagingUtilities.CreateQueryString(queryString.AsKeyValuePairs()); + request.RequestUri = modifiedRequestUri.Uri; + } + } + + return extracted; + } + + /// <summary> + /// Constructs the "Signature Base String" as described in http://tools.ietf.org/html/rfc5849#section-3.4.1 + /// </summary> + /// <param name="request">The HTTP request message.</param> + /// <param name="oauthParameters">The oauth parameters.</param> + /// <returns> + /// The signature base string. + /// </returns> + private string ConstructSignatureBaseString(HttpRequestMessage request, NameValueCollection oauthParameters) { + Requires.NotNull(request, "request"); + Requires.NotNull(oauthParameters, "oauthParameters"); + + var builder = new StringBuilder(); + builder.Append(UrlEscape(request.Method.ToString().ToUpperInvariant())); + builder.Append("&"); + builder.Append(UrlEscape(GetBaseStringUri(request.RequestUri))); + builder.Append("&"); + builder.Append(UrlEscape(this.GetNormalizedParameters(request, oauthParameters))); + + return builder.ToString(); + } + + /// <summary> + /// Generates a string of random characters for use as a nonce. + /// </summary> + /// <returns>The nonce string.</returns> + private string GenerateUniqueFragment() { + return MessagingUtilities.GetRandomString(this.NonceLength, AllowedCharacters); + } + + /// <summary> + /// Gets the "oauth_" prefixed parameters that should be added to an outbound request. + /// </summary> + /// <returns>A collection of name=value pairs.</returns> + private NameValueCollection GetOAuthParameters() { + var nvc = new NameValueCollection(8); + nvc.Add("oauth_version", "1.0"); + nvc.Add("oauth_nonce", this.GenerateUniqueFragment()); + nvc.Add("oauth_timestamp", ToTimeStamp(DateTime.UtcNow)); + nvc.Add("oauth_signature_method", this.SignatureMethod); + nvc.Add("oauth_consumer_key", this.ConsumerKey); + if (!string.IsNullOrEmpty(this.AccessToken)) { + nvc.Add("oauth_token", this.AccessToken); + } + + return nvc; + } + + /// <summary> + /// Gets a normalized string of the query string parameters included in the request and the additional OAuth parameters. + /// </summary> + /// <param name="request">The HTTP request.</param> + /// <param name="oauthParameters">The oauth parameters that will be added to the request.</param> + /// <returns>The normalized string of parameters to included in the signature base string.</returns> + private string GetNormalizedParameters(HttpRequestMessage request, NameValueCollection oauthParameters) { + Requires.NotNull(request, "request"); + Requires.NotNull(oauthParameters, "oauthParameters"); + + NameValueCollection nvc; + if (request.RequestUri.Query != null) { + // NameValueCollection does support non-unique keys, as long as you use it carefully. + nvc = HttpUtility.ParseQueryString(request.RequestUri.Query); + } else { + nvc = new NameValueCollection(8); + } + + // Add OAuth parameters. + nvc.Add(oauthParameters); + + // Now convert the NameValueCollection into an ordered list, and properly escape all keys and value while we're at it. + var list = new List<KeyValuePair<string, string>>(nvc.Count); + foreach (var pair in nvc.AsKeyValuePairs()) { + string escapedKey = UrlEscape(pair.Key); + string escapedValue = UrlEscape(pair.Value ?? string.Empty); // value can be null if no "=" appears in the query string for this key. + list.Add(new KeyValuePair<string, string>(escapedKey, escapedValue)); + } + + // Sort the parameters + list.Sort((kv1, kv2) => { + int compare = string.Compare(kv1.Key, kv2.Key, StringComparison.Ordinal); + if (compare != 0) { + return compare; + } + + return string.Compare(kv1.Value, kv2.Value, StringComparison.Ordinal); + }); + + // Convert this sorted list into a single concatenated string. + var normalizedParameterString = new StringBuilder(); + foreach (var pair in list) { + if (normalizedParameterString.Length > 0) { + normalizedParameterString.Append("&"); + } + + normalizedParameterString.Append(pair.Key); + normalizedParameterString.Append("="); + normalizedParameterString.Append(pair.Value); + } + + return normalizedParameterString.ToString(); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1PlainTextMessageHandler.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1PlainTextMessageHandler.cs new file mode 100644 index 0000000..b2e13d6 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1PlainTextMessageHandler.cs @@ -0,0 +1,59 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth1PlainTextMessageHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Collections.Specialized; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; + + /// <summary> + /// A delegating HTTP handler that signs outgoing HTTP requests + /// with the PLAINTEXT signature. + /// </summary> + public class OAuth1PlainTextMessageHandler : OAuth1HttpMessageHandlerBase { + /// <summary> + /// Gets the signature method to include in the oauth_signature_method parameter. + /// </summary> + /// <value> + /// The signature method. + /// </value> + protected override string SignatureMethod { + get { return "PLAINTEXT"; } + } + + /// <summary> + /// Calculates the signature for the specified buffer. + /// </summary> + /// <param name="signedPayload">The payload to calculate the signature for.</param> + /// <returns> + /// The signature. + /// </returns> + /// <exception cref="System.NotImplementedException">Always thrown.</exception> + protected override byte[] Sign(byte[] signedPayload) { + throw new NotImplementedException(); + } + + /// <summary> + /// Gets the OAuth 1.0 signature to apply to the specified request. + /// </summary> + /// <param name="request">The outbound HTTP request.</param> + /// <param name="oauthParameters">The oauth parameters.</param> + /// <returns> + /// The value for the "oauth_signature" parameter. + /// </returns> + protected override string GetSignature(System.Net.Http.HttpRequestMessage request, NameValueCollection oauthParameters) { + var builder = new StringBuilder(); + builder.Append(MessagingUtilities.EscapeUriDataStringRfc3986(this.ConsumerSecret)); + builder.Append("&"); + builder.Append(MessagingUtilities.EscapeUriDataStringRfc3986(this.AccessTokenSecret)); + return builder.ToString(); + } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1RsaSha1HttpMessageHandler.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1RsaSha1HttpMessageHandler.cs new file mode 100644 index 0000000..129ebc2 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1RsaSha1HttpMessageHandler.cs @@ -0,0 +1,66 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuth1RsaSha1HttpMessageHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Security.Cryptography; + using System.Security.Cryptography.X509Certificates; + using System.Text; + using System.Threading.Tasks; + using Validation; + + /// <summary> + /// A delegating HTTP handler that signs outgoing HTTP requests + /// with an RSA-SHA1 signature. + /// </summary> + public class OAuth1RsaSha1HttpMessageHandler : OAuth1HttpMessageHandlerBase { + /// <summary> + /// Initializes a new instance of the <see cref="OAuth1RsaSha1HttpMessageHandler"/> class. + /// </summary> + public OAuth1RsaSha1HttpMessageHandler() { + } + + /// <summary> + /// Initializes a new instance of the <see cref="OAuth1RsaSha1HttpMessageHandler"/> class. + /// </summary> + /// <param name="innerHandler">The inner handler which is responsible for processing the HTTP response messages.</param> + public OAuth1RsaSha1HttpMessageHandler(HttpMessageHandler innerHandler) + : base(innerHandler) { + } + + /// <summary> + /// Gets or sets the certificate used to sign outgoing messages. Used only by Consumers. + /// </summary> + public X509Certificate2 SigningCertificate { get; set; } + + /// <summary> + /// Gets the signature method to include in the oauth_signature_method parameter. + /// </summary> + /// <value> + /// The signature method. + /// </value> + protected override string SignatureMethod { + get { return "RSA-SHA1"; } + } + + /// <summary> + /// Calculates the signature for the specified buffer. + /// </summary> + /// <param name="signedPayload">The payload to calculate the signature for.</param> + /// <returns> + /// The signature. + /// </returns> + protected override byte[] Sign(byte[] signedPayload) { + Verify.Operation(this.SigningCertificate != null, Strings.RequiredPropertyNotYetPreset); + var provider = (RSACryptoServiceProvider)this.SigningCertificate.PrivateKey; + byte[] binarySignature = provider.SignData(signedPayload, "SHA1"); + return binarySignature; + } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ServiceProviderDescription.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ServiceProviderDescription.cs new file mode 100644 index 0000000..2d07af4 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ServiceProviderDescription.cs @@ -0,0 +1,85 @@ +//----------------------------------------------------------------------- +// <copyright file="ServiceProviderDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OAuth { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + using Validation; + + /// <summary> + /// Describes an OAuth 1.0 service provider. + /// </summary> + public class ServiceProviderDescription { + /// <summary> + /// Initializes a new instance of the <see cref="ServiceProviderDescription" /> class. + /// </summary> + public ServiceProviderDescription() { + this.TemporaryCredentialsRequestEndpointMethod = HttpMethod.Post; + this.TokenRequestEndpointMethod = HttpMethod.Post; + } + + /// <summary> + /// Initializes a new instance of the <see cref="ServiceProviderDescription"/> class. + /// </summary> + /// <param name="temporaryCredentialsRequestEndpoint">The temporary credentials request endpoint.</param> + /// <param name="resourceOwnerAuthorizationEndpoint">The resource owner authorization endpoint.</param> + /// <param name="tokenRequestEndpoint">The token request endpoint.</param> + public ServiceProviderDescription( + string temporaryCredentialsRequestEndpoint, string resourceOwnerAuthorizationEndpoint, string tokenRequestEndpoint) + : this() { + if (temporaryCredentialsRequestEndpoint != null) { + this.TemporaryCredentialsRequestEndpoint = new Uri(temporaryCredentialsRequestEndpoint, UriKind.Absolute); + } + + if (resourceOwnerAuthorizationEndpoint != null) { + this.ResourceOwnerAuthorizationEndpoint = new Uri(resourceOwnerAuthorizationEndpoint, UriKind.Absolute); + } + + if (tokenRequestEndpoint != null) { + this.TokenRequestEndpoint = new Uri(tokenRequestEndpoint, UriKind.Absolute); + } + } + + /// <summary> + /// Gets or sets the temporary credentials request endpoint. + /// </summary> + /// <value> + /// The temporary credentials request endpoint. + /// </value> + public Uri TemporaryCredentialsRequestEndpoint { get; set; } + + /// <summary> + /// Gets or sets the HTTP method to use with the temporary credentials request endpoint. + /// </summary> + public HttpMethod TemporaryCredentialsRequestEndpointMethod { get; set; } + + /// <summary> + /// Gets the resource owner authorization endpoint. + /// </summary> + /// <value> + /// The resource owner authorization endpoint. + /// May be <c>null</c> for 2-legged OAuth. + /// </value> + public Uri ResourceOwnerAuthorizationEndpoint { get; set; } + + /// <summary> + /// Gets the token request endpoint. + /// </summary> + /// <value> + /// The token request endpoint. + /// </value> + public Uri TokenRequestEndpoint { get; set; } + + /// <summary> + /// Gets or sets the HTTP method to use with the token request endpoint. + /// </summary> + public HttpMethod TokenRequestEndpointMethod { get; set; } + } +} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs deleted file mode 100644 index 4d4e67c..0000000 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/WebConsumer.cs +++ /dev/null @@ -1,92 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="WebConsumer.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth { - using System; - using System.Collections.Generic; - using System.Web; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - using Validation; - - /// <summary> - /// A website or application that uses OAuth to access the Service Provider on behalf of the User. - /// </summary> - /// <remarks> - /// The methods on this class are thread-safe. Provided the properties are set and not changed - /// afterward, a single instance of this class may be used by an entire web application safely. - /// </remarks> - public class WebConsumer : ConsumerBase { - /// <summary> - /// Initializes a new instance of the <see cref="WebConsumer"/> class. - /// </summary> - /// <param name="serviceDescription">The endpoints and behavior of the Service Provider.</param> - /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> - public WebConsumer(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) - : base(serviceDescription, tokenManager) { - } - - /// <summary> - /// Begins an OAuth authorization request and redirects the user to the Service Provider - /// to provide that authorization. Upon successful authorization, the user is redirected - /// back to the current page. - /// </summary> - /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> - /// <remarks> - /// Requires HttpContext.Current. - /// </remarks> - public UserAuthorizationRequest PrepareRequestUserAuthorization() { - Uri callback = this.Channel.GetRequestFromContext().GetPublicFacingUrl().StripQueryArgumentsWithPrefix(Protocol.ParameterPrefix); - return this.PrepareRequestUserAuthorization(callback, null, null); - } - - /// <summary> - /// Prepares an OAuth message that begins an authorization request that will - /// redirect the user to the Service Provider to provide that authorization. - /// </summary> - /// <param name="callback"> - /// An optional Consumer URL that the Service Provider should redirect the - /// User Agent to upon successful authorization. - /// </param> - /// <param name="requestParameters">Extra parameters to add to the request token message. Optional.</param> - /// <param name="redirectParameters">Extra parameters to add to the redirect to Service Provider message. Optional.</param> - /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns> - public UserAuthorizationRequest PrepareRequestUserAuthorization(Uri callback, IDictionary<string, string> requestParameters, IDictionary<string, string> redirectParameters) { - string token; - return this.PrepareRequestUserAuthorization(callback, requestParameters, redirectParameters, out token); - } - - /// <summary> - /// Processes an incoming authorization-granted message from an SP and obtains an access token. - /// </summary> - /// <returns>The access token, or null if no incoming authorization message was recognized.</returns> - /// <remarks> - /// Requires HttpContext.Current. - /// </remarks> - public AuthorizedTokenResponse ProcessUserAuthorization() { - return this.ProcessUserAuthorization(this.Channel.GetRequestFromContext()); - } - - /// <summary> - /// Processes an incoming authorization-granted message from an SP and obtains an access token. - /// </summary> - /// <param name="request">The incoming HTTP request.</param> - /// <returns>The access token, or null if no incoming authorization message was recognized.</returns> - public AuthorizedTokenResponse ProcessUserAuthorization(HttpRequestBase request) { - Requires.NotNull(request, "request"); - - UserAuthorizationResponse authorizationMessage; - if (this.Channel.TryReadFromRequest<UserAuthorizationResponse>(request, out authorizationMessage)) { - string requestToken = authorizationMessage.RequestToken; - string verifier = authorizationMessage.VerificationCode; - return this.ProcessUserAuthorization(requestToken, verifier); - } else { - return null; - } - } - } -} diff --git a/src/DotNetOpenAuth.OAuth.Consumer/packages.config b/src/DotNetOpenAuth.OAuth.Consumer/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/packages.config +++ b/src/DotNetOpenAuth.OAuth.Consumer/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj b/src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj index 94a4e6c..8e87ad4 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/DotNetOpenAuth.OAuth.ServiceProvider.csproj @@ -19,18 +19,19 @@ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> </PropertyGroup> <ItemGroup> + <Compile Include="OAuthReporting.cs" /> <Compile Include="OAuth\ChannelElements\IConsumerDescription.cs" /> <Compile Include="OAuth\ChannelElements\IServiceProviderAccessToken.cs" /> <Compile Include="OAuth\ChannelElements\IServiceProviderRequestToken.cs" /> <Compile Include="OAuth\ChannelElements\IServiceProviderTokenManager.cs" /> <Compile Include="OAuth\ChannelElements\ITokenGenerator.cs" /> - <Compile Include="OAuth\ChannelElements\OAuth1Principal.cs" /> <Compile Include="OAuth\ChannelElements\OAuthServiceProviderChannel.cs" /> <Compile Include="OAuth\ChannelElements\OAuthServiceProviderMessageFactory.cs" /> <Compile Include="OAuth\ChannelElements\RsaSha1ServiceProviderSigningBindingElement.cs" /> <Compile Include="OAuth\ChannelElements\StandardTokenGenerator.cs" /> <Compile Include="OAuth\ChannelElements\TokenHandlingBindingElement.cs" /> <Compile Include="OAuth\ServiceProvider.cs" /> + <Compile Include="OAuth\ServiceProviderHostDescription.cs" /> <Compile Include="OAuth\VerificationCodeFormat.cs" /> <Compile Include="Properties\AssemblyInfo.cs"> <SubType> @@ -52,9 +53,11 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuth1Principal.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuth1Principal.cs deleted file mode 100644 index ff44a45..0000000 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuth1Principal.cs +++ /dev/null @@ -1,34 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OAuth1Principal.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.OAuth.ChannelElements { - using System; - using System.Collections.Generic; - using System.Diagnostics.CodeAnalysis; - using System.Linq; - using System.Runtime.InteropServices; - using System.Text; - using Validation; - - /// <summary> - /// Represents an OAuth consumer that is impersonating a known user on the system. - /// </summary> - [SuppressMessage("Microsoft.Interoperability", "CA1409:ComVisibleTypesShouldBeCreatable", Justification = "Not cocreatable.")] - [Serializable] - [ComVisible(true)] - internal class OAuth1Principal : OAuthPrincipal { - /// <summary> - /// Initializes a new instance of the <see cref="OAuth1Principal"/> class. - /// </summary> - /// <param name="token">The access token.</param> - internal OAuth1Principal(IServiceProviderAccessToken token) - : base(token.Username, token.Roles) { - Requires.NotNull(token, "token"); - - this.AccessToken = token.Token; - } - } -} diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs index 62019d8..cb9a91b 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/OAuthServiceProviderChannel.cs @@ -19,21 +19,23 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </summary> internal class OAuthServiceProviderChannel : OAuthChannel { /// <summary> - /// Initializes a new instance of the <see cref="OAuthServiceProviderChannel"/> class. + /// Initializes a new instance of the <see cref="OAuthServiceProviderChannel" /> class. /// </summary> /// <param name="signingBindingElement">The binding element to use for signing.</param> /// <param name="store">The web application store to use for nonces.</param> /// <param name="tokenManager">The token manager instance to use.</param> /// <param name="securitySettings">The security settings.</param> /// <param name="messageTypeProvider">The message type provider.</param> + /// <param name="hostFactories">The host factories.</param> [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")] - internal OAuthServiceProviderChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, IServiceProviderTokenManager tokenManager, ServiceProviderSecuritySettings securitySettings, IMessageFactory messageTypeProvider = null) + internal OAuthServiceProviderChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, IServiceProviderTokenManager tokenManager, ServiceProviderSecuritySettings securitySettings, IMessageFactory messageTypeProvider = null, IHostFactories hostFactories = null) : base( signingBindingElement, tokenManager, securitySettings, messageTypeProvider ?? new OAuthServiceProviderMessageFactory(tokenManager), - InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) { + InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings), + hostFactories) { Requires.NotNull(tokenManager, "tokenManager"); Requires.NotNull(securitySettings, "securitySettings"); Requires.NotNull(signingBindingElement, "signingBindingElement"); diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs index 22c254f..5875650 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ChannelElements/TokenHandlingBindingElement.cs @@ -10,6 +10,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth.Messages; @@ -68,6 +70,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -76,13 +79,13 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var userAuthResponse = message as UserAuthorizationResponse; if (userAuthResponse != null && userAuthResponse.Version >= Protocol.V10a.Version) { var requestToken = this.tokenManager.GetRequestToken(userAuthResponse.RequestToken); requestToken.VerificationCode = userAuthResponse.VerificationCode; this.tokenManager.UpdateToken(requestToken); - return MessageProtections.None; + return MessageProtectionTasks.None; } // Hook to store the token and secret on its way down to the Consumer. @@ -98,10 +101,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { } this.tokenManager.UpdateToken(requestToken); - return MessageProtections.None; + return MessageProtectionTasks.None; } - return null; + return MessageProtectionTasks.Null; } /// <summary> @@ -109,6 +112,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -121,13 +125,13 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var authorizedTokenRequest = message as AuthorizedTokenRequest; if (authorizedTokenRequest != null) { if (authorizedTokenRequest.Version >= Protocol.V10a.Version) { string expectedVerifier = this.tokenManager.GetRequestToken(authorizedTokenRequest.RequestToken).VerificationCode; ErrorUtilities.VerifyProtocol(string.Equals(authorizedTokenRequest.VerificationCode, expectedVerifier, StringComparison.Ordinal), OAuthStrings.IncorrectVerifier); - return MessageProtections.None; + return MessageProtectionTasks.None; } this.VerifyThrowTokenTimeToLive(authorizedTokenRequest); @@ -143,7 +147,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { this.VerifyThrowTokenNotExpired(accessResourceRequest); } - return null; + return MessageProtectionTasks.Null; } #endregion diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs index d2152ea..b163d0d 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProvider.cs @@ -10,8 +10,11 @@ namespace DotNetOpenAuth.OAuth { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; + using System.Net.Http; using System.Security.Principal; using System.ServiceModel.Channels; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; @@ -53,7 +56,7 @@ namespace DotNetOpenAuth.OAuth { /// </summary> /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param> /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> - public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager) + public ServiceProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager) : this(serviceDescription, tokenManager, new OAuthServiceProviderMessageFactory(tokenManager)) { } @@ -63,8 +66,8 @@ namespace DotNetOpenAuth.OAuth { /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param> /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> /// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param> - public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, OAuthServiceProviderMessageFactory messageTypeProvider) - : this(serviceDescription, tokenManager, OAuthElement.Configuration.ServiceProvider.ApplicationStore.CreateInstance(HttpApplicationStore), messageTypeProvider) { + public ServiceProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager, OAuthServiceProviderMessageFactory messageTypeProvider) + : this(serviceDescription, tokenManager, OAuthElement.Configuration.ServiceProvider.ApplicationStore.CreateInstance(GetHttpApplicationStore(), null), messageTypeProvider) { Requires.NotNull(serviceDescription, "serviceDescription"); Requires.NotNull(tokenManager, "tokenManager"); Requires.NotNull(messageTypeProvider, "messageTypeProvider"); @@ -76,7 +79,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param> /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> /// <param name="nonceStore">The nonce store.</param> - public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore) + public ServiceProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore) : this(serviceDescription, tokenManager, nonceStore, new OAuthServiceProviderMessageFactory(tokenManager)) { } @@ -87,7 +90,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> /// <param name="nonceStore">The nonce store.</param> /// <param name="messageTypeProvider">An object that can figure out what type of message is being received for deserialization.</param> - public ServiceProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore, OAuthServiceProviderMessageFactory messageTypeProvider) { + public ServiceProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore, OAuthServiceProviderMessageFactory messageTypeProvider) { Requires.NotNull(serviceDescription, "serviceDescription"); Requires.NotNull(tokenManager, "tokenManager"); Requires.NotNull(nonceStore, "nonceStore"); @@ -103,34 +106,9 @@ namespace DotNetOpenAuth.OAuth { } /// <summary> - /// Gets the standard state storage mechanism that uses ASP.NET's - /// HttpApplication state dictionary to store associations and nonces. - /// </summary> - [EditorBrowsable(EditorBrowsableState.Advanced)] - public static INonceStore HttpApplicationStore { - get { - HttpContext context = HttpContext.Current; - ErrorUtilities.VerifyOperation(context != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(INonceStore).Name); - var store = (INonceStore)context.Application[ApplicationStoreKey]; - if (store == null) { - context.Application.Lock(); - try { - if ((store = (INonceStore)context.Application[ApplicationStoreKey]) == null) { - context.Application[ApplicationStoreKey] = store = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge); - } - } finally { - context.Application.UnLock(); - } - } - - return store; - } - } - - /// <summary> /// Gets the description of this Service Provider. /// </summary> - public ServiceProviderDescription ServiceDescription { get; private set; } + public ServiceProviderHostDescription ServiceDescription { get; private set; } /// <summary> /// Gets or sets the generator responsible for generating new tokens and secrets. @@ -171,6 +149,33 @@ namespace DotNetOpenAuth.OAuth { } /// <summary> + /// Gets the standard state storage mechanism that uses ASP.NET's + /// HttpApplication state dictionary to store associations and nonces. + /// </summary> + /// <param name="context">The HTTP context. If <c>null</c>, this method must be called while <see cref="HttpContext.Current"/> is non-null.</param> + /// <returns>The nonce store.</returns> + public static INonceStore GetHttpApplicationStore(HttpContextBase context = null) { + if (context == null) { + ErrorUtilities.VerifyOperation(HttpContext.Current != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(INonceStore).Name); + context = new HttpContextWrapper(HttpContext.Current); + } + + var store = (INonceStore)context.Application[ApplicationStoreKey]; + if (store == null) { + context.Application.Lock(); + try { + if ((store = (INonceStore)context.Application[ApplicationStoreKey]) == null) { + context.Application[ApplicationStoreKey] = store = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge); + } + } finally { + context.Application.UnLock(); + } + } + + return store; + } + + /// <summary> /// Creates a cryptographically strong random verification code. /// </summary> /// <param name="format">The desired format of the verification code.</param> @@ -201,46 +206,65 @@ namespace DotNetOpenAuth.OAuth { /// <summary> /// Reads any incoming OAuth message. /// </summary> - /// <returns>The deserialized message.</returns> + /// <param name="request">The request.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The deserialized message. + /// </returns> /// <remarks> /// Requires HttpContext.Current. /// </remarks> - public IDirectedProtocolMessage ReadRequest() { - return this.Channel.ReadFromRequest(); + public Task<IDirectedProtocolMessage> ReadRequestAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + return this.ReadRequestAsync((request ?? this.Channel.GetRequestFromContext()).AsHttpRequestMessage(), cancellationToken); } /// <summary> /// Reads any incoming OAuth message. /// </summary> - /// <param name="request">The HTTP request to read the message from.</param> - /// <returns>The deserialized message.</returns> - public IDirectedProtocolMessage ReadRequest(HttpRequestBase request) { - return this.Channel.ReadFromRequest(request); + /// <param name="request">The request.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The deserialized message. + /// </returns> + /// <remarks> + /// Requires HttpContext.Current. + /// </remarks> + public Task<IDirectedProtocolMessage> ReadRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); + return this.Channel.ReadFromRequestAsync(request, cancellationToken); } /// <summary> - /// Gets the incoming request for an unauthorized token, if any. + /// Reads a request for an unauthorized token from the incoming HTTP request. /// </summary> - /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <param name="request">The HTTP request to read from.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> - /// <remarks> - /// Requires HttpContext.Current. - /// </remarks> - public UnauthorizedTokenRequest ReadTokenRequest() { - return this.ReadTokenRequest(this.Channel.GetRequestFromContext()); + public Task<UnauthorizedTokenRequest> ReadTokenRequestAsync( + HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + return this.ReadTokenRequestAsync((request ?? this.channel.GetRequestFromContext()).AsHttpRequestMessage(), cancellationToken); } /// <summary> /// Reads a request for an unauthorized token from the incoming HTTP request. /// </summary> /// <param name="request">The HTTP request to read from.</param> - /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> - public UnauthorizedTokenRequest ReadTokenRequest(HttpRequestBase request) { - UnauthorizedTokenRequest message; - if (this.Channel.TryReadFromRequest(request, out message)) { + public async Task<UnauthorizedTokenRequest> ReadTokenRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); + + var message = await this.Channel.TryReadFromRequestAsync<UnauthorizedTokenRequest>(request, cancellationToken); + if (message != null) { ErrorUtilities.VerifyProtocol(message.Version >= Protocol.Lookup(this.SecuritySettings.MinimumRequiredOAuthVersion).Version, OAuthStrings.MinimumConsumerVersionRequirementNotMet, this.SecuritySettings.MinimumRequiredOAuthVersion, message.Version); } + return message; } @@ -261,16 +285,18 @@ namespace DotNetOpenAuth.OAuth { } /// <summary> - /// Gets the incoming request for the Service Provider to authorize a Consumer's - /// access to some protected resources. + /// Reads in a Consumer's request for the Service Provider to obtain permission from + /// the user to authorize the Consumer's access of some protected resource(s). /// </summary> - /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <param name="request">The HTTP request to read from.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> - /// <remarks> - /// Requires HttpContext.Current. - /// </remarks> - public UserAuthorizationRequest ReadAuthorizationRequest() { - return this.ReadAuthorizationRequest(this.Channel.GetRequestFromContext()); + public Task<UserAuthorizationRequest> ReadAuthorizationRequestAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.channel.GetRequestFromContext(); + return this.ReadAuthorizationRequestAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> @@ -278,12 +304,14 @@ namespace DotNetOpenAuth.OAuth { /// the user to authorize the Consumer's access of some protected resource(s). /// </summary> /// <param name="request">The HTTP request to read from.</param> - /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> - public UserAuthorizationRequest ReadAuthorizationRequest(HttpRequestBase request) { - UserAuthorizationRequest message; - this.Channel.TryReadFromRequest(request, out message); - return message; + public Task<UserAuthorizationRequest> ReadAuthorizationRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); + return this.Channel.TryReadFromRequestAsync<UserAuthorizationRequest>(request, cancellationToken); } /// <summary> @@ -349,27 +377,31 @@ namespace DotNetOpenAuth.OAuth { } /// <summary> - /// Gets the incoming request to exchange an authorized token for an access token. + /// Reads in a Consumer's request to exchange an authorized request token for an access token. /// </summary> - /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <param name="request">The HTTP request to read from.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> - /// <remarks> - /// Requires HttpContext.Current. - /// </remarks> - public AuthorizedTokenRequest ReadAccessTokenRequest() { - return this.ReadAccessTokenRequest(this.Channel.GetRequestFromContext()); + public Task<AuthorizedTokenRequest> ReadAccessTokenRequestAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.Channel.GetRequestFromContext(); + return this.ReadAccessTokenRequestAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> /// Reads in a Consumer's request to exchange an authorized request token for an access token. /// </summary> /// <param name="request">The HTTP request to read from.</param> - /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> - public AuthorizedTokenRequest ReadAccessTokenRequest(HttpRequestBase request) { - AuthorizedTokenRequest message; - this.Channel.TryReadFromRequest(request, out message); - return message; + public Task<AuthorizedTokenRequest> ReadAccessTokenRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); + return this.Channel.TryReadFromRequestAsync<AuthorizedTokenRequest>(request, cancellationToken); } /// <summary> @@ -396,6 +428,9 @@ namespace DotNetOpenAuth.OAuth { /// <summary> /// Gets the authorization (access token) for accessing some protected resource. /// </summary> + /// <param name="request">HTTP details from an incoming WCF message.</param> + /// <param name="requestUri">The URI of the WCF service endpoint.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns> /// <remarks> /// This method verifies that the access token and token secret are valid. @@ -403,15 +438,15 @@ namespace DotNetOpenAuth.OAuth { /// to access the resources being requested. /// </remarks> /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> - public AccessProtectedResourceRequest ReadProtectedResourceAuthorization() { - return this.ReadProtectedResourceAuthorization(this.Channel.GetRequestFromContext()); + public Task<AccessProtectedResourceRequest> ReadProtectedResourceAuthorizationAsync(HttpRequestMessageProperty request, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { + return this.ReadProtectedResourceAuthorizationAsync(new HttpRequestInfo(request, requestUri), cancellationToken); } /// <summary> /// Gets the authorization (access token) for accessing some protected resource. /// </summary> - /// <param name="request">HTTP details from an incoming WCF message.</param> - /// <param name="requestUri">The URI of the WCF service endpoint.</param> + /// <param name="request">The incoming HTTP request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns> /// <remarks> /// This method verifies that the access token and token secret are valid. @@ -419,14 +454,16 @@ namespace DotNetOpenAuth.OAuth { /// to access the resources being requested. /// </remarks> /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> - public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestMessageProperty request, Uri requestUri) { - return this.ReadProtectedResourceAuthorization(new HttpRequestInfo(request, requestUri)); + public Task<AccessProtectedResourceRequest> ReadProtectedResourceAuthorizationAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.channel.GetRequestFromContext(); + return this.ReadProtectedResourceAuthorizationAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> /// Gets the authorization (access token) for accessing some protected resource. /// </summary> /// <param name="request">The incoming HTTP request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The authorization message sent by the Consumer, or null if no authorization message is attached.</returns> /// <remarks> /// This method verifies that the access token and token secret are valid. @@ -434,11 +471,10 @@ namespace DotNetOpenAuth.OAuth { /// to access the resources being requested. /// </remarks> /// <exception cref="ProtocolException">Thrown if an unexpected message is attached to the request.</exception> - public AccessProtectedResourceRequest ReadProtectedResourceAuthorization(HttpRequestBase request) { + public async Task<AccessProtectedResourceRequest> ReadProtectedResourceAuthorizationAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(request, "request"); - - AccessProtectedResourceRequest accessMessage; - if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(request, out accessMessage)) { + var accessMessage = await this.Channel.TryReadFromRequestAsync<AccessProtectedResourceRequest>(request, cancellationToken); + if (accessMessage != null) { if (this.TokenManager.GetTokenType(accessMessage.AccessToken) != TokenType.AccessToken) { throw new ProtocolException( string.Format( @@ -456,11 +492,11 @@ namespace DotNetOpenAuth.OAuth { /// </summary> /// <param name="request">The request.</param> /// <returns>The <see cref="IPrincipal"/> instance that can be used for access control of resources.</returns> - public OAuthPrincipal CreatePrincipal(AccessProtectedResourceRequest request) { + public IPrincipal CreatePrincipal(AccessProtectedResourceRequest request) { Requires.NotNull(request, "request"); IServiceProviderAccessToken accessToken = this.TokenManager.GetAccessToken(request.AccessToken); - return new OAuth1Principal(accessToken); + return OAuthPrincipal.CreatePrincipal(accessToken.Username, accessToken.Roles); } #region IDisposable Members diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderDescription.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProviderHostDescription.cs index 6dbe6ea..33834eb 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ServiceProviderDescription.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuth/ServiceProviderHostDescription.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------- -// <copyright file="ServiceProviderDescription.cs" company="Outercurve Foundation"> +// <copyright file="ServiceProviderHostDescription.cs" company="Outercurve Foundation"> // Copyright (c) Outercurve Foundation. All rights reserved. // </copyright> //----------------------------------------------------------------------- @@ -15,7 +15,7 @@ namespace DotNetOpenAuth.OAuth { /// <summary> /// A description of the endpoints on a Service Provider. /// </summary> - public class ServiceProviderDescription { + public class ServiceProviderHostDescription { /// <summary> /// The field used to store the value of the <see cref="RequestTokenEndpoint"/> property. /// </summary> @@ -23,9 +23,9 @@ namespace DotNetOpenAuth.OAuth { private MessageReceivingEndpoint requestTokenEndpoint; /// <summary> - /// Initializes a new instance of the <see cref="ServiceProviderDescription"/> class. + /// Initializes a new instance of the <see cref="ServiceProviderHostDescription"/> class. /// </summary> - public ServiceProviderDescription() { + public ServiceProviderHostDescription() { this.ProtocolVersion = Protocol.Default.ProtocolVersion; } diff --git a/src/DotNetOpenAuth.OAuth/OAuthReporting.cs b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuthReporting.cs index e2c0aab..5b00c1a 100644 --- a/src/DotNetOpenAuth.OAuth/OAuthReporting.cs +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/OAuthReporting.cs @@ -25,7 +25,7 @@ namespace DotNetOpenAuth { /// <param name="service">The service.</param> /// <param name="tokenManager">The token manager.</param> /// <param name="nonceStore">The nonce store.</param> - internal static void RecordFeatureAndDependencyUse(object value, ServiceProviderDescription service, ITokenManager tokenManager, INonceStore nonceStore) { + internal static void RecordFeatureAndDependencyUse(object value, ServiceProviderHostDescription service, ITokenManager tokenManager, INonceStore nonceStore) { Requires.NotNull(value, "value"); Requires.NotNull(service, "service"); Requires.NotNull(tokenManager, "tokenManager"); @@ -45,9 +45,7 @@ namespace DotNetOpenAuth { builder.Append(nonceStore.GetType().Name); } builder.Append(" "); - builder.Append(service.Version); - builder.Append(" "); - builder.Append(service.UserAuthorizationEndpoint); + builder.Append(service.UserAuthorizationEndpoint != null ? service.UserAuthorizationEndpoint.Location.AbsoluteUri : string.Empty); Reporting.ObservedFeatures.Add(builder.ToString()); Reporting.Touch(); } diff --git a/src/DotNetOpenAuth.OAuth.ServiceProvider/packages.config b/src/DotNetOpenAuth.OAuth.ServiceProvider/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth.ServiceProvider/packages.config +++ b/src/DotNetOpenAuth.OAuth.ServiceProvider/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj b/src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj index 651b414..af9aea9 100644 --- a/src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj +++ b/src/DotNetOpenAuth.OAuth/DotNetOpenAuth.OAuth.csproj @@ -25,7 +25,6 @@ <Compile Include="Configuration\OAuthServiceProviderElement.cs" /> <Compile Include="Configuration\OAuthServiceProviderSecuritySettingsElement.cs" /> <Compile Include="Messaging\ITamperProtectionChannelBindingElement.cs" /> - <Compile Include="OAuthReporting.cs" /> <Compile Include="OAuth\ChannelElements\ITokenManager.cs" /> <Compile Include="OAuth\ChannelElements\OAuthHttpMethodBindingElement.cs" /> <Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElement.cs" /> @@ -35,13 +34,13 @@ <Compile Include="OAuth\ChannelElements\UriOrOobEncoding.cs" /> <Compile Include="OAuth\ConsumerSecuritySettings.cs" /> <Compile Include="OAuth\Messages\ITokenSecretContainingMessage.cs" /> + <Compile Include="OAuth\Messages\MessageBaseSimple.cs" /> <Compile Include="OAuth\OAuthStrings.Designer.cs"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>OAuthStrings.resx</DependentUpon> </Compile> <Compile Include="OAuth\SecuritySettings.cs" /> - <Compile Include="OAuth\ServiceProviderDescription.cs" /> <Compile Include="OAuth\Messages\ITokenContainingMessage.cs" /> <Compile Include="OAuth\Messages\SignedMessageBase.cs" /> <Compile Include="OAuth\ChannelElements\SigningBindingElementBase.cs" /> @@ -82,11 +81,17 @@ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project> <Name>DotNetOpenAuth.Core</Name> </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OAuth.Common\DotNetOpenAuth.OAuth.Common.csproj"> + <Project>{115217c5-22cd-415c-a292-0dd0238cdd89}</Project> + <Name>DotNetOpenAuth.OAuth.Common</Name> + </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs index 9cb0a44..679b1dc 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/ITamperResistantOAuthMessage.cs @@ -7,6 +7,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using System; using System.Collections.Generic; + using System.Net.Http; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; @@ -37,7 +39,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <summary> /// Gets or sets the HTTP method that will be used to transmit the message. /// </summary> - string HttpMethod { get; set; } + HttpMethod HttpMethod { get; set; } /// <summary> /// Gets or sets the URL of the intended receiver of this message. diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs index 1362ca9..f483ade 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthChannel.cs @@ -13,8 +13,12 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using System.IO; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; @@ -22,12 +26,14 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using DotNetOpenAuth.OAuth.Messages; using Validation; + using HttpRequestHeaders = DotNetOpenAuth.Messaging.HttpRequestHeaders; + /// <summary> /// An OAuth-specific implementation of the <see cref="Channel"/> class. /// </summary> internal abstract class OAuthChannel : Channel { /// <summary> - /// Initializes a new instance of the <see cref="OAuthChannel"/> class. + /// Initializes a new instance of the <see cref="OAuthChannel" /> class. /// </summary> /// <param name="signingBindingElement">The binding element to use for signing.</param> /// <param name="tokenManager">The ITokenManager instance to use.</param> @@ -36,9 +42,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Except for mock testing, this should always be one of /// OAuthConsumerMessageFactory or OAuthServiceProviderMessageFactory.</param> /// <param name="bindingElements">The binding elements.</param> + /// <param name="hostFactories">The host factories.</param> [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")] - protected OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements) - : base(messageTypeProvider, bindingElements) { + protected OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements, IHostFactories hostFactories = null) + : base(messageTypeProvider, bindingElements, hostFactories ?? new DefaultOAuthHostFactories()) { Requires.NotNull(tokenManager, "tokenManager"); Requires.NotNull(securitySettings, "securitySettings"); Requires.NotNull(signingBindingElement, "signingBindingElement"); @@ -76,11 +83,12 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// expect an OAuth message response to. /// </summary> /// <param name="request">The message to attach.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The initialized web request.</returns> - internal HttpWebRequest InitializeRequest(IDirectedProtocolMessage request) { + internal async Task<HttpRequestMessage> InitializeRequestAsync(IDirectedProtocolMessage request, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); - ProcessOutgoingMessage(request); + await this.ProcessOutgoingMessageAsync(request, cancellationToken); return this.CreateHttpRequest(request); } @@ -108,29 +116,25 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// a protocol request message. /// </summary> /// <param name="request">The HTTP request to search.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The deserialized message, if one is found. Null otherwise.</returns> - protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { + protected override async Task<IDirectedProtocolMessage> ReadFromRequestCoreAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // First search the Authorization header. - string authorization = request.Headers[HttpRequestHeaders.Authorization]; + var authorization = request.Headers.Authorization; var fields = MessagingUtilities.ParseAuthorizationHeader(Protocol.AuthorizationHeaderScheme, authorization).ToDictionary(); fields.Remove("realm"); // ignore the realm parameter, since we don't use it, and it must be omitted from signature base string. // Scrape the entity - if (!string.IsNullOrEmpty(request.Headers[HttpRequestHeaders.ContentType])) { - var contentType = new ContentType(request.Headers[HttpRequestHeaders.ContentType]); - if (string.Equals(contentType.MediaType, HttpFormUrlEncoded, StringComparison.Ordinal)) { - foreach (string key in request.Form) { - if (key != null) { - fields.Add(key, request.Form[key]); - } else { - Logger.OAuth.WarnFormat("Ignoring query string parameter '{0}' since it isn't a standard name=value parameter.", request.Form[key]); - } - } + foreach (var pair in await ParseUrlEncodedFormContentAsync(request, cancellationToken)) { + if (pair.Key != null) { + fields.Add(pair.Key, pair.Value); + } else { + Logger.OAuth.WarnFormat("Ignoring query string parameter '{0}' since it isn't a standard name=value parameter.", pair.Value); } } // Scrape the query string - var qs = request.GetQueryStringBeforeRewriting(); + var qs = HttpUtility.ParseQueryString(request.RequestUri.Query); foreach (string key in qs) { if (key != null) { fields.Add(key, qs[key]); @@ -153,8 +157,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { // Add receiving HTTP transport information required for signature generation. var signedMessage = message as ITamperResistantOAuthMessage; if (signedMessage != null) { - signedMessage.Recipient = request.GetPublicFacingUrl(); - signedMessage.HttpMethod = request.HttpMethod; + signedMessage.Recipient = request.RequestUri; + signedMessage.HttpMethod = request.Method; } return message; @@ -167,8 +171,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <returns> /// The deserialized message parts, if found. Null otherwise. /// </returns> - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { - string body = response.GetResponseReader().ReadToEnd(); + protected override async Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken) { + string body = await response.Content.ReadAsStringAsync(); return HttpUtility.ParseQueryString(body).ToDictionary(); } @@ -179,8 +183,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <returns> /// The <see cref="HttpRequest"/> prepared to send the request. /// </returns> - protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { - HttpWebRequest httpRequest; + protected override HttpRequestMessage CreateHttpRequest(IDirectedProtocolMessage request) { + HttpRequestMessage httpRequest; HttpDeliveryMethods transmissionMethod = request.HttpMethods; if ((transmissionMethod & HttpDeliveryMethods.AuthorizationHeaderRequest) != 0) { @@ -200,6 +204,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { } else { throw new NotSupportedException(); } + return httpRequest; } @@ -212,16 +217,12 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <remarks> /// This method implements spec V1.0 section 5.3. /// </remarks> - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) { var messageAccessor = this.MessageDescriptions.GetAccessor(response); var fields = messageAccessor.Serialize(); - string responseBody = MessagingUtilities.CreateQueryString(fields); - OutgoingWebResponse encodedResponse = new OutgoingWebResponse { - Body = responseBody, - OriginalMessage = response, - Status = HttpStatusCode.OK, - Headers = new System.Net.WebHeaderCollection(), + var encodedResponse = new HttpResponseMessage { + Content = new FormUrlEncodedContent(fields), }; ApplyMessageTemplate(response, encodedResponse); @@ -256,7 +257,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// </summary> /// <param name="message">The message.</param> /// <returns>"POST", "GET" or some other similar http verb.</returns> - private static string GetHttpMethod(IDirectedProtocolMessage message) { + private static HttpMethod GetHttpMethod(IDirectedProtocolMessage message) { Requires.NotNull(message, "message"); var signedMessage = message as ITamperResistantOAuthMessage; @@ -273,11 +274,9 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// <param name="requestMessage">The message to be transmitted to the ServiceProvider.</param> /// <returns>The web request ready to send.</returns> /// <remarks> - /// <para>If the message has non-empty ExtraData in it, the request stream is sent to - /// the server automatically. If it is empty, the request stream must be sent by the caller.</para> - /// <para>This method implements OAuth 1.0 section 5.2, item #1 (described in section 5.4).</para> + /// This method implements OAuth 1.0 section 5.2, item #1 (described in section 5.4). /// </remarks> - private HttpWebRequest InitializeRequestAsAuthHeader(IDirectedProtocolMessage requestMessage) { + private HttpRequestMessage InitializeRequestAsAuthHeader(IDirectedProtocolMessage requestMessage) { var dictionary = this.MessageDescriptions.GetAccessor(requestMessage); // copy so as to not modify original @@ -285,41 +284,38 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { foreach (string key in dictionary.DeclaredKeys) { fields.Add(key, dictionary[key]); } + if (this.Realm != null) { fields.Add("realm", this.Realm.AbsoluteUri); } - HttpWebRequest httpRequest; UriBuilder recipientBuilder = new UriBuilder(requestMessage.Recipient); bool hasEntity = HttpMethodHasEntity(GetHttpMethod(requestMessage)); if (!hasEntity) { MessagingUtilities.AppendQueryArgs(recipientBuilder, requestMessage.ExtraData); } - httpRequest = (HttpWebRequest)WebRequest.Create(recipientBuilder.Uri); + + var httpRequest = new HttpRequestMessage(GetHttpMethod(requestMessage), recipientBuilder.Uri); this.PrepareHttpWebRequest(httpRequest); - httpRequest.Method = GetHttpMethod(requestMessage); - httpRequest.Headers.Add(HttpRequestHeader.Authorization, MessagingUtilities.AssembleAuthorizationHeader(Protocol.AuthorizationHeaderScheme, fields)); + httpRequest.Headers.Authorization = new AuthenticationHeaderValue(Protocol.AuthorizationHeaderScheme, MessagingUtilities.AssembleAuthorizationHeader(fields)); if (hasEntity) { - // WARNING: We only set up the request stream for the caller if there is - // extra data. If there isn't any extra data, the caller must do this themselves. var requestMessageWithBinaryData = requestMessage as IMessageWithBinaryData; if (requestMessageWithBinaryData != null && requestMessageWithBinaryData.SendAsMultipart) { // Include the binary data in the multipart entity, and any standard text extra message data. // The standard declared message parts are included in the authorization header. - var multiPartFields = new List<MultipartPostPart>(requestMessageWithBinaryData.BinaryData); - multiPartFields.AddRange(requestMessage.ExtraData.Select(field => MultipartPostPart.CreateFormPart(field.Key, field.Value))); - this.SendParametersInEntityAsMultipart(httpRequest, multiPartFields); + var content = InitializeMultipartFormDataContent(requestMessageWithBinaryData); + httpRequest.Content = content; + + foreach (var extraData in requestMessage.ExtraData) { + content.Add(new StringContent(extraData.Value), extraData.Key); + } } else { ErrorUtilities.VerifyProtocol(requestMessageWithBinaryData == null || requestMessageWithBinaryData.BinaryData.Count == 0, MessagingStrings.BinaryDataRequiresMultipart); if (requestMessage.ExtraData.Count > 0) { - this.SendParametersInEntity(httpRequest, requestMessage.ExtraData); - } else { - // We'll assume the content length is zero since the caller may not have - // anything. They're responsible to change it when the add the payload if they have one. - httpRequest.ContentLength = 0; + httpRequest.Content = new FormUrlEncodedContent(requestMessage.ExtraData); } } } diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs index 98eb9b3..29ef8d5 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/OAuthHttpMethodBindingElement.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; /// <summary> @@ -33,24 +35,25 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// True if the <paramref name="message"/> applied to this binding element /// and the operation was successful. False otherwise. /// </returns> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var oauthMessage = message as ITamperResistantOAuthMessage; if (oauthMessage != null) { HttpDeliveryMethods transmissionMethod = oauthMessage.HttpMethods; try { oauthMessage.HttpMethod = MessagingUtilities.GetHttpVerb(transmissionMethod); - return MessageProtections.None; + return MessageProtectionTasks.None; } catch (ArgumentException ex) { Logger.OAuth.Error("Unrecognized HttpDeliveryMethods value.", ex); - return null; + return MessageProtectionTasks.Null; } } else { - return null; + return MessageProtectionTasks.Null; } } @@ -59,6 +62,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// True if the <paramref name="message"/> applied to this binding element /// and the operation was successful. False if the operation did not apply to this message. @@ -67,8 +71,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Thrown when the binding element rules indicate that this message is invalid and should /// NOT be processed. /// </exception> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { - return null; + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { + return MessageProtectionTasks.Null; } #endregion diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs index 780afdc..357ca45 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementBase.cs @@ -12,6 +12,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using System.Globalization; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; @@ -79,11 +81,12 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Signs the outgoing message. /// </summary> /// <param name="message">The message to sign.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var signedMessage = message as ITamperResistantOAuthMessage; if (signedMessage != null && this.IsMessageApplicable(signedMessage)) { if (this.SignatureCallback != null) { @@ -95,29 +98,30 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { signedMessage.SignatureMethod = this.signatureMethod; Logger.Bindings.DebugFormat("Signing {0} message using {1}.", message.GetType().Name, this.signatureMethod); signedMessage.Signature = this.GetSignature(signedMessage); - return MessageProtections.TamperProtection; + return MessageProtectionTasks.TamperProtection; } - return null; + return MessageProtectionTasks.Null; } /// <summary> /// Verifies the signature on an incoming message. /// </summary> /// <param name="message">The message whose signature should be verified.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> /// <exception cref="InvalidSignatureException">Thrown if the signature is invalid.</exception> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var signedMessage = message as ITamperResistantOAuthMessage; if (signedMessage != null && this.IsMessageApplicable(signedMessage)) { Logger.Bindings.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature); if (!string.Equals(signedMessage.SignatureMethod, this.signatureMethod, StringComparison.Ordinal)) { Logger.Bindings.WarnFormat("Expected signature method '{0}' but received message with a signature method of '{1}'.", this.signatureMethod, signedMessage.SignatureMethod); - return MessageProtections.None; + return MessageProtectionTasks.None; } if (this.SignatureCallback != null) { @@ -131,10 +135,10 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { throw new InvalidSignatureException(message); } - return MessageProtections.TamperProtection; + return MessageProtectionTasks.TamperProtection; } - return null; + return MessageProtectionTasks.Null; } #endregion @@ -151,13 +155,13 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Unavoidable")] internal static string ConstructSignatureBaseString(ITamperResistantOAuthMessage message, MessageDictionary messageDictionary) { Requires.NotNull(message, "message"); - Requires.NotNullOrEmpty(message.HttpMethod, "message.HttpMethod"); + Requires.NotNull(message.HttpMethod, "message.HttpMethod"); Requires.NotNull(messageDictionary, "messageDictionary"); ErrorUtilities.VerifyInternal(messageDictionary.Message == message, "Message references are not equal."); List<string> signatureBaseStringElements = new List<string>(3); - signatureBaseStringElements.Add(message.HttpMethod.ToUpperInvariant()); + signatureBaseStringElements.Add(message.HttpMethod.ToString().ToUpperInvariant()); // For multipart POST messages, only include the message parts that are NOT // in the POST entity (those parts that may appear in an OAuth authorization header). diff --git a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs index 2b25566..c37d239 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/ChannelElements/SigningBindingElementChain.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using Validation; @@ -86,14 +88,15 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public async Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { foreach (IChannelBindingElement signer in this.signers) { ErrorUtilities.VerifyInternal(signer.Channel != null, "A binding element's Channel property is unexpectedly null."); - MessageProtections? result = signer.ProcessOutgoingMessage(message); + MessageProtections? result = await signer.ProcessOutgoingMessageAsync(message, cancellationToken); if (result.HasValue) { return result; } @@ -107,14 +110,15 @@ namespace DotNetOpenAuth.OAuth.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public async Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { foreach (IChannelBindingElement signer in this.signers) { ErrorUtilities.VerifyInternal(signer.Channel != null, "A binding element's Channel property is unexpectedly null."); - MessageProtections? result = signer.ProcessIncomingMessage(message); + MessageProtections? result = await signer.ProcessIncomingMessageAsync(message, cancellationToken); if (result.HasValue) { return result; } diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AccessProtectedResourceRequest.cs index aeee649..9b698b9 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/Messages/AccessProtectedResourceRequest.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/AccessProtectedResourceRequest.cs @@ -8,6 +8,8 @@ namespace DotNetOpenAuth.OAuth.Messages { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Net.Http; + using DotNetOpenAuth.Messaging; /// <summary> @@ -18,7 +20,7 @@ namespace DotNetOpenAuth.OAuth.Messages { /// <summary> /// A store for the binary data that is carried in the message. /// </summary> - private List<MultipartPostPart> binaryData = new List<MultipartPostPart>(); + private List<MultipartContentMember> binaryData = new List<MultipartContentMember>(); /// <summary> /// Initializes a new instance of the <see cref="AccessProtectedResourceRequest"/> class. @@ -56,7 +58,7 @@ namespace DotNetOpenAuth.OAuth.Messages { /// Gets the parts of the message that carry binary data. /// </summary> /// <value>A list of parts. Never null.</value> - public IList<MultipartPostPart> BinaryData { + public IList<MultipartContentMember> BinaryData { get { return this.binaryData; } } @@ -64,7 +66,7 @@ namespace DotNetOpenAuth.OAuth.Messages { /// Gets a value indicating whether this message should be sent as multi-part POST. /// </summary> public bool SendAsMultipart { - get { return this.HttpMethod == "POST" && this.BinaryData.Count > 0; } + get { return this.HttpMethod == HttpMethod.Post && this.BinaryData.Count > 0; } } #endregion diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBaseSimple.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBaseSimple.cs new file mode 100644 index 0000000..23822d3 --- /dev/null +++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/MessageBaseSimple.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DotNetOpenAuth.OAuth.Messages { + class MessageBaseSimple { + } +} diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Messages/SignedMessageBase.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/SignedMessageBase.cs index 6af75ec..7bc5b7d 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/Messages/SignedMessageBase.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/SignedMessageBase.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.OAuth.Messages { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; + using System.Net.Http; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth.ChannelElements; @@ -75,7 +76,7 @@ namespace DotNetOpenAuth.OAuth.Messages { /// <summary> /// Gets or sets the HTTP method that will be used to transmit the message. /// </summary> - string ITamperResistantOAuthMessage.HttpMethod { + HttpMethod ITamperResistantOAuthMessage.HttpMethod { get { return this.HttpMethod; } set { this.HttpMethod = value; } } @@ -169,7 +170,7 @@ namespace DotNetOpenAuth.OAuth.Messages { /// <summary> /// Gets or sets the HTTP method that will be used to transmit the message. /// </summary> - protected string HttpMethod { get; set; } + protected HttpMethod HttpMethod { get; set; } /// <summary> /// Gets or sets the message signature. diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationRequest.cs b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationRequest.cs index 4f98622..fd634da 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationRequest.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/Messages/UserAuthorizationRequest.cs @@ -62,7 +62,7 @@ namespace DotNetOpenAuth.OAuth.Messages { } /// <summary> - /// Gets or sets the Request Token obtained in the previous step. + /// Gets the Request Token obtained in the previous step. /// </summary> /// <remarks> /// The Service Provider MAY declare this parameter as REQUIRED, or @@ -70,7 +70,7 @@ namespace DotNetOpenAuth.OAuth.Messages { /// case it will prompt the User to enter it manually. /// </remarks> [MessagePart("oauth_token", IsRequired = false)] - internal string RequestToken { get; set; } + public string RequestToken { get; internal set; } /// <summary> /// Gets or sets a URL the Service Provider will use to redirect the User back diff --git a/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs b/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs index 72f0ff4..049fd58 100644 --- a/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs +++ b/src/DotNetOpenAuth.OAuth/OAuth/Protocol.cs @@ -60,6 +60,31 @@ namespace DotNetOpenAuth.OAuth { internal const string AuthorizationHeaderScheme = "OAuth"; /// <summary> + /// The name of the 'oauth_callback' parameter. + /// </summary> + internal const string CallbackParameter = "oauth_callback"; + + /// <summary> + /// The name of the 'oauth_callback_confirmed' parameter. + /// </summary> + internal const string CallbackConfirmedParameter = "oauth_callback_confirmed"; + + /// <summary> + /// The name of the 'oauth_token' parameter. + /// </summary> + internal const string TokenParameter = "oauth_token"; + + /// <summary> + /// The name of the 'oauth_token_secret' parameter. + /// </summary> + internal const string TokenSecretParameter = "oauth_token_secret"; + + /// <summary> + /// The name of the 'oauth_verifier' parameter. + /// </summary> + internal const string VerifierParameter = "oauth_verifier"; + + /// <summary> /// Gets the <see cref="Protocol"/> instance with values initialized for V1.0 of the protocol. /// </summary> internal static readonly Protocol V10 = new Protocol { diff --git a/src/DotNetOpenAuth.OAuth/packages.config b/src/DotNetOpenAuth.OAuth/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth/packages.config +++ b/src/DotNetOpenAuth.OAuth/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj index 18c488d..763d866 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/DotNetOpenAuth.OAuth2.AuthorizationServer.csproj @@ -74,9 +74,9 @@ <ItemGroup> <Reference Include="System.Net.Http" /> <Reference Include="System.Net.Http.WebRequest" /> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs index a5f7d9b..e7edb66 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServer.cs @@ -12,6 +12,8 @@ namespace DotNetOpenAuth.OAuth2 { using System.Net.Http; using System.Security.Cryptography; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; @@ -46,7 +48,7 @@ namespace DotNetOpenAuth.OAuth2 { Requires.NotNull(authorizationServer, "authorizationServer"); this.aggregatingClientAuthenticationModule = new AggregatingClientCredentialReader(this.clientAuthenticationModules); this.Channel = new OAuth2AuthorizationServerChannel(authorizationServer, this.aggregatingClientAuthenticationModule); - this.clientAuthenticationModules.AddRange(OAuth2AuthorizationServerSection.Configuration.ClientAuthenticationModules.CreateInstances(true)); + this.clientAuthenticationModules.AddRange(OAuth2AuthorizationServerSection.Configuration.ClientAuthenticationModules.CreateInstances(true, null)); this.ScopeSatisfiedCheck = DefaultScopeSatisfiedCheck; } @@ -84,16 +86,17 @@ namespace DotNetOpenAuth.OAuth2 { /// the user to authorize the Client's access of some protected resource(s). /// </summary> /// <param name="request">The HTTP request to read from.</param> - /// <returns>The incoming request, or null if no OAuth message was attached.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "unauthorizedclient", Justification = "Protocol required.")] - public EndUserAuthorizationRequest ReadAuthorizationRequest(HttpRequestBase request = null) { - if (request == null) { - request = this.Channel.GetRequestFromContext(); - } + public async Task<EndUserAuthorizationRequest> ReadAuthorizationRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); - EndUserAuthorizationRequest message; - if (this.Channel.TryReadFromRequest(request, out message)) { + var message = await this.Channel.TryReadFromRequestAsync<EndUserAuthorizationRequest>(request, cancellationToken); + if (message != null) { if (message.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode) { // Clients with no secrets can only request implicit grant types. var client = this.AuthorizationServerServices.GetClientOrThrow(message.ClientIdentifier); @@ -105,38 +108,34 @@ namespace DotNetOpenAuth.OAuth2 { } /// <summary> - /// Approves an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client. - /// </summary> - /// <param name="authorizationRequest">The authorization request to approve.</param> - /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param> - /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param> - /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> - public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) { - Requires.NotNull(authorizationRequest, "authorizationRequest"); - - var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, scopes, callback); - this.Channel.Respond(response); - } - - /// <summary> - /// Rejects an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client. + /// Reads in a client's request for the Authorization Server to obtain permission from + /// the user to authorize the Client's access of some protected resource(s). /// </summary> - /// <param name="authorizationRequest">The authorization request to disapprove.</param> - /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param> - public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) { - Requires.NotNull(authorizationRequest, "authorizationRequest"); - - var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback); - this.Channel.Respond(response); + /// <param name="request">The HTTP request to read from.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public Task<EndUserAuthorizationRequest> ReadAuthorizationRequestAsync( + HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.Channel.GetRequestFromContext(); + return this.ReadAuthorizationRequestAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> - /// Handles an incoming request to the authorization server's token endpoint. + /// Reads in a client's request for the Authorization Server to obtain permission from + /// the user to authorize the Client's access of some protected resource(s). /// </summary> - /// <param name="request">The HTTP request.</param> - /// <returns>The HTTP response to send to the client.</returns> - public OutgoingWebResponse HandleTokenRequest(HttpRequestMessage request) { - return this.HandleTokenRequest(new HttpRequestInfo(request)); + /// <param name="requestUri">The URL that carries the authorization request.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The incoming request, or null if no OAuth message was attached. + /// </returns> + /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception> + public Task<EndUserAuthorizationRequest> ReadAuthorizationRequestAsync(Uri requestUri, CancellationToken cancellationToken = default(CancellationToken)) { + var request = new HttpRequestMessage(HttpMethod.Get, requestUri); + return this.ReadAuthorizationRequestAsync(request, cancellationToken); } /// <summary> @@ -144,15 +143,13 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="request">The HTTP request.</param> /// <returns>The HTTP response to send to the client.</returns> - public OutgoingWebResponse HandleTokenRequest(HttpRequestBase request = null) { - if (request == null) { - request = this.Channel.GetRequestFromContext(); - } + public async Task<HttpResponseMessage> HandleTokenRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); - AccessTokenRequestBase requestMessage; IProtocolMessage responseMessage; try { - if (this.Channel.TryReadFromRequest(request, out requestMessage)) { + AccessTokenRequestBase requestMessage = await this.Channel.TryReadFromRequestAsync<AccessTokenRequestBase>(request, cancellationToken); + if (requestMessage != null) { var accessTokenResult = this.AuthorizationServerServices.CreateAccessToken(requestMessage); ErrorUtilities.VerifyHost(accessTokenResult != null, "IAuthorizationServerHost.CreateAccessToken must not return null."); @@ -179,7 +176,20 @@ namespace DotNetOpenAuth.OAuth2 { responseMessage = new AccessTokenFailedResponse() { Error = Protocol.AccessTokenRequestErrorCodes.InvalidRequest }; } - return this.Channel.PrepareResponse(responseMessage); + return await this.Channel.PrepareResponseAsync(responseMessage, cancellationToken); + } + + /// <summary> + /// Handles an incoming request to the authorization server's token endpoint. + /// </summary> + /// <param name="request">The HTTP request.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The HTTP response to send to the client. + /// </returns> + public Task<HttpResponseMessage> HandleTokenRequestAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.Channel.GetRequestFromContext(); + return this.HandleTokenRequestAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServerAccessToken.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServerAccessToken.cs index 7c9f808..cbf4b09 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServerAccessToken.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/AuthorizationServerAccessToken.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.OAuth2 { using System.Security.Cryptography; using System.Text; using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth2.ChannelElements; /// <summary> @@ -40,12 +41,23 @@ namespace DotNetOpenAuth.OAuth2 { public RSACryptoServiceProvider ResourceServerEncryptionKey { get; set; } /// <summary> + /// Gets or sets the symmetric key store to use if the asymmetric key properties are not set. + /// </summary> + public ICryptoKeyStore SymmetricKeyStore { get; set; } + + /// <summary> /// Serializes this instance to a simple string for transmission to the client. /// </summary> /// <returns>A non-empty string.</returns> protected internal override string Serialize() { - ErrorUtilities.VerifyHost(this.AccessTokenSigningKey != null, AuthServerStrings.AccessTokenSigningKeyMissing); - var formatter = CreateFormatter(this.AccessTokenSigningKey, this.ResourceServerEncryptionKey); + ErrorUtilities.VerifyHost(this.AccessTokenSigningKey != null || this.SymmetricKeyStore != null, AuthServerStrings.AccessTokenSigningKeyMissing); + IDataBagFormatter<AccessToken> formatter; + if (this.AccessTokenSigningKey != null) { + formatter = CreateFormatter(this.AccessTokenSigningKey, this.ResourceServerEncryptionKey); + } else { + formatter = CreateFormatter(this.SymmetricKeyStore); + } + return formatter.Serialize(this); } } diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/AuthServerBindingElementBase.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/AuthServerBindingElementBase.cs index 9d3a52c..f77ca91 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/AuthServerBindingElementBase.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/AuthServerBindingElementBase.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using Messaging; /// <summary> @@ -56,21 +58,23 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> /// <remarks> /// Implementations that provide message protection must honor the - /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// <see cref="MessagePartAttribute.RequiredProtection" /> properties where applicable. /// </remarks> - public abstract MessageProtections? ProcessOutgoingMessage(IProtocolMessage message); + public abstract Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken); /// <summary> /// Performs any transformation on an incoming message that may be necessary and/or /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -83,6 +87,6 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public abstract MessageProtections? ProcessIncomingMessage(IProtocolMessage message); + public abstract Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken); } } diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/MessageValidationBindingElement.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/MessageValidationBindingElement.cs index 6d4220b..823baaf 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/MessageValidationBindingElement.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/MessageValidationBindingElement.cs @@ -10,6 +10,8 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { using System.Globalization; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.OAuth2.Messages; using Messaging; using Validation; @@ -52,6 +54,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -60,7 +63,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public override Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var accessTokenResponse = message as AccessTokenSuccessResponse; if (accessTokenResponse != null) { var directResponseMessage = (IDirectResponseProtocolMessage)accessTokenResponse; @@ -68,7 +71,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { ErrorUtilities.VerifyProtocol(accessTokenRequest.GrantType != GrantType.ClientCredentials || accessTokenResponse.RefreshToken == null, OAuthStrings.NoGrantNoRefreshToken); } - return null; + return MessageProtectionTasks.Null; } /// <summary> @@ -76,19 +79,19 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - /// <exception cref="ProtocolException"> - /// Thrown when the binding element rules indicate that this message is invalid and should - /// NOT be processed. - /// </exception> + /// <exception cref="TokenEndpointProtocolException">Thrown when an authorization or protocol rule is violated.</exception> + /// <exception cref="ProtocolException">Thrown when the binding element rules indicate that this message is invalid and should + /// NOT be processed.</exception> /// <remarks> /// Implementations that provide message protection must honor the - /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. + /// <see cref="MessagePartAttribute.RequiredProtection" /> properties where applicable. /// </remarks> - public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public override Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { bool applied = false; // Check that the client secret is correct for client authenticated messages. @@ -201,7 +204,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { } } - return applied ? (MessageProtections?)MessageProtections.None : null; + return applied ? MessageProtectionTasks.None : MessageProtectionTasks.Null; } } } diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs index 249f5e7..609cedb 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs @@ -7,7 +7,12 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { using System; using System.Collections.Generic; + using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; + using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2.AuthServer.Messages; @@ -61,7 +66,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// The deserialized message parts, if found. Null otherwise. /// </returns> /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + protected override Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken) { throw new NotImplementedException(); } @@ -75,11 +80,11 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <remarks> /// This method implements spec OAuth V1.0 section 5.3. /// </remarks> - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { - var webResponse = new OutgoingWebResponse(); + protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) { + var webResponse = new HttpResponseMessage(); ApplyMessageTemplate(response, webResponse); string json = this.SerializeAsJson(response); - webResponse.SetResponse(json, new ContentType(JsonEncoded)); + webResponse.Content = new StringContent(json, Encoding.UTF8, JsonEncoded); return webResponse; } @@ -87,12 +92,15 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The deserialized message, if one is found. Null otherwise. /// </returns> - protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { - if (!string.IsNullOrEmpty(request.Url.Fragment)) { - var fields = HttpUtility.ParseQueryString(request.Url.Fragment.Substring(1)).ToDictionary(); + protected override async Task<IDirectedProtocolMessage> ReadFromRequestCoreAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + Requires.NotNull(request, "request"); + + if (!string.IsNullOrEmpty(request.RequestUri.Fragment)) { + var fields = HttpUtility.ParseQueryString(request.RequestUri.Fragment.Substring(1)).ToDictionary(); MessageReceivingEndpoint recipient; try { @@ -105,7 +113,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { return (IDirectedProtocolMessage)this.Receive(fields, recipient); } - return base.ReadFromRequestCore(request); + return await base.ReadFromRequestCoreAsync(request, cancellationToken); } /// <summary> diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/TokenCodeSerializationBindingElement.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/TokenCodeSerializationBindingElement.cs index 5a1dbae..938e587 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/TokenCodeSerializationBindingElement.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ChannelElements/TokenCodeSerializationBindingElement.cs @@ -12,6 +12,8 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { using System.Linq; using System.Security.Cryptography; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth2.AuthServer.ChannelElements; @@ -37,6 +39,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -45,7 +48,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public override Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var directResponse = message as IDirectResponseProtocolMessage; var request = directResponse != null ? directResponse.OriginatingRequest as IAccessTokenRequestInternal : null; @@ -55,7 +58,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { var codeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer); var code = authCodeCarrier.AuthorizationDescription; authCodeCarrier.Code = codeFormatter.Serialize(code); - return MessageProtections.None; + return MessageProtectionTasks.None; } // Serialize the refresh token, if applicable. @@ -74,7 +77,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { accessTokenResponse.AccessToken = accessTokenResponse.AuthorizationDescription.Serialize(); } - return null; + return MessageProtectionTasks.Null; } /// <summary> @@ -82,6 +85,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -98,7 +102,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "incorrectclientcredentials", Justification = "Protocol requirement")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "authorizationexpired", Justification = "Protocol requirement")] [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "DotNetOpenAuth.Messaging.ErrorUtilities.VerifyProtocol(System.Boolean,System.String,System.Object[])", Justification = "Protocol requirement")] - public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public override Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var authCodeCarrier = message as IAuthorizationCodeCarryingRequest; if (authCodeCarrier != null) { var authorizationCodeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer); @@ -115,7 +119,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { refreshTokenCarrier.AuthorizationDescription = refreshToken; } - return null; + return MessageProtectionTasks.Null; } } } diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ClientDescription.cs b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ClientDescription.cs index a10e1aa..6d77f14 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ClientDescription.cs +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/OAuth2/ClientDescription.cs @@ -22,15 +22,36 @@ namespace DotNetOpenAuth.OAuth2 { private readonly string secret; /// <summary> - /// Initializes a new instance of the <see cref="ClientDescription"/> class. + /// Initializes a new instance of the <see cref="ClientDescription"/> class + /// to represent a confidential client (one that has an authenticating secret.) /// </summary> /// <param name="secret">The secret.</param> /// <param name="defaultCallback">The default callback.</param> - /// <param name="clientType">Type of the client.</param> - public ClientDescription(string secret, Uri defaultCallback, ClientType clientType) { + public ClientDescription(string secret, Uri defaultCallback) { + Requires.NotNullOrEmpty(secret, "secret"); + Requires.NotNull(defaultCallback, "defaultCallback"); + this.secret = secret; this.DefaultCallback = defaultCallback; - this.ClientType = clientType; + this.ClientType = ClientType.Confidential; + } + + /// <summary> + /// Initializes a new instance of the <see cref="ClientDescription"/> class + /// to represent a public client (one that does not have an authenticating secret.) + /// </summary> + /// <param name="defaultCallback">The default callback.</param> + public ClientDescription(Uri defaultCallback) { + Requires.NotNull(defaultCallback, "defaultCallback"); + + this.DefaultCallback = defaultCallback; + this.ClientType = ClientType.Public; + } + + /// <summary> + /// Initializes a new instance of the <see cref="ClientDescription"/> class. + /// </summary> + protected ClientDescription() { } #region IClientDescription Members @@ -42,12 +63,12 @@ namespace DotNetOpenAuth.OAuth2 { /// <value> /// An absolute URL; or <c>null</c> if none is registered. /// </value> - public Uri DefaultCallback { get; private set; } + public Uri DefaultCallback { get; protected set; } /// <summary> /// Gets the type of the client. /// </summary> - public ClientType ClientType { get; private set; } + public ClientType ClientType { get; protected set; } /// <summary> /// Gets a value indicating whether a non-empty secret is registered for this client. diff --git a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/packages.config b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/packages.config index 1d93cf5..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth2.AuthorizationServer/packages.config +++ b/src/DotNetOpenAuth.OAuth2.AuthorizationServer/packages.config @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj b/src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj index ef48970..71b3f74 100644 --- a/src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj +++ b/src/DotNetOpenAuth.OAuth2.Client.UI/DotNetOpenAuth.OAuth2.Client.UI.csproj @@ -48,9 +48,9 @@ </EmbeddedResource> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs index 2c90c99..8f1c5f6 100644 --- a/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs +++ b/src/DotNetOpenAuth.OAuth2.Client.UI/OAuth2/ClientAuthorizationView.cs @@ -13,6 +13,8 @@ namespace DotNetOpenAuth.OAuth2 { using System.Drawing; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Windows.Forms; using DotNetOpenAuth.Messaging; @@ -93,6 +95,14 @@ namespace DotNetOpenAuth.OAuth2 { } /// <summary> + /// Gets or sets a value indicating whether the implicit grant type should be used instead of the authorization code grant. + /// </summary> + /// <value> + /// <c>true</c> if [request implicit grant]; otherwise, <c>false</c>. + /// </value> + public bool RequestImplicitGrant { get; set; } + + /// <summary> /// Called when the authorization flow has been completed. /// </summary> protected virtual void OnCompleted() { @@ -108,10 +118,10 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Avoid bug in .NET WebBrowser control.")] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "It's a new instance we control.")] - protected override void OnLoad(EventArgs e) { + protected override async void OnLoad(EventArgs e) { base.OnLoad(e); - Uri authorizationUrl = this.Client.RequestUserAuthorization(this.Authorization); + Uri authorizationUrl = await this.Client.RequestUserAuthorizationAsync(this.Authorization, implicitResponseType: this.RequestImplicitGrant); this.webBrowser1.Navigate(authorizationUrl.AbsoluteUri); // use AbsoluteUri to workaround bug in WebBrowser that calls Uri.ToString instead of Uri.AbsoluteUri leading to escaping errors. } @@ -133,18 +143,21 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatingEventArgs"/> instance containing the event data.</param> - private void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { - this.ProcessLocationChanged(e.Url); + private async void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) { + await this.ProcessLocationChangedAsync(e.Url); } /// <summary> /// Processes changes in the URL the browser has navigated to. /// </summary> /// <param name="location">The location.</param> - private void ProcessLocationChanged(Uri location) { + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + private async Task ProcessLocationChangedAsync(Uri location) { if (SignificantlyEqual(location, this.Authorization.Callback, UriComponents.SchemeAndServer | UriComponents.Path)) { try { - this.Client.ProcessUserAuthorization(location, this.Authorization); + await this.Client.ProcessUserAuthorizationAsync(location, this.Authorization); } catch (ProtocolException ex) { var options = (MessageBoxOptions)0; if (this.RightToLeft == System.Windows.Forms.RightToLeft.Yes) { @@ -162,8 +175,8 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatedEventArgs"/> instance containing the event data.</param> - private void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { - this.ProcessLocationChanged(e.Url); + private async void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { + await this.ProcessLocationChangedAsync(e.Url); } /// <summary> @@ -171,8 +184,8 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> - private void WebBrowser1_LocationChanged(object sender, EventArgs e) { - this.ProcessLocationChanged(this.webBrowser1.Url); + private async void WebBrowser1_LocationChanged(object sender, EventArgs e) { + await this.ProcessLocationChangedAsync(this.webBrowser1.Url); } } } diff --git a/src/DotNetOpenAuth.OAuth2.Client.UI/packages.config b/src/DotNetOpenAuth.OAuth2.Client.UI/packages.config index 58890d8..e3309bc 100644 --- a/src/DotNetOpenAuth.OAuth2.Client.UI/packages.config +++ b/src/DotNetOpenAuth.OAuth2.Client.UI/packages.config @@ -1,4 +1,4 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj b/src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj index 49596bb..f20f681 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj +++ b/src/DotNetOpenAuth.OAuth2.Client/DotNetOpenAuth.OAuth2.Client.csproj @@ -64,10 +64,11 @@ </ItemGroup> <ItemGroup> <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> <Reference Include="System.Net.Http.WebRequest" /> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/BearerTokenHttpMessageHandler.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/BearerTokenHttpMessageHandler.cs index da4c869..92f882f 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/BearerTokenHttpMessageHandler.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/BearerTokenHttpMessageHandler.cs @@ -72,21 +72,21 @@ namespace DotNetOpenAuth.OAuth2 { /// <returns> /// Returns <see cref="T:System.Threading.Tasks.Task`1" />. The task object representing the asynchronous operation. /// </returns> - protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { string bearerToken = this.BearerToken; if (bearerToken == null) { - ErrorUtilities.VerifyProtocol(!this.Authorization.AccessTokenExpirationUtc.HasValue || this.Authorization.AccessTokenExpirationUtc < DateTime.UtcNow || this.Authorization.RefreshToken != null, ClientStrings.AuthorizationExpired); + ErrorUtilities.VerifyProtocol(!this.Authorization.AccessTokenExpirationUtc.HasValue || this.Authorization.AccessTokenExpirationUtc >= DateTime.UtcNow || this.Authorization.RefreshToken != null, ClientStrings.AuthorizationExpired); if (this.Authorization.AccessTokenExpirationUtc.HasValue && this.Authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) { ErrorUtilities.VerifyProtocol(this.Authorization.RefreshToken != null, ClientStrings.AccessTokenRefreshFailed); - this.Client.RefreshAuthorization(this.Authorization); + await this.Client.RefreshAuthorizationAsync(this.Authorization, cancellationToken: cancellationToken); } bearerToken = this.Authorization.AccessToken; } request.Headers.Authorization = new AuthenticationHeaderValue(Protocol.BearerHttpAuthorizationScheme, bearerToken); - return base.SendAsync(request, cancellationToken); + return await base.SendAsync(request, cancellationToken); } } } diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ChannelElements/OAuth2ClientChannel.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ChannelElements/OAuth2ClientChannel.cs index cf57618..aba0290 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ChannelElements/OAuth2ClientChannel.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ChannelElements/OAuth2ClientChannel.cs @@ -9,12 +9,16 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { using System.Collections.Generic; using System.Collections.Specialized; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Xml; - using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2.Messages; + using Validation; + /// <summary> /// The messaging channel used by OAuth 2.0 Clients. /// </summary> @@ -32,10 +36,11 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { }; /// <summary> - /// Initializes a new instance of the <see cref="OAuth2ClientChannel"/> class. + /// Initializes a new instance of the <see cref="OAuth2ClientChannel" /> class. /// </summary> - internal OAuth2ClientChannel() - : base(MessageTypes) { + /// <param name="hostFactories">The host factories.</param> + internal OAuth2ClientChannel(IHostFactories hostFactories) + : base(MessageTypes, hostFactories: hostFactories) { } /// <summary> @@ -64,11 +69,11 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// The <see cref="HttpWebRequest"/> prepared to send the request. /// </returns> /// <remarks> - /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method + /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCoreAsync"/> method /// is overridden and does not require this method. /// </remarks> - protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { - HttpWebRequest httpRequest; + protected override HttpRequestMessage CreateHttpRequest(IDirectedProtocolMessage request) { + HttpRequestMessage httpRequest; if ((request.HttpMethods & HttpDeliveryMethods.GetRequest) != 0) { httpRequest = InitializeRequestAsGet(request); } else if ((request.HttpMethods & HttpDeliveryMethods.PostRequest) != 0) { @@ -88,16 +93,17 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// The deserialized message parts, if found. Null otherwise. /// </returns> /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + protected override async Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken) { // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain // Others return text/javascript. Again bad. - string body = response.GetResponseReader().ReadToEnd(); - if (response.ContentType.MediaType == JsonEncoded || response.ContentType.MediaType == JsonTextEncoded) { + string body = await response.Content.ReadAsStringAsync(); + var contentType = response.Content.Headers.ContentType.MediaType; + if (contentType == JsonEncoded || contentType == JsonTextEncoded) { return this.DeserializeFromJson(body); - } else if (response.ContentType.MediaType == HttpFormUrlEncoded || response.ContentType.MediaType == PlainTextEncoded) { + } else if (contentType == HttpFormUrlEncoded || contentType == PlainTextEncoded) { return HttpUtility.ParseQueryString(body).ToDictionary(); } else { - throw ErrorUtilities.ThrowProtocol(ClientStrings.UnexpectedResponseContentType, response.ContentType.MediaType); + throw ErrorUtilities.ThrowProtocol(ClientStrings.UnexpectedResponseContentType, contentType); } } @@ -105,21 +111,24 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The deserialized message, if one is found. Null otherwise. /// </returns> - protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { - Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.GetPublicFacingUrl().AbsoluteUri); + protected override async Task<IDirectedProtocolMessage> ReadFromRequestCoreAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + Requires.NotNull(request, "request"); + + Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.Method, request.RequestUri.AbsoluteUri); - var fields = request.GetQueryStringBeforeRewriting().ToDictionary(); + var fields = HttpUtility.ParseQueryString(request.RequestUri.Query).ToDictionary(); // Also read parameters from the fragment, if it's available. // Typically the fragment is not available because the browser doesn't send it to a web server // but this request may have been fabricated by an installed desktop app, in which case // the fragment is available. - string fragment = request.GetPublicFacingUrl().Fragment; + string fragment = request.RequestUri.Fragment; if (!string.IsNullOrEmpty(fragment)) { - foreach (var pair in HttpUtility.ParseQueryString(fragment.Substring(1)).ToDictionary()) { + foreach (var pair in HttpUtility.ParseQueryString(fragment.Substring(1)).AsKeyValuePairs()) { fields.Add(pair.Key, pair.Value); } } @@ -146,7 +155,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <remarks> /// This method implements spec OAuth V1.0 section 5.3. /// </remarks> - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) { // Clients don't ever send direct responses. throw new NotImplementedException(); } @@ -155,7 +164,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Performs additional processing on an outgoing web request before it is sent to the remote server. /// </summary> /// <param name="request">The request.</param> - protected override void PrepareHttpWebRequest(HttpWebRequest request) { + protected override void PrepareHttpWebRequest(HttpRequestMessage request) { base.PrepareHttpWebRequest(request); if (this.ClientCredentialApplicator != null) { diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs index d66f4fd..9730321 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientBase.cs @@ -13,8 +13,9 @@ namespace DotNetOpenAuth.OAuth2 { using System.Net.Http; using System.Security; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Xml; - using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2.ChannelElements; using DotNetOpenAuth.OAuth2.Messages; @@ -33,10 +34,10 @@ namespace DotNetOpenAuth.OAuth2 { /// The tool to use to apply client credentials to authenticated requests to the Authorization Server. /// May be <c>null</c> for clients with no secret or other means of authentication. /// </param> - protected ClientBase(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, ClientCredentialApplicator clientCredentialApplicator = null) { + protected ClientBase(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, ClientCredentialApplicator clientCredentialApplicator = null, IHostFactories hostFactories = null) { Requires.NotNull(authorizationServer, "authorizationServer"); this.AuthorizationServer = authorizationServer; - this.Channel = new OAuth2ClientChannel(); + this.Channel = new OAuth2ClientChannel(hostFactories); this.ClientIdentifier = clientIdentifier; this.ClientCredentialApplicator = clientCredentialApplicator; } @@ -116,11 +117,15 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="request">The request for protected resources from the service provider.</param> /// <param name="authorization">The authorization for this request previously obtained via OAuth.</param> - public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public Task AuthorizeRequestAsync(HttpWebRequest request, IAuthorizationState authorization, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); Requires.NotNull(authorization, "authorization"); - this.AuthorizeRequest(request.Headers, authorization); + return this.AuthorizeRequestAsync(request.Headers, authorization, cancellationToken); } /// <summary> @@ -129,7 +134,11 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="requestHeaders">The headers on the request for protected resources from the service provider.</param> /// <param name="authorization">The authorization for this request previously obtained via OAuth.</param> - public void AuthorizeRequest(WebHeaderCollection requestHeaders, IAuthorizationState authorization) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public async Task AuthorizeRequestAsync(WebHeaderCollection requestHeaders, IAuthorizationState authorization, CancellationToken cancellationToken) { Requires.NotNull(requestHeaders, "requestHeaders"); Requires.NotNull(authorization, "authorization"); Requires.That(!string.IsNullOrEmpty(authorization.AccessToken), "authorization", "AccessToken required."); @@ -137,7 +146,7 @@ namespace DotNetOpenAuth.OAuth2 { if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) { ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, ClientStrings.AccessTokenRefreshFailed); - this.RefreshAuthorization(authorization); + await this.RefreshAuthorizationAsync(authorization, cancellationToken: cancellationToken); } AuthorizeRequest(requestHeaders, authorization.AccessToken); @@ -174,13 +183,14 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="authorization">The authorization to update.</param> /// <param name="skipIfUsefulLifeExceeds">If given, the access token will <em>not</em> be refreshed if its remaining lifetime exceeds this value.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A value indicating whether the access token was actually renewed; <c>true</c> if it was renewed, or <c>false</c> if it still had useful life remaining.</returns> /// <remarks> /// This method may modify the value of the <see cref="IAuthorizationState.RefreshToken"/> property on /// the <paramref name="authorization"/> parameter if the authorization server has cycled out your refresh token. /// If the parameter value was updated, this method calls <see cref="IAuthorizationState.SaveChanges"/> on that instance. /// </remarks> - public bool RefreshAuthorization(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null) { + public async Task<bool> RefreshAuthorizationAsync(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(authorization, "authorization"); Requires.That(!string.IsNullOrEmpty(authorization.RefreshToken), "authorization", "RefreshToken required."); @@ -200,7 +210,7 @@ namespace DotNetOpenAuth.OAuth2 { this.ApplyClientCredential(request); - var response = this.Channel.Request<AccessTokenSuccessResponse>(request); + var response = await this.Channel.RequestAsync<AccessTokenSuccessResponse>(request, cancellationToken); UpdateAuthorizationWithResponse(authorization, response); return true; } @@ -211,12 +221,13 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="refreshToken">The refresh token.</param> /// <param name="scope">The scope subset desired in the access token.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A description of the obtained access token, and possibly a new refresh token.</returns> /// <remarks> /// If the return value includes a new refresh token, the old refresh token should be discarded and /// replaced with the new one. /// </remarks> - public IAuthorizationState GetScopedAccessToken(string refreshToken, HashSet<string> scope) { + public async Task<IAuthorizationState> GetScopedAccessTokenAsync(string refreshToken, HashSet<string> scope, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(refreshToken, "refreshToken"); Requires.NotNull(scope, "scope"); @@ -227,7 +238,7 @@ namespace DotNetOpenAuth.OAuth2 { this.ApplyClientCredential(request); - var response = this.Channel.Request<AccessTokenSuccessResponse>(request); + var response = await this.Channel.RequestAsync<AccessTokenSuccessResponse>(request, cancellationToken); var authorization = new AuthorizationState(); UpdateAuthorizationWithResponse(authorization, response); @@ -240,8 +251,11 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="userName">The resource owner's username, as it is known by the authorization server.</param> /// <param name="password">The resource owner's account password.</param> /// <param name="scopes">The desired scope of access.</param> - /// <returns>The result, containing the tokens if successful.</returns> - public IAuthorizationState ExchangeUserCredentialForToken(string userName, string password, IEnumerable<string> scopes = null) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The result, containing the tokens if successful. + /// </returns> + public Task<IAuthorizationState> ExchangeUserCredentialForTokenAsync(string userName, string password, IEnumerable<string> scopes = null, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNullOrEmpty(userName, "userName"); Requires.NotNull(password, "password"); @@ -250,17 +264,20 @@ namespace DotNetOpenAuth.OAuth2 { Password = password, }; - return this.RequestAccessToken(request, scopes); + return this.RequestAccessTokenAsync(request, scopes, cancellationToken); } /// <summary> /// Obtains an access token for accessing client-controlled resources on the resource server. /// </summary> /// <param name="scopes">The desired scopes.</param> - /// <returns>The result of the authorization request.</returns> - public IAuthorizationState GetClientAccessToken(IEnumerable<string> scopes = null) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The result of the authorization request. + /// </returns> + public Task<IAuthorizationState> GetClientAccessTokenAsync(IEnumerable<string> scopes = null, CancellationToken cancellationToken = default(CancellationToken)) { var request = new AccessTokenClientCredentialsRequest(this.AuthorizationServer.TokenEndpoint, this.AuthorizationServer.Version); - return this.RequestAccessToken(request, scopes); + return this.RequestAccessTokenAsync(request, scopes, cancellationToken); } /// <summary> @@ -322,7 +339,11 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="authorizationState">The authorization state to update.</param> /// <param name="authorizationSuccess">The authorization success message obtained from the authorization server.</param> - internal void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + internal async Task UpdateAuthorizationWithResponseAsync(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess, CancellationToken cancellationToken) { Requires.NotNull(authorizationState, "authorizationState"); Requires.NotNull(authorizationSuccess, "authorizationSuccess"); @@ -332,7 +353,7 @@ namespace DotNetOpenAuth.OAuth2 { AuthorizationCode = authorizationSuccess.AuthorizationCode, }; this.ApplyClientCredential(accessTokenRequest); - IProtocolMessage accessTokenResponse = this.Channel.Request(accessTokenRequest); + IProtocolMessage accessTokenResponse = await this.Channel.RequestAsync(accessTokenRequest, cancellationToken); var accessTokenSuccess = accessTokenResponse as AccessTokenSuccessResponse; var failedAccessTokenResponse = accessTokenResponse as AccessTokenFailedResponse; if (accessTokenSuccess != null) { @@ -387,8 +408,11 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="request">The request message.</param> /// <param name="scopes">The scopes requested by the client.</param> - /// <returns>The result of the request.</returns> - private IAuthorizationState RequestAccessToken(ScopedAccessTokenRequest request, IEnumerable<string> scopes = null) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The result of the request. + /// </returns> + private async Task<IAuthorizationState> RequestAccessTokenAsync(ScopedAccessTokenRequest request, IEnumerable<string> scopes, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); var authorizationState = new AuthorizationState(scopes); @@ -397,7 +421,7 @@ namespace DotNetOpenAuth.OAuth2 { this.ApplyClientCredential(request); request.Scope.UnionWith(authorizationState.Scope); - var response = this.Channel.Request(request); + var response = await this.Channel.RequestAsync(request, cancellationToken); var success = response as AccessTokenSuccessResponse; var failure = response as AccessTokenFailedResponse; ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany); diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientCredentialApplicator.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientCredentialApplicator.cs index 39ba1cb..769cf56 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientCredentialApplicator.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/ClientCredentialApplicator.cs @@ -9,6 +9,7 @@ namespace DotNetOpenAuth.OAuth2 { using System.Collections.Generic; using System.Linq; using System.Net; + using System.Net.Http; using System.Text; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2.Messages; @@ -75,7 +76,7 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="clientIdentifier">The identifier by which the authorization server should recognize this client.</param> /// <param name="request">The outbound message to apply authentication information to.</param> - public virtual void ApplyClientCredential(string clientIdentifier, HttpWebRequest request) { + public virtual void ApplyClientCredential(string clientIdentifier, HttpRequestMessage request) { } /// <summary> @@ -126,7 +127,7 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="clientIdentifier">The identifier by which the authorization server should recognize this client.</param> /// <param name="request">The outbound message to apply authentication information to.</param> - public override void ApplyClientCredential(string clientIdentifier, HttpWebRequest request) { + public override void ApplyClientCredential(string clientIdentifier, HttpRequestMessage request) { if (clientIdentifier != null) { if (this.credential != null) { ErrorUtilities.VerifyHost( diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs index dcb3826..7a52c0f 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/UserAgentClient.cs @@ -8,9 +8,11 @@ namespace DotNetOpenAuth.OAuth2 { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; - using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2.Messages; using Validation; @@ -26,8 +28,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="authorizationServer">The token issuer.</param> /// <param name="clientIdentifier">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> - public UserAgentClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) - : this(authorizationServer, clientIdentifier, DefaultSecretApplicator(clientSecret)) { + public UserAgentClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null, IHostFactories hostFactories = null) + : this(authorizationServer, clientIdentifier, DefaultSecretApplicator(clientSecret), hostFactories) { } /// <summary> @@ -37,8 +39,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="tokenEndpoint">The token endpoint.</param> /// <param name="clientIdentifier">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> - public UserAgentClient(Uri authorizationEndpoint, Uri tokenEndpoint, string clientIdentifier = null, string clientSecret = null) - : this(authorizationEndpoint, tokenEndpoint, clientIdentifier, DefaultSecretApplicator(clientSecret)) { + public UserAgentClient(Uri authorizationEndpoint, Uri tokenEndpoint, string clientIdentifier = null, string clientSecret = null, IHostFactories hostFactories = null) + : this(authorizationEndpoint, tokenEndpoint, clientIdentifier, DefaultSecretApplicator(clientSecret), hostFactories) { } /// <summary> @@ -51,8 +53,8 @@ namespace DotNetOpenAuth.OAuth2 { /// The tool to use to apply client credentials to authenticated requests to the Authorization Server. /// May be <c>null</c> for clients with no secret or other means of authentication. /// </param> - public UserAgentClient(Uri authorizationEndpoint, Uri tokenEndpoint, string clientIdentifier, ClientCredentialApplicator clientCredentialApplicator) - : this(new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint, TokenEndpoint = tokenEndpoint }, clientIdentifier, clientCredentialApplicator) { + public UserAgentClient(Uri authorizationEndpoint, Uri tokenEndpoint, string clientIdentifier, ClientCredentialApplicator clientCredentialApplicator, IHostFactories hostFactories = null) + : this(new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint, TokenEndpoint = tokenEndpoint }, clientIdentifier, clientCredentialApplicator, hostFactories) { Requires.NotNull(authorizationEndpoint, "authorizationEndpoint"); Requires.NotNull(tokenEndpoint, "tokenEndpoint"); } @@ -66,8 +68,8 @@ namespace DotNetOpenAuth.OAuth2 { /// The tool to use to apply client credentials to authenticated requests to the Authorization Server. /// May be <c>null</c> for clients with no secret or other means of authentication. /// </param> - public UserAgentClient(AuthorizationServerDescription authorizationServer, string clientIdentifier, ClientCredentialApplicator clientCredentialApplicator) - : base(authorizationServer, clientIdentifier, clientCredentialApplicator) { + public UserAgentClient(AuthorizationServerDescription authorizationServer, string clientIdentifier, ClientCredentialApplicator clientCredentialApplicator, IHostFactories hostFactories = null) + : base(authorizationServer, clientIdentifier, clientCredentialApplicator, hostFactories) { } /// <summary> @@ -77,15 +79,16 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="scope">The scope of authorized access requested.</param> /// <param name="state">The client state that should be returned with the authorization response.</param> /// <param name="returnTo">The URL that the authorization response should be sent to via a user-agent redirect.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A fully-qualified URL suitable to initiate the authorization flow. /// </returns> - public Uri RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) { + public Task<Uri> RequestUserAuthorizationAsync(IEnumerable<string> scope = null, string state = null, Uri returnTo = null, CancellationToken cancellationToken = default(CancellationToken)) { var authorization = new AuthorizationState(scope) { Callback = returnTo, }; - return this.RequestUserAuthorization(authorization, state: state); + return this.RequestUserAuthorizationAsync(authorization, state: state, cancellationToken: cancellationToken); } /// <summary> @@ -93,20 +96,20 @@ namespace DotNetOpenAuth.OAuth2 { /// this client to access protected data at some resource server. /// </summary> /// <param name="authorization">The authorization state that is tracking this particular request. Optional.</param> - /// <param name="implicitResponseType"> - /// <c>true</c> to request an access token in the fragment of the response's URL; - /// <c>false</c> to authenticate to the authorization server and acquire the access token (and possibly a refresh token) via a private channel. - /// </param> + /// <param name="implicitResponseType"><c>true</c> to request an access token in the fragment of the response's URL; + /// <c>false</c> to authenticate to the authorization server and acquire the access token (and possibly a refresh token) via a private channel.</param> /// <param name="state">The client state that should be returned with the authorization response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A fully-qualified URL suitable to initiate the authorization flow. /// </returns> - public Uri RequestUserAuthorization(IAuthorizationState authorization, bool implicitResponseType = false, string state = null) { + public async Task<Uri> RequestUserAuthorizationAsync(IAuthorizationState authorization, bool implicitResponseType = false, string state = null, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(authorization, "authorization"); RequiresEx.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier)); var request = this.PrepareRequestUserAuthorization(authorization, implicitResponseType, state); - return this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel); + var response = await this.Channel.PrepareResponseAsync(request, cancellationToken); + return response.GetDirectUriRequest(); } /// <summary> @@ -114,21 +117,24 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param> /// <param name="authorizationState">The authorization.</param> - /// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns> - public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected. + /// </returns> + public async Task<IAuthorizationState> ProcessUserAuthorizationAsync(Uri actualRedirectUrl, IAuthorizationState authorizationState = null, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(actualRedirectUrl, "actualRedirectUrl"); if (authorizationState == null) { authorizationState = new AuthorizationState(); } - var carrier = new HttpRequestInfo("GET", actualRedirectUrl); - IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier); + var carrier = new HttpRequestMessage(HttpMethod.Get, actualRedirectUrl); + IDirectedProtocolMessage response = await this.Channel.ReadFromRequestAsync(carrier, cancellationToken); if (response == null) { return null; } - return this.ProcessUserAuthorization(authorizationState, response); + return await this.ProcessUserAuthorizationAsync(authorizationState, response, cancellationToken); } /// <summary> @@ -136,10 +142,11 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="authorizationState">The authorization.</param> /// <param name="response">The incoming authorization response message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected. /// </returns> - internal IAuthorizationState ProcessUserAuthorization(IAuthorizationState authorizationState, IDirectedProtocolMessage response) { + internal async Task<IAuthorizationState> ProcessUserAuthorizationAsync(IAuthorizationState authorizationState, IDirectedProtocolMessage response, CancellationToken cancellationToken) { Requires.NotNull(authorizationState, "authorizationState"); Requires.NotNull(response, "response"); @@ -148,7 +155,7 @@ namespace DotNetOpenAuth.OAuth2 { if ((accessTokenSuccess = response as EndUserAuthorizationSuccessAccessTokenResponse) != null) { UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess); } else if ((authCodeSuccess = response as EndUserAuthorizationSuccessAuthCodeResponse) != null) { - this.UpdateAuthorizationWithResponse(authorizationState, authCodeSuccess); + await this.UpdateAuthorizationWithResponseAsync(authorizationState, authCodeSuccess, cancellationToken); } else if (response is EndUserAuthorizationFailedResponse) { authorizationState.Delete(); return null; diff --git a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs index 63d96e1..2b5a80a 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs +++ b/src/DotNetOpenAuth.OAuth2.Client/OAuth2/WebServerClient.cs @@ -10,10 +10,13 @@ namespace DotNetOpenAuth.OAuth2 { using System.Globalization; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Security; - using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2.Messages; @@ -29,26 +32,26 @@ namespace DotNetOpenAuth.OAuth2 { private const string XsrfCookieName = "DotNetOpenAuth.WebServerClient.XSRF-Session"; /// <summary> - /// Initializes a new instance of the <see cref="WebServerClient"/> class. + /// Initializes a new instance of the <see cref="WebServerClient" /> class. /// </summary> /// <param name="authorizationServer">The authorization server.</param> /// <param name="clientIdentifier">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> - public WebServerClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) - : this(authorizationServer, clientIdentifier, DefaultSecretApplicator(clientSecret)) { + /// <param name="hostFactories">The host factories.</param> + public WebServerClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null, IHostFactories hostFactories = null) + : this(authorizationServer, clientIdentifier, DefaultSecretApplicator(clientSecret), hostFactories) { } /// <summary> - /// Initializes a new instance of the <see cref="WebServerClient"/> class. + /// Initializes a new instance of the <see cref="WebServerClient" /> class. /// </summary> /// <param name="authorizationServer">The authorization server.</param> /// <param name="clientIdentifier">The client identifier.</param> - /// <param name="clientCredentialApplicator"> - /// The tool to use to apply client credentials to authenticated requests to the Authorization Server. - /// May be <c>null</c> for clients with no secret or other means of authentication. - /// </param> - public WebServerClient(AuthorizationServerDescription authorizationServer, string clientIdentifier, ClientCredentialApplicator clientCredentialApplicator) - : base(authorizationServer, clientIdentifier, clientCredentialApplicator) { + /// <param name="clientCredentialApplicator">The tool to use to apply client credentials to authenticated requests to the Authorization Server. + /// May be <c>null</c> for clients with no secret or other means of authentication.</param> + /// <param name="hostFactories"></param> + public WebServerClient(AuthorizationServerDescription authorizationServer, string clientIdentifier, ClientCredentialApplicator clientCredentialApplicator, IHostFactories hostFactories = null) + : base(authorizationServer, clientIdentifier, clientCredentialApplicator, hostFactories) { } /// <summary> @@ -60,34 +63,28 @@ namespace DotNetOpenAuth.OAuth2 { /// <summary> /// Prepares a request for user authorization from an authorization server. /// </summary> - /// <param name="scope">The scope of authorized access requested.</param> - /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed. If null, the current request's URL will be used.</param> - public void RequestUserAuthorization(IEnumerable<string> scope = null, Uri returnTo = null) { - var authorizationState = new AuthorizationState(scope) { - Callback = returnTo, - }; - this.PrepareRequestUserAuthorization(authorizationState).Send(); - } - - /// <summary> - /// Prepares a request for user authorization from an authorization server. - /// </summary> /// <param name="scopes">The scope of authorized access requested.</param> /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed. If null, the current request's URL will be used.</param> - /// <returns>The authorization request.</returns> - public OutgoingWebResponse PrepareRequestUserAuthorization(IEnumerable<string> scopes = null, Uri returnTo = null) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The authorization request. + /// </returns> + public Task<HttpResponseMessage> PrepareRequestUserAuthorizationAsync(IEnumerable<string> scopes = null, Uri returnTo = null, CancellationToken cancellationToken = default(CancellationToken)) { var authorizationState = new AuthorizationState(scopes) { Callback = returnTo, }; - return this.PrepareRequestUserAuthorization(authorizationState); + return this.PrepareRequestUserAuthorizationAsync(authorizationState, cancellationToken); } /// <summary> /// Prepares a request for user authorization from an authorization server. /// </summary> /// <param name="authorization">The authorization state to associate with this particular request.</param> - /// <returns>The authorization request.</returns> - public OutgoingWebResponse PrepareRequestUserAuthorization(IAuthorizationState authorization) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The authorization request. + /// </returns> + public async Task<HttpResponseMessage> PrepareRequestUserAuthorizationAsync(IAuthorizationState authorization, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(authorization, "authorization"); RequiresEx.ValidState(authorization.Callback != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired); RequiresEx.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier), Strings.RequiredPropertyNotYetPreset, "ClientIdentifier"); @@ -108,23 +105,18 @@ namespace DotNetOpenAuth.OAuth2 { // Mitigate XSRF attacks by including a state value that would be unpredictable between users, but // verifiable for the same user/session. // If the host is implementing the authorization tracker though, they're handling this protection themselves. - HttpCookie cookie = null; + var cookies = new List<CookieHeaderValue>(); if (this.AuthorizationTracker == null) { - var context = this.Channel.GetHttpContext(); - string xsrfKey = MessagingUtilities.GetNonCryptoRandomDataAsBase64(16); - cookie = new HttpCookie(XsrfCookieName, xsrfKey) { + cookies.Add(new CookieHeaderValue(XsrfCookieName, xsrfKey) { HttpOnly = true, Secure = FormsAuthentication.RequireSSL, - ////Expires = DateTime.Now.Add(OAuth2ClientSection.Configuration.MaxAuthorizationTime), // we prefer session cookies to persistent ones - }; + }); request.ClientState = xsrfKey; } - var response = this.Channel.PrepareResponse(request); - if (cookie != null) { - response.Cookies.Add(cookie); - } + var response = await this.Channel.PrepareResponseAsync(request, cancellationToken); + response.Headers.AddCookies(cookies); return response; } @@ -133,34 +125,45 @@ namespace DotNetOpenAuth.OAuth2 { /// Processes the authorization response from an authorization server, if available. /// </summary> /// <param name="request">The incoming HTTP request that may carry an authorization response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The authorization state that contains the details of the authorization.</returns> - public IAuthorizationState ProcessUserAuthorization(HttpRequestBase request = null) { + public Task<IAuthorizationState> ProcessUserAuthorizationAsync( + HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.Channel.GetRequestFromContext(); + return this.ProcessUserAuthorizationAsync(request.AsHttpRequestMessage(), cancellationToken); + } + + /// <summary> + /// Processes the authorization response from an authorization server, if available. + /// </summary> + /// <param name="request">The incoming HTTP request that may carry an authorization response.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The authorization state that contains the details of the authorization.</returns> + public async Task<IAuthorizationState> ProcessUserAuthorizationAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); RequiresEx.ValidState(!string.IsNullOrEmpty(this.ClientIdentifier), Strings.RequiredPropertyNotYetPreset, "ClientIdentifier"); RequiresEx.ValidState(this.ClientCredentialApplicator != null, Strings.RequiredPropertyNotYetPreset, "ClientCredentialApplicator"); - if (request == null) { - request = this.Channel.GetRequestFromContext(); - } - - IMessageWithClientState response; - if (this.Channel.TryReadFromRequest<IMessageWithClientState>(request, out response)) { - Uri callback = MessagingUtilities.StripMessagePartsFromQueryString(request.GetPublicFacingUrl(), this.Channel.MessageDescriptions.Get(response)); + var response = await this.Channel.TryReadFromRequestAsync<IMessageWithClientState>(request, cancellationToken); + if (response != null) { + Uri callback = request.RequestUri.StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(response)); IAuthorizationState authorizationState; if (this.AuthorizationTracker != null) { authorizationState = this.AuthorizationTracker.GetAuthorizationState(callback, response.ClientState); ErrorUtilities.VerifyProtocol(authorizationState != null, ClientStrings.AuthorizationResponseUnexpectedMismatch); } else { - var context = this.Channel.GetHttpContext(); - - HttpCookie cookie = request.Cookies[XsrfCookieName]; - ErrorUtilities.VerifyProtocol(cookie != null && string.Equals(response.ClientState, cookie.Value, StringComparison.Ordinal), ClientStrings.AuthorizationResponseUnexpectedMismatch); + var xsrfCookieValue = (from cookieHeader in request.Headers.GetCookies() + from cookie in cookieHeader.Cookies + where cookie.Name == XsrfCookieName + select cookie.Value).FirstOrDefault(); + ErrorUtilities.VerifyProtocol(xsrfCookieValue != null && string.Equals(response.ClientState, xsrfCookieValue, StringComparison.Ordinal), ClientStrings.AuthorizationResponseUnexpectedMismatch); authorizationState = new AuthorizationState { Callback = callback }; } var success = response as EndUserAuthorizationSuccessAuthCodeResponse; var failure = response as EndUserAuthorizationFailedResponse; ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany); if (success != null) { - this.UpdateAuthorizationWithResponse(authorizationState, success); + await this.UpdateAuthorizationWithResponseAsync(authorizationState, success, cancellationToken); } else { // failure Logger.OAuth.Info("User refused to grant the requested authorization at the Authorization Server."); authorizationState.Delete(); diff --git a/src/DotNetOpenAuth.OAuth2.Client/packages.config b/src/DotNetOpenAuth.OAuth2.Client/packages.config index 1d93cf5..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth2.Client/packages.config +++ b/src/DotNetOpenAuth.OAuth2.Client/packages.config @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/DotNetOpenAuth.OAuth2.ClientAuthorization.csproj b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/DotNetOpenAuth.OAuth2.ClientAuthorization.csproj index 732f43a..d0f7bcf 100644 --- a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/DotNetOpenAuth.OAuth2.ClientAuthorization.csproj +++ b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/DotNetOpenAuth.OAuth2.ClientAuthorization.csproj @@ -59,6 +59,10 @@ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project> <Name>DotNetOpenAuth.Core</Name> </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OAuth.Common\DotNetOpenAuth.OAuth.Common.csproj"> + <Project>{115217c5-22cd-415c-a292-0dd0238cdd89}</Project> + <Name>DotNetOpenAuth.OAuth.Common</Name> + </ProjectReference> <ProjectReference Include="..\DotNetOpenAuth.OAuth2\DotNetOpenAuth.OAuth2.csproj"> <Project>{56459A6C-6BA2-4BAC-A9C0-27E3BD961FA6}</Project> <Name>DotNetOpenAuth.OAuth2</Name> @@ -75,9 +79,11 @@ <None Include="packages.config" /> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> diff --git a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/ChannelElements/OAuth2ChannelBase.cs b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/ChannelElements/OAuth2ChannelBase.cs index e6be1c4..65de660 100644 --- a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/ChannelElements/OAuth2ChannelBase.cs +++ b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/ChannelElements/OAuth2ChannelBase.cs @@ -12,6 +12,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2.Messages; + using Validation; /// <summary> @@ -24,15 +25,14 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray(); /// <summary> - /// Initializes a new instance of the <see cref="OAuth2ChannelBase"/> class. + /// Initializes a new instance of the <see cref="OAuth2ChannelBase" /> class. /// </summary> /// <param name="messageTypes">The message types that are received by this channel.</param> - /// <param name="channelBindingElements"> - /// The binding elements to use in sending and receiving messages. - /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages. - /// </param> - internal OAuth2ChannelBase(Type[] messageTypes, params IChannelBindingElement[] channelBindingElements) - : base(Requires.NotNull(messageTypes, "messageTypes"), Versions, channelBindingElements) { + /// <param name="channelBindingElements">The binding elements to use in sending and receiving messages. + /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages.</param> + /// <param name="hostFactories">The host factories.</param> + internal OAuth2ChannelBase(Type[] messageTypes, IChannelBindingElement[] channelBindingElements = null, IHostFactories hostFactories = null) + : base(Requires.NotNull(messageTypes, "messageTypes"), Versions, hostFactories ?? new OAuth.DefaultOAuthHostFactories(), channelBindingElements ?? new IChannelBindingElement[0]) { } /// <summary> diff --git a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/AuthenticatedClientRequestBase.cs b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/AuthenticatedClientRequestBase.cs index 96eecbb..cda9a1f 100644 --- a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/AuthenticatedClientRequestBase.cs +++ b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/AuthenticatedClientRequestBase.cs @@ -7,6 +7,8 @@ namespace DotNetOpenAuth.OAuth2.Messages { using System; using System.Net; + using System.Net.Http; + using DotNetOpenAuth.Messaging; /// <summary> @@ -16,7 +18,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// <summary> /// The backing for the <see cref="Headers"/> property. /// </summary> - private readonly WebHeaderCollection headers = new WebHeaderCollection(); + private readonly System.Net.Http.Headers.HttpRequestHeaders headers = new HttpRequestMessage().Headers; /// <summary> /// Initializes a new instance of the <see cref="AuthenticatedClientRequestBase"/> class. @@ -51,7 +53,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { /// Gets the HTTP headers of the request. /// </summary> /// <value>May be an empty collection, but must not be <c>null</c>.</value> - public WebHeaderCollection Headers { + public System.Net.Http.Headers.HttpRequestHeaders Headers { get { return this.headers; } } } diff --git a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs index cb1c5d4..cb9a974 100644 --- a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs +++ b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs @@ -40,7 +40,7 @@ namespace DotNetOpenAuth.OAuth2.Messages { } /// <summary> - /// Gets or sets the error. + /// Gets or sets the error. Usually one of <see cref="Protocol.EndUserAuthorizationRequestErrorCodes"/> /// </summary> /// <value> /// One of the values given in <see cref="Protocol.EndUserAuthorizationRequestErrorCodes"/>. diff --git a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/packages.config b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth2.ClientAuthorization/packages.config +++ b/src/DotNetOpenAuth.OAuth2.ClientAuthorization/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj b/src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj index 2191c16..6641cc0 100644 --- a/src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj +++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/DotNetOpenAuth.OAuth2.ResourceServer.csproj @@ -56,7 +56,7 @@ <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\Validation.2.0.0.12319\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs index 8cf7eeb..1d90844 100644 --- a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs +++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs @@ -9,13 +9,18 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth2.Messages; using Validation; + using HttpRequestHeaders = DotNetOpenAuth.Messaging.HttpRequestHeaders; /// <summary> /// The channel for the OAuth protocol. @@ -34,10 +39,11 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray(); /// <summary> - /// Initializes a new instance of the <see cref="OAuth2ResourceServerChannel"/> class. + /// Initializes a new instance of the <see cref="OAuth2ResourceServerChannel" /> class. /// </summary> - protected internal OAuth2ResourceServerChannel() - : base(MessageTypes, Versions) { + /// <param name="hostFactories">The host factories.</param> + protected internal OAuth2ResourceServerChannel(IHostFactories hostFactories = null) + : base(MessageTypes, Versions, hostFactories ?? new OAuth.DefaultOAuthHostFactories()) { // TODO: add signing (authenticated request) binding element. } @@ -45,13 +51,16 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// Gets the protocol message that may be embedded in the given HTTP request. /// </summary> /// <param name="request">The request to search for an embedded message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The deserialized message, if one is found. Null otherwise. /// </returns> - protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { + protected override async Task<IDirectedProtocolMessage> ReadFromRequestCoreAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + Requires.NotNull(request, "request"); + var fields = new Dictionary<string, string>(); string accessToken; - if ((accessToken = SearchForBearerAccessTokenInRequest(request)) != null) { + if ((accessToken = await SearchForBearerAccessTokenInRequestAsync(request, cancellationToken)) != null) { fields[Protocol.token_type] = Protocol.AccessTokenTypes.Bearer; fields[Protocol.access_token] = accessToken; } @@ -81,7 +90,7 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// The deserialized message parts, if found. Null otherwise. /// </returns> /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + protected override Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken) { // We never expect resource servers to send out direct requests, // and therefore won't have direct responses. throw new NotImplementedException(); @@ -98,8 +107,8 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// <remarks> /// This method implements spec OAuth V1.0 section 5.3. /// </remarks> - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { - var webResponse = new OutgoingWebResponse(); + protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) { + var webResponse = new HttpResponseMessage(); // The only direct response from a resource server is some authorization error (400, 401, 403). var unauthorizedResponse = response as UnauthorizedResponse; @@ -108,12 +117,12 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { // First initialize based on the specifics within the message. ApplyMessageTemplate(response, webResponse); if (!(response is IHttpDirectResponse)) { - webResponse.Status = HttpStatusCode.Unauthorized; + webResponse.StatusCode = HttpStatusCode.Unauthorized; } // Now serialize all the message parts into the WWW-Authenticate header. var fields = this.MessageDescriptions.GetAccessor(response); - webResponse.Headers[HttpResponseHeader.WwwAuthenticate] = MessagingUtilities.AssembleAuthorizationHeader(unauthorizedResponse.Scheme, fields); + webResponse.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(unauthorizedResponse.Scheme, MessagingUtilities.AssembleAuthorizationHeader(fields))); return webResponse; } @@ -122,27 +131,24 @@ namespace DotNetOpenAuth.OAuth2.ChannelElements { /// </summary> /// <param name="request">The request.</param> /// <returns>The bearer access token, if one exists. Otherwise <c>null</c>.</returns> - private static string SearchForBearerAccessTokenInRequest(HttpRequestBase request) { + private static async Task<string> SearchForBearerAccessTokenInRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); // First search the authorization header. - string authorizationHeader = request.Headers[HttpRequestHeaders.Authorization]; - if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace, StringComparison.OrdinalIgnoreCase)) { - return authorizationHeader.Substring(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace.Length); + var authorizationHeader = request.Headers.Authorization; + if (authorizationHeader != null && string.Equals(authorizationHeader.Scheme, Protocol.BearerHttpAuthorizationScheme, StringComparison.OrdinalIgnoreCase)) { + return authorizationHeader.Parameter; } // Failing that, scan the entity - if (!string.IsNullOrEmpty(request.Headers[HttpRequestHeaders.ContentType])) { - var contentType = new ContentType(request.Headers[HttpRequestHeaders.ContentType]); - if (string.Equals(contentType.MediaType, HttpFormUrlEncoded, StringComparison.Ordinal)) { - if (request.Form[Protocol.BearerTokenEncodedUrlParameterName] != null) { - return request.Form[Protocol.BearerTokenEncodedUrlParameterName]; - } + foreach (var pair in await ParseUrlEncodedFormContentAsync(request, cancellationToken)) { + if (string.Equals(pair.Key, Protocol.BearerTokenEncodedUrlParameterName, StringComparison.Ordinal)) { + return pair.Value; } } // Finally, check the least desirable location: the query string - var unrewrittenQuery = request.GetQueryStringBeforeRewriting(); + var unrewrittenQuery = HttpUtility.ParseQueryString(request.RequestUri.Query); if (!string.IsNullOrEmpty(unrewrittenQuery[Protocol.BearerTokenEncodedUrlParameterName])) { return unrewrittenQuery[Protocol.BearerTokenEncodedUrlParameterName]; } diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs index bd129c0..e990e0b 100644 --- a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs +++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/ResourceServer.cs @@ -11,10 +11,13 @@ namespace DotNetOpenAuth.OAuth2 { using System.Linq; using System.Net; using System.Net.Http; + using System.Security.Claims; using System.Security.Principal; using System.ServiceModel.Channels; using System.Text; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using System.Web; using ChannelElements; using DotNetOpenAuth.OAuth.ChannelElements; @@ -78,25 +81,42 @@ namespace DotNetOpenAuth.OAuth2 { /// Discovers what access the client should have considering the access token in the current request. /// </summary> /// <param name="httpRequestInfo">The HTTP request info.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="requiredScopes">The set of scopes required to approve this request.</param> /// <returns> /// The access token describing the authorization the client has. Never <c>null</c>. /// </returns> - /// <exception cref="ProtocolFaultResponseException"> - /// Thrown when the client is not authorized. This exception should be caught and the - /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage"/> message should be returned to the client. - /// </exception> - public virtual AccessToken GetAccessToken(HttpRequestBase httpRequestInfo = null, params string[] requiredScopes) { + /// <exception cref="ProtocolFaultResponseException">Thrown when the client is not authorized. This exception should be caught and the + /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage" /> message should be returned to the client.</exception> + public virtual Task<AccessToken> GetAccessTokenAsync(HttpRequestBase httpRequestInfo = null, CancellationToken cancellationToken = default(CancellationToken), params string[] requiredScopes) { + Requires.NotNull(requiredScopes, "requiredScopes"); + RequiresEx.ValidState(this.ScopeSatisfiedCheck != null, Strings.RequiredPropertyNotYetPreset); + + httpRequestInfo = httpRequestInfo ?? this.Channel.GetRequestFromContext(); + return this.GetAccessTokenAsync(httpRequestInfo.AsHttpRequestMessage(), cancellationToken, requiredScopes); + } + + /// <summary> + /// Discovers what access the client should have considering the access token in the current request. + /// </summary> + /// <param name="request">The HTTP request message.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="requiredScopes">The set of scopes required to approve this request.</param> + /// <returns> + /// The access token describing the authorization the client has. Never <c>null</c>. + /// </returns> + /// <exception cref="ProtocolFaultResponseException">Thrown when the client is not authorized. This exception should be caught and the + /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage" /> message should be returned to the client.</exception> + public virtual async Task<AccessToken> GetAccessTokenAsync(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken), params string[] requiredScopes) { + Requires.NotNull(requestMessage, "requestMessage"); Requires.NotNull(requiredScopes, "requiredScopes"); RequiresEx.ValidState(this.ScopeSatisfiedCheck != null, Strings.RequiredPropertyNotYetPreset); - if (httpRequestInfo == null) { - httpRequestInfo = this.Channel.GetRequestFromContext(); - } AccessToken accessToken; AccessProtectedResourceRequest request = null; try { - if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) { + request = await this.Channel.TryReadFromRequestAsync<AccessProtectedResourceRequest>(requestMessage, cancellationToken); + if (request != null) { accessToken = this.AccessTokenAnalyzer.DeserializeAccessToken(request, request.AccessToken); ErrorUtilities.VerifyHost(accessToken != null, "IAccessTokenAnalyzer.DeserializeAccessToken returned a null reslut."); if (string.IsNullOrEmpty(accessToken.User) && string.IsNullOrEmpty(accessToken.ClientIdentifier)) { @@ -130,34 +150,16 @@ namespace DotNetOpenAuth.OAuth2 { /// <summary> /// Discovers what access the client should have considering the access token in the current request. /// </summary> - /// <param name="request">The HTTP request message.</param> - /// <param name="requiredScopes">The set of scopes required to approve this request.</param> - /// <returns> - /// The access token describing the authorization the client has. Never <c>null</c>. - /// </returns> - /// <exception cref="ProtocolFaultResponseException"> - /// Thrown when the client is not authorized. This exception should be caught and the - /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage"/> message should be returned to the client. - /// </exception> - public virtual AccessToken GetAccessToken(HttpRequestMessage request, params string[] requiredScopes) { - Requires.NotNull(request, "request"); - return this.GetAccessToken(new HttpRequestInfo(request), requiredScopes); - } - - /// <summary> - /// Discovers what access the client should have considering the access token in the current request. - /// </summary> /// <param name="httpRequestInfo">The HTTP request info.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="requiredScopes">The set of scopes required to approve this request.</param> /// <returns> /// The principal that contains the user and roles that the access token is authorized for. Never <c>null</c>. /// </returns> - /// <exception cref="ProtocolFaultResponseException"> - /// Thrown when the client is not authorized. This exception should be caught and the - /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage"/> message should be returned to the client. - /// </exception> - public virtual IPrincipal GetPrincipal(HttpRequestBase httpRequestInfo = null, params string[] requiredScopes) { - AccessToken accessToken = this.GetAccessToken(httpRequestInfo, requiredScopes); + /// <exception cref="ProtocolFaultResponseException">Thrown when the client is not authorized. This exception should be caught and the + /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage" /> message should be returned to the client.</exception> + public virtual async Task<IPrincipal> GetPrincipalAsync(HttpRequestBase httpRequestInfo = null, CancellationToken cancellationToken = default(CancellationToken), params string[] requiredScopes) { + AccessToken accessToken = await this.GetAccessTokenAsync(httpRequestInfo, cancellationToken, requiredScopes); // Mitigates attacks on this approach of differentiating clients from resource owners // by checking that a username doesn't look suspiciously engineered to appear like the other type. @@ -167,10 +169,8 @@ namespace DotNetOpenAuth.OAuth2 { string principalUserName = !string.IsNullOrEmpty(accessToken.User) ? this.ResourceOwnerPrincipalPrefix + accessToken.User : this.ClientPrincipalPrefix + accessToken.ClientIdentifier; - string[] principalScope = accessToken.Scope != null ? accessToken.Scope.ToArray() : new string[0]; - var principal = new OAuthPrincipal(principalUserName, principalScope); - return principal; + return OAuthPrincipal.CreatePrincipal(principalUserName, accessToken.Scope); } /// <summary> @@ -178,36 +178,34 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="request">HTTP details from an incoming WCF message.</param> /// <param name="requestUri">The URI of the WCF service endpoint.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="requiredScopes">The set of scopes required to approve this request.</param> /// <returns> /// The principal that contains the user and roles that the access token is authorized for. Never <c>null</c>. /// </returns> - /// <exception cref="ProtocolFaultResponseException"> - /// Thrown when the client is not authorized. This exception should be caught and the - /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage"/> message should be returned to the client. - /// </exception> - public virtual IPrincipal GetPrincipal(HttpRequestMessageProperty request, Uri requestUri, params string[] requiredScopes) { + /// <exception cref="ProtocolFaultResponseException">Thrown when the client is not authorized. This exception should be caught and the + /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage" /> message should be returned to the client.</exception> + public virtual Task<IPrincipal> GetPrincipalAsync(HttpRequestMessageProperty request, Uri requestUri, CancellationToken cancellationToken = default(CancellationToken), params string[] requiredScopes) { Requires.NotNull(request, "request"); Requires.NotNull(requestUri, "requestUri"); - return this.GetPrincipal(new HttpRequestInfo(request, requestUri), requiredScopes); + return this.GetPrincipalAsync(new HttpRequestInfo(request, requestUri), cancellationToken, requiredScopes); } /// <summary> /// Discovers what access the client should have considering the access token in the current request. /// </summary> /// <param name="request">HTTP details from an incoming HTTP request message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="requiredScopes">The set of scopes required to approve this request.</param> /// <returns> /// The principal that contains the user and roles that the access token is authorized for. Never <c>null</c>. /// </returns> - /// <exception cref="ProtocolFaultResponseException"> - /// Thrown when the client is not authorized. This exception should be caught and the - /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage"/> message should be returned to the client. - /// </exception> - public IPrincipal GetPrincipal(HttpRequestMessage request, params string[] requiredScopes) { + /// <exception cref="ProtocolFaultResponseException">Thrown when the client is not authorized. This exception should be caught and the + /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage" /> message should be returned to the client.</exception> + public Task<IPrincipal> GetPrincipalAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken), params string[] requiredScopes) { Requires.NotNull(request, "request"); - return this.GetPrincipal(new HttpRequestInfo(request), requiredScopes); + return this.GetPrincipalAsync(new HttpRequestInfo(request), cancellationToken, requiredScopes); } } } diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/StandardAccessTokenAnalyzer.cs b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/StandardAccessTokenAnalyzer.cs index 32f10ba..3bd0324 100644 --- a/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/StandardAccessTokenAnalyzer.cs +++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/OAuth2/StandardAccessTokenAnalyzer.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.OAuth2 { using System.IO; using System.Security.Cryptography; using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth2.ChannelElements; using Validation; @@ -30,6 +31,14 @@ namespace DotNetOpenAuth.OAuth2 { } /// <summary> + /// Initializes a new instance of the <see cref="StandardAccessTokenAnalyzer"/> class. + /// </summary> + public StandardAccessTokenAnalyzer(ICryptoKeyStore symmetricKeyStore) { + Requires.NotNull(symmetricKeyStore, "symmetricKeyStore"); + this.SymmetricKeyStore = symmetricKeyStore; + } + + /// <summary> /// Gets the authorization server public signing key. /// </summary> /// <value>The authorization server public signing key.</value> @@ -41,6 +50,8 @@ namespace DotNetOpenAuth.OAuth2 { /// <value>The resource server private encryption key.</value> public RSACryptoServiceProvider ResourceServerPrivateEncryptionKey { get; private set; } + public ICryptoKeyStore SymmetricKeyStore { get; private set; } + /// <summary> /// Reads an access token to find out what data it authorizes access to. /// </summary> @@ -50,7 +61,9 @@ namespace DotNetOpenAuth.OAuth2 { /// <exception cref="ProtocolException">Thrown if the access token is expired, invalid, or from an untrusted authorization server.</exception> public virtual AccessToken DeserializeAccessToken(IDirectedProtocolMessage message, string accessToken) { ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), ResourceServerStrings.MissingAccessToken); - var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServerPublicSigningKey, this.ResourceServerPrivateEncryptionKey); + var accessTokenFormatter = this.AuthorizationServerPublicSigningKey != null + ? AccessToken.CreateFormatter(this.AuthorizationServerPublicSigningKey, this.ResourceServerPrivateEncryptionKey) + : AccessToken.CreateFormatter(this.SymmetricKeyStore); var token = new AccessToken(); try { accessTokenFormatter.Deserialize(token, accessToken, message, Protocol.access_token); diff --git a/src/DotNetOpenAuth.OAuth2.ResourceServer/packages.config b/src/DotNetOpenAuth.OAuth2.ResourceServer/packages.config index 544825c..702ef34 100644 --- a/src/DotNetOpenAuth.OAuth2.ResourceServer/packages.config +++ b/src/DotNetOpenAuth.OAuth2.ResourceServer/packages.config @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> <package id="Microsoft.IdentityModel" version="6.1.7600.16394" targetFramework="net45" /> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj b/src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj index c570242..d0c3626 100644 --- a/src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj +++ b/src/DotNetOpenAuth.OAuth2/DotNetOpenAuth.OAuth2.csproj @@ -59,9 +59,11 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/AccessToken.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/AccessToken.cs index fa87972..a8c911e 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/AccessToken.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/AccessToken.cs @@ -57,6 +57,15 @@ namespace DotNetOpenAuth.OAuth2 { } /// <summary> + /// Creates a formatter capable of serializing/deserializing an access token. + /// </summary> + /// <returns>An access token serializer.</returns> + internal static IDataBagFormatter<AccessToken> CreateFormatter(ICryptoKeyStore symmetricKeyStore) { + Requires.NotNull(symmetricKeyStore, "symmetricKeyStore"); + return new UriStyleMessageFormatter<AccessToken>(symmetricKeyStore, bucket: "AccessTokens", signed: true, encrypted: true); + } + + /// <summary> /// Initializes this instance of the <see cref="AccessToken"/> class. /// </summary> /// <param name="authorization">The authorization to apply to this access token.</param> diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs index f2acf79..1871ad6 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/OAuthUtilities.cs @@ -10,10 +10,13 @@ namespace DotNetOpenAuth.OAuth2 { using System.Globalization; using System.Linq; using System.Net; + using System.Net.Http.Headers; using System.Text; using DotNetOpenAuth.Messaging; using Validation; + using HttpRequestHeaders = DotNetOpenAuth.Messaging.HttpRequestHeaders; + /// <summary> /// Some common utility methods for OAuth 2.0. /// </summary> @@ -26,7 +29,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <summary> /// The string "Basic ". /// </summary> - private const string HttpBasicAuthScheme = "Basic "; + private const string HttpBasicAuthScheme = "Basic"; /// <summary> /// The delimiter between scope elements. @@ -161,7 +164,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <param name="headers">The headers collection to set the authorization header to.</param> /// <param name="userName">The username. Cannot be empty.</param> /// <param name="password">The password. Cannot be null.</param> - internal static void ApplyHttpBasicAuth(WebHeaderCollection headers, string userName, string password) { + internal static void ApplyHttpBasicAuth(System.Net.Http.Headers.HttpRequestHeaders headers, string userName, string password) { Requires.NotNull(headers, "headers"); Requires.NotNullOrEmpty(userName, "userName"); Requires.NotNull(password, "password"); @@ -169,8 +172,7 @@ namespace DotNetOpenAuth.OAuth2 { string concat = userName + ":" + password; byte[] bits = HttpBasicEncoding.GetBytes(concat); string base64 = Convert.ToBase64String(bits); - string header = HttpBasicAuthScheme + base64; - headers[HttpRequestHeader.Authorization] = header; + headers.Authorization = new AuthenticationHeaderValue(HttpBasicAuthScheme, base64); } /// <summary> @@ -178,12 +180,12 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="headers">The incoming web headers.</param> /// <returns>The network credentials; or <c>null</c> if none could be discovered in the request.</returns> - internal static NetworkCredential ParseHttpBasicAuth(WebHeaderCollection headers) { + internal static NetworkCredential ParseHttpBasicAuth(System.Net.Http.Headers.HttpRequestHeaders headers) { Requires.NotNull(headers, "headers"); - string authorizationHeader = headers[HttpRequestHeaders.Authorization]; - if (authorizationHeader != null && authorizationHeader.StartsWith(HttpBasicAuthScheme, StringComparison.Ordinal)) { - string base64 = authorizationHeader.Substring(HttpBasicAuthScheme.Length); + var authorizationHeader = headers.Authorization; + if (authorizationHeader != null && string.Equals(authorizationHeader.Scheme, HttpBasicAuthScheme, StringComparison.Ordinal)) { + string base64 = authorizationHeader.Parameter; byte[] bits = Convert.FromBase64String(base64); string usernameColonPassword = HttpBasicEncoding.GetString(bits); string[] usernameAndPassword = usernameColonPassword.Split(ColonSeparator, 2); diff --git a/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs b/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs index d780a81..93cbd93 100644 --- a/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs +++ b/src/DotNetOpenAuth.OAuth2/OAuth2/Protocol.cs @@ -22,7 +22,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <summary> /// Protocol constants for OAuth 2.0. /// </summary> - internal class Protocol { + public class Protocol { /// <summary> /// The HTTP authorization scheme "Bearer"; /// </summary> @@ -135,7 +135,7 @@ namespace DotNetOpenAuth.OAuth2 { /// <summary> /// The "error_uri" string. /// </summary> - public const string error_uri = "error_uri"; + internal const string error_uri = "error_uri"; /// <summary> /// The "error_description" string. @@ -169,7 +169,7 @@ namespace DotNetOpenAuth.OAuth2 { /// </summary> /// <param name="version">The OAuth version to get.</param> /// <returns>A matching <see cref="Protocol"/> instance.</returns> - public static Protocol Lookup(ProtocolVersion version) { + internal static Protocol Lookup(ProtocolVersion version) { switch (version) { case ProtocolVersion.V20: return Protocol.V20; default: throw new ArgumentOutOfRangeException("version"); @@ -177,6 +177,47 @@ namespace DotNetOpenAuth.OAuth2 { } /// <summary> + /// Error codes that an authorization server can return to a client in response to a malformed or unsupported end user authorization request. + /// </summary> + public static class EndUserAuthorizationRequestErrorCodes + { + /// <summary> + /// The request is missing a required parameter, includes an unknown parameter or parameter value, or is otherwise malformed. + /// </summary> + public const string InvalidRequest = "invalid_request"; + + /// <summary> + /// The client is not authorized to use the requested response type. + /// </summary> + public const string UnauthorizedClient = "unauthorized_client"; + + /// <summary> + /// The end-user or authorization server denied the request. + /// </summary> + public const string AccessDenied = "access_denied"; + + /// <summary> + /// The requested response type is not supported by the authorization server. + /// </summary> + public const string UnsupportedResponseType = "unsupported_response_type"; + + /// <summary> + /// The requested scope is invalid, unknown, or malformed. + /// </summary> + public const string InvalidScope = "invalid_scope"; + + /// <summary> + /// The authorization server encountered an unexpected condition which prevented it from fulfilling the request. + /// </summary> + public const string ServerError = "server_error"; + + /// <summary> + /// The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server. + /// </summary> + public const string TemporarilyUnavailable = "temporarily_unavailable"; + } + + /// <summary> /// Values for the "response_type" parameter. /// </summary> internal static class ResponseTypes @@ -248,47 +289,6 @@ namespace DotNetOpenAuth.OAuth2 { } /// <summary> - /// Error codes that an authorization server can return to a client in response to a malformed or unsupported end user authorization request. - /// </summary> - internal static class EndUserAuthorizationRequestErrorCodes - { - /// <summary> - /// The request is missing a required parameter, includes an unknown parameter or parameter value, or is otherwise malformed. - /// </summary> - internal const string InvalidRequest = "invalid_request"; - - /// <summary> - /// The client is not authorized to use the requested response type. - /// </summary> - internal const string UnauthorizedClient = "unauthorized_client"; - - /// <summary> - /// The end-user or authorization server denied the request. - /// </summary> - internal const string AccessDenied = "access_denied"; - - /// <summary> - /// The requested response type is not supported by the authorization server. - /// </summary> - internal const string UnsupportedResponseType = "unsupported_response_type"; - - /// <summary> - /// The requested scope is invalid, unknown, or malformed. - /// </summary> - internal const string InvalidScope = "invalid_scope"; - - /// <summary> - /// The authorization server encountered an unexpected condition which prevented it from fulfilling the request. - /// </summary> - internal const string ServerError = "server_error"; - - /// <summary> - /// The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server. - /// </summary> - internal const string TemporarilyUnavailable = "temporarily_unavailable"; - } - - /// <summary> /// Recognized access token types. /// </summary> internal static class AccessTokenTypes { diff --git a/src/DotNetOpenAuth.OAuth2/packages.config b/src/DotNetOpenAuth.OAuth2/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OAuth2/packages.config +++ b/src/DotNetOpenAuth.OAuth2/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj b/src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj index 3e0369d..93a0697 100644 --- a/src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj +++ b/src/DotNetOpenAuth.OpenId.Provider.UI/DotNetOpenAuth.OpenId.Provider.UI.csproj @@ -52,9 +52,11 @@ </ItemGroup> <ItemGroup> <Reference Include="System" /> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs index a29f6e3..603d530 100644 --- a/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs +++ b/src/DotNetOpenAuth.OpenId.Provider.UI/OpenId/Provider/ProviderEndpoint.cs @@ -8,7 +8,10 @@ namespace DotNetOpenAuth.OpenId.Provider { using System; using System.Collections.Generic; using System.ComponentModel; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; @@ -43,12 +46,14 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <summary> /// Backing field for the <see cref="Provider"/> property. /// </summary> - private static OpenIdProvider provider; + private Lazy<OpenIdProvider> provider; /// <summary> - /// The lock that must be obtained when initializing the provider field. + /// Initializes a new instance of the <see cref="ProviderEndpoint"/> class. /// </summary> - private static object providerInitializerLock = new object(); + public ProviderEndpoint() { + this.provider = new Lazy<OpenIdProvider>(this.CreateProvider); + } /// <summary> /// Fired when an incoming OpenID request is an authentication challenge @@ -67,22 +72,14 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Gets or sets the <see cref="OpenIdProvider"/> instance to use for all instances of this control. /// </summary> /// <value>The default value is an <see cref="OpenIdProvider"/> instance initialized according to the web.config file.</value> - public static OpenIdProvider Provider { + public OpenIdProvider Provider { get { - if (provider == null) { - lock (providerInitializerLock) { - if (provider == null) { - provider = CreateProvider(); - } - } - } - - return provider; + return this.provider.Value; } set { Requires.NotNull(value, "value"); - provider = value; + this.provider = new Lazy<OpenIdProvider>(() => value, LazyThreadSafetyMode.PublicationOnly); } } @@ -172,12 +169,16 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Sends the response for the <see cref="PendingAuthenticationRequest"/> and clears the property. + /// Sends the response for the <see cref="PendingAuthenticationRequest" /> and clears the property. /// </summary> - public static void SendResponse() { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The response message. + /// </returns> + public Task<HttpResponseMessage> PrepareResponseAsync(CancellationToken cancellationToken = default(CancellationToken)) { var pendingRequest = PendingRequest; PendingRequest = null; - Provider.SendResponse(pendingRequest); + return this.Provider.PrepareResponseAsync(pendingRequest, cancellationToken); } /// <summary> @@ -189,41 +190,46 @@ namespace DotNetOpenAuth.OpenId.Provider { protected override void OnLoad(EventArgs e) { base.OnLoad(e); - // There is the unusual scenario that this control is hosted by - // an ASP.NET web page that has other UI on it to that the user - // might see, including controls that cause a postback to occur. - // We definitely want to ignore postbacks, since any openid messages - // they contain will be old. - if (this.Enabled && !this.Page.IsPostBack) { - // Use the explicitly given state store on this control if there is one. - // Then try the configuration file specified one. Finally, use the default - // in-memory one that's built into OpenIdProvider. - // determine what incoming message was received - IRequest request = Provider.GetRequest(); - if (request != null) { - PendingRequest = null; + this.Page.RegisterAsyncTask(new PageAsyncTask(async cancellationToken => { + // There is the unusual scenario that this control is hosted by + // an ASP.NET web page that has other UI on it to that the user + // might see, including controls that cause a postback to occur. + // We definitely want to ignore postbacks, since any openid messages + // they contain will be old. + if (this.Enabled && !this.Page.IsPostBack) { + // Use the explicitly given state store on this control if there is one. + // Then try the configuration file specified one. Finally, use the default + // in-memory one that's built into OpenIdProvider. + // determine what incoming message was received + IRequest request = await Provider.GetRequestAsync(new HttpRequestWrapper(this.Context.Request), cancellationToken); + if (request != null) { + PendingRequest = null; - // process the incoming message appropriately and send the response - IAuthenticationRequest idrequest; - IAnonymousRequest anonRequest; - if ((idrequest = request as IAuthenticationRequest) != null) { - PendingAuthenticationRequest = idrequest; - this.OnAuthenticationChallenge(idrequest); - } else if ((anonRequest = request as IAnonymousRequest) != null) { - PendingAnonymousRequest = anonRequest; - if (!this.OnAnonymousRequest(anonRequest)) { - // This is a feature not supported by the OP, so - // go ahead and set disapproved so we can send a response. - Logger.OpenId.Warn("An incoming anonymous OpenID request message was detected, but the ProviderEndpoint.AnonymousRequest event is not handled, so returning cancellation message to relying party."); - anonRequest.IsApproved = false; + // process the incoming message appropriately and send the response + IAuthenticationRequest idrequest; + IAnonymousRequest anonRequest; + if ((idrequest = request as IAuthenticationRequest) != null) { + PendingAuthenticationRequest = idrequest; + this.OnAuthenticationChallenge(idrequest); + } else if ((anonRequest = request as IAnonymousRequest) != null) { + PendingAnonymousRequest = anonRequest; + if (!this.OnAnonymousRequest(anonRequest)) { + // This is a feature not supported by the OP, so + // go ahead and set disapproved so we can send a response. + Logger.OpenId.Warn( + "An incoming anonymous OpenID request message was detected, but the ProviderEndpoint.AnonymousRequest event is not handled, so returning cancellation message to relying party."); + anonRequest.IsApproved = false; + } + } + if (request.IsResponseReady) { + PendingAuthenticationRequest = null; + var response = await Provider.PrepareResponseAsync(request, cancellationToken); + await response.SendAsync(new HttpContextWrapper(this.Context), cancellationToken); + this.Context.Response.End(); } - } - if (request.IsResponseReady) { - PendingAuthenticationRequest = null; - Provider.SendResponse(request); } } - } + })); } /// <summary> @@ -256,8 +262,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Creates the default OpenIdProvider to use. /// </summary> /// <returns>The new instance of OpenIdProvider.</returns> - private static OpenIdProvider CreateProvider() { - return new OpenIdProvider(OpenIdElement.Configuration.Provider.ApplicationStore.CreateInstance(OpenIdProvider.HttpApplicationStore)); + private OpenIdProvider CreateProvider() { + return new OpenIdProvider(OpenIdElement.Configuration.Provider.ApplicationStore.CreateInstance(OpenIdProvider.GetHttpApplicationStore(new HttpContextWrapper(this.Context)), null)); } } } diff --git a/src/DotNetOpenAuth.OpenId.Provider.UI/packages.config b/src/DotNetOpenAuth.OpenId.Provider.UI/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OpenId.Provider.UI/packages.config +++ b/src/DotNetOpenAuth.OpenId.Provider.UI/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj b/src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj index 0df2b70..24baea8 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj +++ b/src/DotNetOpenAuth.OpenId.Provider/DotNetOpenAuth.OpenId.Provider.csproj @@ -73,9 +73,11 @@ </ItemGroup> <ItemGroup> <Reference Include="System" /> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs index 45a69a5..5eb4f90 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/OpenIdProviderChannel.cs @@ -20,26 +20,28 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </summary> internal class OpenIdProviderChannel : OpenIdChannel { /// <summary> - /// Initializes a new instance of the <see cref="OpenIdProviderChannel"/> class. + /// Initializes a new instance of the <see cref="OpenIdProviderChannel" /> class. /// </summary> /// <param name="cryptoKeyStore">The OpenID Provider's association store or handle encoder.</param> /// <param name="nonceStore">The nonce store to use.</param> /// <param name="securitySettings">The security settings.</param> - internal OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings) - : this(cryptoKeyStore, nonceStore, new OpenIdProviderMessageFactory(), securitySettings) { + /// <param name="hostFactories">The host factories.</param> + internal OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings, IHostFactories hostFactories) + : this(cryptoKeyStore, nonceStore, new OpenIdProviderMessageFactory(), securitySettings, hostFactories) { Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); Requires.NotNull(securitySettings, "securitySettings"); } /// <summary> - /// Initializes a new instance of the <see cref="OpenIdProviderChannel"/> class. + /// Initializes a new instance of the <see cref="OpenIdProviderChannel" /> class. /// </summary> /// <param name="cryptoKeyStore">The association store to use.</param> /// <param name="nonceStore">The nonce store to use.</param> /// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param> /// <param name="securitySettings">The security settings.</param> - private OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, ProviderSecuritySettings securitySettings) - : base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings)) { + /// <param name="hostFactories">The host factories.</param> + private OpenIdProviderChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, ProviderSecuritySettings securitySettings, IHostFactories hostFactories) + : base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings), hostFactories) { Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); Requires.NotNull(messageTypeProvider, "messageTypeProvider"); Requires.NotNull(securitySettings, "securitySettings"); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs index fbbf37a..26d9133 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/ChannelElements/ProviderSigningBindingElement.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; @@ -56,12 +58,13 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { - var result = base.ProcessOutgoingMessage(message); + public override async Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { + var result = await base.ProcessOutgoingMessageAsync(message, cancellationToken); if (result != null) { return result; } @@ -158,13 +161,16 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="message">The message.</param> /// <param name="signedMessage">The signed message.</param> /// <param name="protectionsApplied">The protections applied.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The applied protections. /// </returns> - protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) { + protected override Task<MessageProtections> VerifySignatureByUnrecognizedHandleAsync(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied, CancellationToken cancellationToken) { // If we're on the Provider, then the RP sent us a check_auth with a signature // we don't have an association for. (It may have expired, or it may be a faulty RP). - throw new InvalidSignatureException(message); + var tcs = new TaskCompletionSource<MessageProtections>(); + tcs.SetException(new InvalidSignatureException(message)); + return tcs.Task; } /// <summary> @@ -224,9 +230,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { MessageDescription description = this.Channel.MessageDescriptions.Get(signedMessage); var signedParts = from part in description.Mapping.Values - where (part.RequiredProtection & System.Net.Security.ProtectionLevel.Sign) != 0 - && part.GetValue(signedMessage) != null - select part.Name; + where (part.RequiredProtection & System.Net.Security.ProtectionLevel.Sign) != 0 + && part.GetValue(signedMessage) != null + select part.Name; string prefix = Protocol.V20.openid.Prefix; ErrorUtilities.VerifyInternal(signedParts.All(name => name.StartsWith(prefix, StringComparison.Ordinal)), "All signed message parts must start with 'openid.'."); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs index 9d73d9a..f25a107 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AnonymousRequest.cs @@ -7,6 +7,8 @@ namespace DotNetOpenAuth.OpenId.Provider { using System; using System.Diagnostics.CodeAnalysis; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using Validation; @@ -75,16 +77,16 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Gets the response message, once <see cref="IsResponseReady"/> is <c>true</c>. + /// Gets the response message, once <see cref="IsResponseReady" /> is <c>true</c>. /// </summary> - protected override IProtocolMessage ResponseMessage { - get { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The response message.</returns> + protected override async Task<IProtocolMessage> GetResponseMessageAsync(CancellationToken cancellationToken) { if (this.IsApproved.HasValue) { - return this.IsApproved.Value ? (IProtocolMessage)this.positiveResponse : this.NegativeResponse; + return this.IsApproved.Value ? (IProtocolMessage)this.positiveResponse : await this.GetNegativeResponseAsync(); } else { return null; } - } } #endregion diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs index 0167580..6e67f53 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AuthenticationRequest.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.OpenId.Provider { using System; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using Validation; @@ -174,19 +176,6 @@ namespace DotNetOpenAuth.OpenId.Provider { get { return (CheckIdRequest)base.RequestMessage; } } - /// <summary> - /// Gets the response message, once <see cref="IsResponseReady"/> is <c>true</c>. - /// </summary> - protected override IProtocolMessage ResponseMessage { - get { - if (this.IsAuthenticated.HasValue) { - return this.IsAuthenticated.Value ? (IProtocolMessage)this.positiveResponse : this.NegativeResponse; - } else { - return null; - } - } - } - #region IAuthenticationRequest Methods /// <summary> @@ -211,6 +200,8 @@ namespace DotNetOpenAuth.OpenId.Provider { this.positiveResponse.ClaimedIdentifier = builder.Uri; } + #endregion + /// <summary> /// Sets the Claimed and Local identifiers even after they have been initially set. /// </summary> @@ -222,6 +213,17 @@ namespace DotNetOpenAuth.OpenId.Provider { this.positiveResponse.LocalIdentifier = identifier; } - #endregion + /// <summary> + /// Gets the response message, once <see cref="IsResponseReady" /> is <c>true</c>. + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The response message.</returns> + protected override async Task<IProtocolMessage> GetResponseMessageAsync(CancellationToken cancellationToken) { + if (this.IsAuthenticated.HasValue) { + return this.IsAuthenticated.Value ? (IProtocolMessage)this.positiveResponse : await this.GetNegativeResponseAsync(); + } else { + return null; + } + } } } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs index 91bb6f3..5aea3ca 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/AutoResponsiveRequest.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenId.Provider { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using Validation; @@ -62,17 +64,22 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Gets the response message, once <see cref="IsResponseReady"/> is <c>true</c>. + /// Gets the response message, once <see cref="IsResponseReady" /> is <c>true</c>. /// </summary> - internal IProtocolMessage ResponseMessageTestHook { - get { return this.ResponseMessage; } + /// <returns>The response message.</returns> + internal Task<IProtocolMessage> GetResponseMessageAsyncTestHook(CancellationToken cancellationToken) { + return this.GetResponseMessageAsync(cancellationToken); } /// <summary> - /// Gets the response message, once <see cref="IsResponseReady"/> is <c>true</c>. + /// Gets the response message, once <see cref="IsResponseReady" /> is <c>true</c>. /// </summary> - protected override IProtocolMessage ResponseMessage { - get { return this.response; } + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The response message. + /// </returns> + protected override Task<IProtocolMessage> GetResponseMessageAsync(CancellationToken cancellationToken) { + return Task.FromResult(this.response); } } } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/AXFetchAsSregTransform.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/AXFetchAsSregTransform.cs index d5f3f4e..17c9a1a 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/AXFetchAsSregTransform.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/AXFetchAsSregTransform.cs @@ -10,6 +10,8 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Behaviors; using DotNetOpenAuth.OpenId.Extensions; @@ -51,34 +53,36 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { /// Called when a request is received by the Provider. /// </summary> /// <param name="request">The incoming request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// <c>true</c> if this behavior owns this request and wants to stop other behaviors + /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. /// </returns> /// <remarks> - /// Implementations may set a new value to <see cref="IRequest.SecuritySettings"/> but - /// should not change the properties on the instance of <see cref="ProviderSecuritySettings"/> + /// Implementations may set a new value to <see cref="IRequest.SecuritySettings" /> but + /// should not change the properties on the instance of <see cref="ProviderSecuritySettings" /> /// itself as that instance may be shared across many requests. /// </remarks> - bool IProviderBehavior.OnIncomingRequest(IRequest request) { + Task<bool> IProviderBehavior.OnIncomingRequestAsync(IRequest request, CancellationToken cancellationToken) { var extensionRequest = request as Provider.HostProcessedRequest; if (extensionRequest != null) { extensionRequest.UnifyExtensionsAsSreg(); } - return false; + return Task.FromResult(false); } /// <summary> /// Called when the Provider is preparing to send a response to an authentication request. /// </summary> /// <param name="request">The request that is configured to generate the outgoing response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> - /// <c>true</c> if this behavior owns this request and wants to stop other behaviors + /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. /// </returns> - bool IProviderBehavior.OnOutgoingResponse(Provider.IAuthenticationRequest request) { - request.ConvertSregToMatchRequest(); + async Task<bool> IProviderBehavior.OnOutgoingResponseAsync(Provider.IAuthenticationRequest request, CancellationToken cancellationToken) { + await request.ConvertSregToMatchRequestAsync(cancellationToken); return false; } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/GsaIcamProfile.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/GsaIcamProfile.cs index e12ca39..0aa4642 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/GsaIcamProfile.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/GsaIcamProfile.cs @@ -8,6 +8,8 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Behaviors; @@ -69,6 +71,7 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { /// Called when a request is received by the Provider. /// </summary> /// <param name="request">The incoming request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. @@ -78,7 +81,7 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { /// should not change the properties on the instance of <see cref="ProviderSecuritySettings"/> /// itself as that instance may be shared across many requests. /// </remarks> - bool IProviderBehavior.OnIncomingRequest(IRequest request) { + Task<bool> IProviderBehavior.OnIncomingRequestAsync(IRequest request, CancellationToken cancellationToken) { var hostProcessedRequest = request as IHostProcessedRequest; if (hostProcessedRequest != null) { // Only apply our special policies if the RP requested it. @@ -91,23 +94,24 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { // Apply GSA-specific security to this individual request. request.SecuritySettings.RequireSsl = !DisableSslRequirement; - return true; + return Task.FromResult(true); } } } - return false; + return Task.FromResult(false); } /// <summary> /// Called when the Provider is preparing to send a response to an authentication request. /// </summary> /// <param name="request">The request that is configured to generate the outgoing response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. /// </returns> - bool IProviderBehavior.OnOutgoingResponse(Provider.IAuthenticationRequest request) { + async Task<bool> IProviderBehavior.OnOutgoingResponseAsync(Provider.IAuthenticationRequest request, CancellationToken cancellationToken) { bool result = false; // Nothing to do for negative assertions. @@ -116,7 +120,7 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { } var requestInternal = (Provider.AuthenticationRequest)request; - var responseMessage = (IProtocolMessageWithExtensions)requestInternal.Response; + var responseMessage = (IProtocolMessageWithExtensions)await requestInternal.GetResponseAsync(cancellationToken); // Only apply our special policies if the RP requested it. var papeRequest = request.GetExtension<PolicyRequest>(); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/PpidGeneration.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/PpidGeneration.cs index c8bdd93..5acd4c9 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/PpidGeneration.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Behaviors/PpidGeneration.cs @@ -8,6 +8,8 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Behaviors; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; @@ -52,6 +54,7 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { /// Called when a request is received by the Provider. /// </summary> /// <param name="request">The incoming request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. @@ -61,26 +64,27 @@ namespace DotNetOpenAuth.OpenId.Provider.Behaviors { /// should not change the properties on the instance of <see cref="ProviderSecuritySettings"/> /// itself as that instance may be shared across many requests. /// </remarks> - bool IProviderBehavior.OnIncomingRequest(IRequest request) { - return false; + Task<bool> IProviderBehavior.OnIncomingRequestAsync(IRequest request, CancellationToken cancellationToken) { + return Task.FromResult(false); } /// <summary> /// Called when the Provider is preparing to send a response to an authentication request. /// </summary> /// <param name="request">The request that is configured to generate the outgoing response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. /// </returns> - bool IProviderBehavior.OnOutgoingResponse(IAuthenticationRequest request) { + async Task<bool> IProviderBehavior.OnOutgoingResponseAsync(IAuthenticationRequest request, CancellationToken cancellationToken) { // Nothing to do for negative assertions. if (!request.IsAuthenticated.Value) { return false; } var requestInternal = (Provider.AuthenticationRequest)request; - var responseMessage = (IProtocolMessageWithExtensions)requestInternal.Response; + var responseMessage = (IProtocolMessageWithExtensions)await requestInternal.GetResponseAsync(cancellationToken); // Only apply our special policies if the RP requested it. var papeRequest = request.GetExtension<PolicyRequest>(); diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs index d4332d2..45a59d2 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/ExtensionsInteropHelper.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenId.Provider.Extensions { using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; @@ -74,13 +76,18 @@ namespace DotNetOpenAuth.OpenId.Provider.Extensions { /// attribute request extension came in. /// </summary> /// <param name="request">The authentication request with the response extensions already added.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> /// <remarks> /// If the original attribute request came in as AX, the Simple Registration extension is converted /// to an AX response and then the Simple Registration extension is removed from the response. /// </remarks> - internal static void ConvertSregToMatchRequest(this Provider.IHostProcessedRequest request) { + internal static async Task ConvertSregToMatchRequestAsync(this Provider.IHostProcessedRequest request, CancellationToken cancellationToken) { var req = (Provider.HostProcessedRequest)request; - var response = req.Response as IProtocolMessageWithExtensions; // negative responses don't support extensions. + var protocolMessage = await req.GetResponseAsync(cancellationToken); + var response = protocolMessage as IProtocolMessageWithExtensions; // negative responses don't support extensions. var sregRequest = request.GetExtension<ClaimsRequest>(); if (sregRequest != null && response != null) { if (sregRequest.Synthesized) { diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs index 278ad6c..c531ddd 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Extensions/UI/UIRequestTools.cs @@ -10,6 +10,8 @@ namespace DotNetOpenAuth.OpenId.Provider.Extensions.UI { using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.UI; using DotNetOpenAuth.OpenId.Messages; @@ -35,8 +37,8 @@ namespace DotNetOpenAuth.OpenId.Provider.Extensions.UI { /// Gets the URL of the RP icon for the OP to display. /// </summary> /// <param name="realm">The realm of the RP where the authentication request originated.</param> - /// <param name="webRequestHandler">The web request handler to use for discovery. - /// Usually available via <see cref="Channel.WebRequestHandler">OpenIdProvider.Channel.WebRequestHandler</see>.</param> + /// <param name="hostFactories">The host factories.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order. /// </returns> @@ -51,13 +53,11 @@ namespace DotNetOpenAuth.OpenId.Provider.Extensions.UI { /// </Service> /// </example> /// </remarks> - public static IEnumerable<Uri> GetRelyingPartyIconUrls(Realm realm, IDirectWebRequestHandler webRequestHandler) { + public static async Task<IEnumerable<Uri>> GetRelyingPartyIconUrlsAsync(Realm realm, IHostFactories hostFactories, CancellationToken cancellationToken) { Requires.NotNull(realm, "realm"); - Requires.NotNull(webRequestHandler, "webRequestHandler"); - ErrorUtilities.VerifyArgumentNotNull(realm, "realm"); - ErrorUtilities.VerifyArgumentNotNull(webRequestHandler, "webRequestHandler"); + Requires.NotNull(hostFactories, "hostFactories"); - XrdsDocument xrds = realm.Discover(webRequestHandler, false); + XrdsDocument xrds = await realm.DiscoverAsync(hostFactories, false, cancellationToken); if (xrds == null) { return Enumerable.Empty<Uri>(); } else { diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs index 9c5004c..a727e42 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/HostProcessedRequest.cs @@ -10,19 +10,23 @@ namespace DotNetOpenAuth.OpenId.Provider { using System.Linq; using System.Net; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using Validation; + using System.Runtime.Serialization; /// <summary> /// A base class from which identity and non-identity RP requests can derive. /// </summary> [Serializable] - internal abstract class HostProcessedRequest : Request, IHostProcessedRequest { + internal abstract class HostProcessedRequest : Request, IHostProcessedRequest, IDeserializationCallback { /// <summary> /// The negative assertion to send, if the host site chooses to send it. /// </summary> - private readonly NegativeAssertionResponse negativeResponse; + [NonSerialized] + private Lazy<Task<NegativeAssertionResponse>> negativeResponse; /// <summary> /// A cache of the result from discovery of the Realm URL. @@ -38,7 +42,7 @@ namespace DotNetOpenAuth.OpenId.Provider { : base(request, provider.SecuritySettings) { Requires.NotNull(provider, "provider"); - this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel); + this.SharedInitialization(provider); Reporting.RecordEventOccurrence(this, request.Realm); } @@ -85,13 +89,6 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Gets the negative response. - /// </summary> - protected NegativeAssertionResponse NegativeResponse { - get { return this.negativeResponse; } - } - - /// <summary> /// Gets the original request message. /// </summary> /// <value>This may be null in the case of an unrecognizable message.</value> @@ -105,7 +102,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Gets a value indicating whether verification of the return URL claimed by the Relying Party /// succeeded. /// </summary> - /// <param name="requestHandler">The request handler.</param> + /// <param name="hostFactories">The host factories.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Result of realm discovery. /// </returns> @@ -115,25 +113,45 @@ namespace DotNetOpenAuth.OpenId.Provider { /// property getter multiple times in one request is not a performance hit. /// See OpenID Authentication 2.0 spec section 9.2.1. /// </remarks> - public RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(IDirectWebRequestHandler requestHandler) { + public async Task<RelyingPartyDiscoveryResult> IsReturnUrlDiscoverableAsync(IHostFactories hostFactories, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(hostFactories, "hostFactories"); if (!this.realmDiscoveryResult.HasValue) { - this.realmDiscoveryResult = this.IsReturnUrlDiscoverableCore(requestHandler); + this.realmDiscoveryResult = await this.IsReturnUrlDiscoverableCoreAsync(hostFactories, cancellationToken); } return this.realmDiscoveryResult.Value; } + #endregion + + /// <summary> + /// Runs when the entire object graph has been deserialized. + /// </summary> + /// <param name="sender">The object that initiated the callback. The functionality for this parameter is not currently implemented.</param> + void IDeserializationCallback.OnDeserialization(object sender) { + // Bug: user_setup_url won't be created for OpenID 1.1 RPs in this path. + this.SharedInitialization(null); + } + + /// <summary> + /// Gets the negative response. + /// </summary> + /// <returns>The negative assertion message.</returns> + protected Task<NegativeAssertionResponse> GetNegativeResponseAsync() { + return this.negativeResponse.Value; + } + /// <summary> /// Gets a value indicating whether verification of the return URL claimed by the Relying Party /// succeeded. /// </summary> - /// <param name="requestHandler">The request handler.</param> + /// <param name="hostFactories">The host factories.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Result of realm discovery. /// </returns> - private RelyingPartyDiscoveryResult IsReturnUrlDiscoverableCore(IDirectWebRequestHandler requestHandler) { - Requires.NotNull(requestHandler, "requestHandler"); - + private async Task<RelyingPartyDiscoveryResult> IsReturnUrlDiscoverableCoreAsync(IHostFactories hostFactories, CancellationToken cancellationToken) { + Requires.NotNull(hostFactories, "hostFactories"); ErrorUtilities.VerifyInternal(this.Realm != null, "Realm should have been read or derived by now."); try { @@ -142,7 +160,7 @@ namespace DotNetOpenAuth.OpenId.Provider { return RelyingPartyDiscoveryResult.NoServiceDocument; } - var returnToEndpoints = this.Realm.DiscoverReturnToEndpoints(requestHandler, false); + var returnToEndpoints = await this.Realm.DiscoverReturnToEndpointsAsync(hostFactories, false, cancellationToken); if (returnToEndpoints == null) { return RelyingPartyDiscoveryResult.NoServiceDocument; } @@ -177,6 +195,12 @@ namespace DotNetOpenAuth.OpenId.Provider { return RelyingPartyDiscoveryResult.NoMatchingReturnTo; } - #endregion + /// <summary> + /// Performs initialization common to construction and deserialization. + /// </summary> + /// <param name="provider">The provider.</param> + private void SharedInitialization(OpenIdProvider provider) { + this.negativeResponse = new Lazy<Task<NegativeAssertionResponse>>(() => NegativeAssertionResponse.CreateAsync(this.RequestMessage, CancellationToken.None, provider.Channel)); + } } } diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs index d96e5c9..aabc8cb 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/OpenIdProvider.cs @@ -12,7 +12,9 @@ namespace DotNetOpenAuth.OpenId.Provider { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; + using System.Net.Http; using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; @@ -53,35 +55,37 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Initializes a new instance of the <see cref="OpenIdProvider"/> class. /// </summary> public OpenIdProvider() - : this(OpenIdElement.Configuration.Provider.ApplicationStore.CreateInstance(HttpApplicationStore)) { + : this(OpenIdElement.Configuration.Provider.ApplicationStore.CreateInstance(GetHttpApplicationStore(), null)) { } /// <summary> - /// Initializes a new instance of the <see cref="OpenIdProvider"/> class. + /// Initializes a new instance of the <see cref="OpenIdProvider" /> class. /// </summary> /// <param name="applicationStore">The application store to use. Cannot be null.</param> - public OpenIdProvider(IOpenIdApplicationStore applicationStore) - : this((INonceStore)applicationStore, (ICryptoKeyStore)applicationStore) { + /// <param name="hostFactories">The host factories.</param> + public OpenIdProvider(IOpenIdApplicationStore applicationStore, IHostFactories hostFactories = null) + : this((INonceStore)applicationStore, (ICryptoKeyStore)applicationStore, hostFactories) { Requires.NotNull(applicationStore, "applicationStore"); } /// <summary> - /// Initializes a new instance of the <see cref="OpenIdProvider"/> class. + /// Initializes a new instance of the <see cref="OpenIdProvider" /> class. /// </summary> /// <param name="nonceStore">The nonce store to use. Cannot be null.</param> /// <param name="cryptoKeyStore">The crypto key store. Cannot be null.</param> - private OpenIdProvider(INonceStore nonceStore, ICryptoKeyStore cryptoKeyStore) { + /// <param name="hostFactories">The host factories.</param> + private OpenIdProvider(INonceStore nonceStore, ICryptoKeyStore cryptoKeyStore, IHostFactories hostFactories) { Requires.NotNull(nonceStore, "nonceStore"); Requires.NotNull(cryptoKeyStore, "cryptoKeyStore"); this.SecuritySettings = OpenIdElement.Configuration.Provider.SecuritySettings.CreateSecuritySettings(); this.behaviors.CollectionChanged += this.OnBehaviorsChanged; - foreach (var behavior in OpenIdElement.Configuration.Provider.Behaviors.CreateInstances(false)) { + foreach (var behavior in OpenIdElement.Configuration.Provider.Behaviors.CreateInstances(false, null)) { this.behaviors.Add(behavior); } this.AssociationStore = new SwitchingAssociationStore(cryptoKeyStore, this.SecuritySettings); - this.Channel = new OpenIdProviderChannel(this.AssociationStore, nonceStore, this.SecuritySettings); + this.Channel = new OpenIdProviderChannel(this.AssociationStore, nonceStore, this.SecuritySettings, hostFactories); this.CryptoKeyStore = cryptoKeyStore; this.discoveryServices = new IdentifierDiscoveryServices(this); @@ -89,31 +93,6 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Gets the standard state storage mechanism that uses ASP.NET's - /// HttpApplication state dictionary to store associations and nonces. - /// </summary> - [EditorBrowsable(EditorBrowsableState.Advanced)] - public static IOpenIdApplicationStore HttpApplicationStore { - get { - RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - HttpContext context = HttpContext.Current; - var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]; - if (store == null) { - context.Application.Lock(); - try { - if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) { - context.Application[ApplicationStoreKey] = store = new StandardProviderApplicationStore(); - } - } finally { - context.Application.UnLock(); - } - } - - return store; - } - } - - /// <summary> /// Gets the channel to use for sending/receiving messages. /// </summary> public Channel Channel { get; internal set; } @@ -170,11 +149,10 @@ namespace DotNetOpenAuth.OpenId.Provider { public ICryptoKeyStore CryptoKeyStore { get; private set; } /// <summary> - /// Gets the web request handler to use for discovery and the part of - /// authentication where direct messages are sent to an untrusted remote party. + /// Gets the factory for various dependencies. /// </summary> - IDirectWebRequestHandler IOpenIdHost.WebRequestHandler { - get { return this.Channel.WebRequestHandler; } + IHostFactories IOpenIdHost.HostFactories { + get { return this.Channel.HostFactories; } } /// <summary> @@ -197,55 +175,79 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Gets the web request handler to use for discovery and the part of - /// authentication where direct messages are sent to an untrusted remote party. + /// Gets the standard state storage mechanism that uses ASP.NET's + /// HttpApplication state dictionary to store associations and nonces. /// </summary> - internal IDirectWebRequestHandler WebRequestHandler { - get { return this.Channel.WebRequestHandler; } + /// <param name="context">The context.</param> + /// <returns>The application store.</returns> + public static IOpenIdApplicationStore GetHttpApplicationStore(HttpContextBase context = null) { + if (context == null) { + ErrorUtilities.VerifyOperation(HttpContext.Current != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(IOpenIdApplicationStore).Name); + context = new HttpContextWrapper(HttpContext.Current); + } + + var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]; + if (store == null) { + context.Application.Lock(); + try { + if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) { + context.Application[ApplicationStoreKey] = store = new StandardProviderApplicationStore(); + } + } finally { + context.Application.UnLock(); + } + } + + return store; } /// <summary> /// Gets the incoming OpenID request if there is one, or null if none was detected. /// </summary> - /// <returns>The request that the hosting Provider should possibly process and then transmit the response for.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The request that the hosting Provider should possibly process and then transmit the response for. + /// </returns> + /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> + /// <exception cref="ProtocolException">Thrown if the incoming message is recognized but deviates from the protocol specification irrecoverably.</exception> /// <remarks> - /// <para>Requests may be infrastructural to OpenID and allow auto-responses, or they may + /// <para>Requests may be infrastructural to OpenID and allow auto-responses, or they may /// be authentication requests where the Provider site has to make decisions based /// on its own user database and policies.</para> - /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> + /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> /// </remarks> - /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> - /// <exception cref="ProtocolException">Thrown if the incoming message is recognized but deviates from the protocol specification irrecoverably.</exception> - public IRequest GetRequest() { - return this.GetRequest(this.Channel.GetRequestFromContext()); + public Task<IRequest> GetRequestAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.Channel.GetRequestFromContext(); + return this.GetRequestAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> /// Gets the incoming OpenID request if there is one, or null if none was detected. /// </summary> - /// <param name="httpRequestInfo">The incoming HTTP request to extract the message from.</param> + /// <param name="request">The incoming HTTP request to extract the message from.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The request that the hosting Provider should process and then transmit the response for. /// Null if no valid OpenID request was detected in the given HTTP request. /// </returns> + /// <exception cref="ProtocolException">Thrown if the incoming message is recognized + /// but deviates from the protocol specification irrecoverably.</exception> /// <remarks> /// Requests may be infrastructural to OpenID and allow auto-responses, or they may /// be authentication requests where the Provider site has to make decisions based /// on its own user database and policies. /// </remarks> - /// <exception cref="ProtocolException">Thrown if the incoming message is recognized - /// but deviates from the protocol specification irrecoverably.</exception> - public IRequest GetRequest(HttpRequestBase httpRequestInfo) { - Requires.NotNull(httpRequestInfo, "httpRequestInfo"); + public async Task<IRequest> GetRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "request"); IDirectedProtocolMessage incomingMessage = null; try { - incomingMessage = this.Channel.ReadFromRequest(httpRequestInfo); + incomingMessage = await this.Channel.ReadFromRequestAsync(request, cancellationToken); if (incomingMessage == null) { // If the incoming request does not resemble an OpenID message at all, // it's probably a user who just navigated to this URL, and we should // just return null so the host can display a message to the user. - if (httpRequestInfo.HttpMethod == "GET" && !httpRequestInfo.GetPublicFacingUrl().QueryStringContainPrefixedParameters(Protocol.Default.openid.Prefix)) { + if (request.Method == HttpMethod.Get && !request.RequestUri.QueryStringContainPrefixedParameters(Protocol.Default.openid.Prefix)) { return null; } @@ -282,7 +284,7 @@ namespace DotNetOpenAuth.OpenId.Provider { if (result != null) { foreach (var behavior in this.Behaviors) { - if (behavior.OnIncomingRequest(result)) { + if (await behavior.OnIncomingRequestAsync(result, cancellationToken)) { // This behavior matched this request. break; } @@ -293,7 +295,7 @@ namespace DotNetOpenAuth.OpenId.Provider { throw ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessageReceivedOfMany); } catch (ProtocolException ex) { - IRequest errorResponse = this.GetErrorResponse(ex, httpRequestInfo, incomingMessage); + IRequest errorResponse = this.GetErrorResponse(ex, request, incomingMessage); if (errorResponse == null) { throw; } @@ -303,89 +305,23 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Sends the response to a received request. - /// </summary> - /// <param name="request">The incoming OpenID request whose response is to be sent.</param> - /// <exception cref="ThreadAbortException">Thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception> - /// <remarks> - /// <para>Requires an HttpContext.Current context. If one is not available, the caller should use - /// <see cref="PrepareResponse"/> instead and manually send the <see cref="OutgoingWebResponse"/> - /// to the client.</para> - /// </remarks> - /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception> - [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")] - [EditorBrowsable(EditorBrowsableState.Never)] - public void SendResponse(IRequest request) { - RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); - Requires.NotNull(request, "request"); - Requires.That(request.IsResponseReady, "request", OpenIdStrings.ResponseNotReady); - - this.ApplyBehaviorsToResponse(request); - Request requestInternal = (Request)request; - this.Channel.Send(requestInternal.Response); - } - - /// <summary> - /// Sends the response to a received request. - /// </summary> - /// <param name="request">The incoming OpenID request whose response is to be sent.</param> - /// <remarks> - /// <para>Requires an HttpContext.Current context. If one is not available, the caller should use - /// <see cref="PrepareResponse"/> instead and manually send the <see cref="OutgoingWebResponse"/> - /// to the client.</para> - /// </remarks> - /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception> - [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")] - public void Respond(IRequest request) { - RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired); - Requires.NotNull(request, "request"); - Requires.That(request.IsResponseReady, "request", OpenIdStrings.ResponseNotReady); - - this.ApplyBehaviorsToResponse(request); - Request requestInternal = (Request)request; - this.Channel.Respond(requestInternal.Response); - } - - /// <summary> /// Gets the response to a received request. /// </summary> /// <param name="request">The request.</param> - /// <returns>The response that should be sent to the client.</returns> - /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The response that should be sent to the client. + /// </returns> + /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady" /> is <c>false</c>.</exception> [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")] - public OutgoingWebResponse PrepareResponse(IRequest request) { + public async Task<HttpResponseMessage> PrepareResponseAsync(IRequest request, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(request, "request"); Requires.That(request.IsResponseReady, "request", OpenIdStrings.ResponseNotReady); - this.ApplyBehaviorsToResponse(request); + await this.ApplyBehaviorsToResponseAsync(request, cancellationToken); Request requestInternal = (Request)request; - return this.Channel.PrepareResponse(requestInternal.Response); - } - - /// <summary> - /// Sends an identity assertion on behalf of one of this Provider's - /// members in order to redirect the user agent to a relying party - /// web site and log him/her in immediately in one uninterrupted step. - /// </summary> - /// <param name="providerEndpoint">The absolute URL on the Provider site that receives OpenID messages.</param> - /// <param name="relyingPartyRealm">The URL of the Relying Party web site. - /// This will typically be the home page, but may be a longer URL if - /// that Relying Party considers the scope of its realm to be more specific. - /// The URL provided here must allow discovery of the Relying Party's - /// XRDS document that advertises its OpenID RP endpoint.</param> - /// <param name="claimedIdentifier">The Identifier you are asserting your member controls.</param> - /// <param name="localIdentifier">The Identifier you know your user by internally. This will typically - /// be the same as <paramref name="claimedIdentifier"/>.</param> - /// <param name="extensions">The extensions.</param> - public void SendUnsolicitedAssertion(Uri providerEndpoint, Realm relyingPartyRealm, Identifier claimedIdentifier, Identifier localIdentifier, params IExtensionMessage[] extensions) { - RequiresEx.ValidState(HttpContext.Current != null, MessagingStrings.HttpContextRequired); - Requires.NotNull(providerEndpoint, "providerEndpoint"); - Requires.That(providerEndpoint.IsAbsoluteUri, "providerEndpoint", OpenIdStrings.AbsoluteUriRequired); - Requires.NotNull(relyingPartyRealm, "relyingPartyRealm"); - Requires.NotNull(claimedIdentifier, "claimedIdentifier"); - Requires.NotNull(localIdentifier, "localIdentifier"); - - this.PrepareUnsolicitedAssertion(providerEndpoint, relyingPartyRealm, claimedIdentifier, localIdentifier, extensions).Send(); + var response = await requestInternal.GetResponseAsync(cancellationToken); + return await this.Channel.PrepareResponseAsync(response, cancellationToken); } /// <summary> @@ -401,19 +337,20 @@ namespace DotNetOpenAuth.OpenId.Provider { /// XRDS document that advertises its OpenID RP endpoint.</param> /// <param name="claimedIdentifier">The Identifier you are asserting your member controls.</param> /// <param name="localIdentifier">The Identifier you know your user by internally. This will typically - /// be the same as <paramref name="claimedIdentifier"/>.</param> + /// be the same as <paramref name="claimedIdentifier" />.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="extensions">The extensions.</param> /// <returns> - /// A <see cref="OutgoingWebResponse"/> object describing the HTTP response to send + /// A <see cref="HttpResponseMessage" /> object describing the HTTP response to send /// the user agent to allow the redirect with assertion to happen. /// </returns> - public OutgoingWebResponse PrepareUnsolicitedAssertion(Uri providerEndpoint, Realm relyingPartyRealm, Identifier claimedIdentifier, Identifier localIdentifier, params IExtensionMessage[] extensions) { + public async Task<HttpResponseMessage> PrepareUnsolicitedAssertionAsync(Uri providerEndpoint, Realm relyingPartyRealm, Identifier claimedIdentifier, Identifier localIdentifier, CancellationToken cancellationToken = default(CancellationToken), params IExtensionMessage[] extensions) { Requires.NotNull(providerEndpoint, "providerEndpoint"); Requires.That(providerEndpoint.IsAbsoluteUri, "providerEndpoint", OpenIdStrings.AbsoluteUriRequired); Requires.NotNull(relyingPartyRealm, "relyingPartyRealm"); Requires.NotNull(claimedIdentifier, "claimedIdentifier"); Requires.NotNull(localIdentifier, "localIdentifier"); - RequiresEx.ValidState(this.Channel.WebRequestHandler != null); + RequiresEx.ValidState(this.Channel.HostFactories != null); // Although the RP should do their due diligence to make sure that this OP // is authorized to send an assertion for the given claimed identifier, @@ -421,7 +358,7 @@ namespace DotNetOpenAuth.OpenId.Provider { // and make sure that it is tied to this OP and OP local identifier. if (this.SecuritySettings.UnsolicitedAssertionVerification != ProviderSecuritySettings.UnsolicitedAssertionVerificationLevel.NeverVerify) { var serviceEndpoint = IdentifierDiscoveryResult.CreateForClaimedIdentifier(claimedIdentifier, localIdentifier, new ProviderEndpointDescription(providerEndpoint, Protocol.Default.Version), null, null); - var discoveredEndpoints = this.discoveryServices.Discover(claimedIdentifier); + var discoveredEndpoints = await this.discoveryServices.DiscoverAsync(claimedIdentifier, cancellationToken); if (!discoveredEndpoints.Contains(serviceEndpoint)) { Logger.OpenId.WarnFormat( "Failed to send unsolicited assertion for {0} because its discovered services did not include this endpoint: {1}{2}{1}Discovered endpoints: {1}{3}", @@ -439,7 +376,7 @@ namespace DotNetOpenAuth.OpenId.Provider { Logger.OpenId.InfoFormat("Preparing unsolicited assertion for {0}", claimedIdentifier); RelyingPartyEndpointDescription returnToEndpoint = null; - var returnToEndpoints = relyingPartyRealm.DiscoverReturnToEndpoints(this.WebRequestHandler, true); + var returnToEndpoints = await relyingPartyRealm.DiscoverReturnToEndpointsAsync(this.Channel.HostFactories, true, cancellationToken); if (returnToEndpoints != null) { returnToEndpoint = returnToEndpoints.FirstOrDefault(); } @@ -458,7 +395,7 @@ namespace DotNetOpenAuth.OpenId.Provider { } Reporting.RecordEventOccurrence(this, "PrepareUnsolicitedAssertion"); - return this.Channel.PrepareResponse(positiveAssertion); + return await this.Channel.PrepareResponseAsync(positiveAssertion, cancellationToken); } #region IDisposable Members @@ -491,11 +428,15 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Applies all behaviors to the response message. /// </summary> /// <param name="request">The request.</param> - private void ApplyBehaviorsToResponse(IRequest request) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + private async Task ApplyBehaviorsToResponseAsync(IRequest request, CancellationToken cancellationToken) { var authRequest = request as IAuthenticationRequest; if (authRequest != null) { foreach (var behavior in this.Behaviors) { - if (behavior.OnOutgoingResponse(authRequest)) { + if (await behavior.OnOutgoingResponseAsync(authRequest, cancellationToken)) { // This behavior matched this request. break; } @@ -512,16 +453,16 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <returns> /// Either the <see cref="IRequest"/> to return to the host site or null to indicate no response could be reasonably created and that the caller should rethrow the exception. /// </returns> - private IRequest GetErrorResponse(ProtocolException ex, HttpRequestBase httpRequestInfo, IDirectedProtocolMessage incomingMessage) { + private IRequest GetErrorResponse(ProtocolException ex, HttpRequestMessage request, IDirectedProtocolMessage incomingMessage) { Requires.NotNull(ex, "ex"); - Requires.NotNull(httpRequestInfo, "httpRequestInfo"); + Requires.NotNull(request, "request"); Logger.OpenId.Error("An exception was generated while processing an incoming OpenID request.", ex); IErrorMessage errorMessage; // We must create the appropriate error message type (direct vs. indirect) // based on what we see in the request. - string returnTo = httpRequestInfo.QueryString[Protocol.Default.openid.return_to]; + string returnTo = HttpUtility.ParseQueryString(request.RequestUri.Query)[Protocol.Default.openid.return_to]; if (returnTo != null) { // An indirect request message from the RP // We need to return an indirect response error message so the RP can consume it. @@ -532,7 +473,7 @@ namespace DotNetOpenAuth.OpenId.Provider { } else { errorMessage = new IndirectErrorResponse(Protocol.Default.Version, new Uri(returnTo)); } - } else if (httpRequestInfo.HttpMethod == "POST") { + } else if (request.Method == HttpMethod.Post) { // A direct request message from the RP // We need to return a direct response error message so the RP can consume it. // Consistent with OpenID 2.0 section 5.1.2.2. diff --git a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs index ceabab3..138b814 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs +++ b/src/DotNetOpenAuth.OpenId.Provider/OpenId/Provider/Request.cs @@ -9,12 +9,14 @@ namespace DotNetOpenAuth.OpenId.Provider { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using Validation; /// <summary> - /// Implements the <see cref="IRequest"/> interface for all incoming + /// Implements the <see cref="IRequest" /> interface for all incoming /// request messages to an OpenID Provider. /// </summary> [Serializable] @@ -91,33 +93,6 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <value>Defaults to the <see cref="OpenIdProvider.SecuritySettings"/> on the <see cref="OpenIdProvider"/>.</value> public ProviderSecuritySettings SecuritySettings { get; set; } - /// <summary> - /// Gets the response to send to the user agent. - /// </summary> - /// <exception cref="InvalidOperationException">Thrown if <see cref="IsResponseReady"/> is <c>false</c>.</exception> - internal IProtocolMessage Response { - get { - RequiresEx.ValidState(this.IsResponseReady, OpenIdStrings.ResponseNotReady); - - if (this.responseExtensions.Count > 0) { - var extensibleResponse = this.ResponseMessage as IProtocolMessageWithExtensions; - ErrorUtilities.VerifyOperation(extensibleResponse != null, MessagingStrings.MessageNotExtensible, this.ResponseMessage.GetType().Name); - foreach (var extension in this.responseExtensions) { - // It's possible that a prior call to this property - // has already added some/all of the extensions to the message. - // We don't have to worry about deleting old ones because - // this class provides no facility for removing extensions - // that are previously added. - if (!extensibleResponse.Extensions.Contains(extension)) { - extensibleResponse.Extensions.Add(extension); - } - } - } - - return this.ResponseMessage; - } - } - #endregion /// <summary> @@ -129,11 +104,6 @@ namespace DotNetOpenAuth.OpenId.Provider { } /// <summary> - /// Gets the response message, once <see cref="IsResponseReady"/> is <c>true</c>. - /// </summary> - protected abstract IProtocolMessage ResponseMessage { get; } - - /// <summary> /// Gets the protocol version used in the request. /// </summary> protected Protocol Protocol { @@ -203,5 +173,40 @@ namespace DotNetOpenAuth.OpenId.Provider { } #endregion + + /// <summary> + /// Gets the response to send to the user agent. + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The response.</returns> + /// <exception cref="InvalidOperationException">Thrown if <see cref="IsResponseReady" /> is <c>false</c>.</exception> + internal async Task<IProtocolMessage> GetResponseAsync(CancellationToken cancellationToken) { + RequiresEx.ValidState(this.IsResponseReady, OpenIdStrings.ResponseNotReady); + + if (this.responseExtensions.Count > 0) { + var responseMessage = await this.GetResponseMessageAsync(cancellationToken); + var extensibleResponse = responseMessage as IProtocolMessageWithExtensions; + ErrorUtilities.VerifyOperation(extensibleResponse != null, MessagingStrings.MessageNotExtensible, responseMessage.GetType().Name); + foreach (var extension in this.responseExtensions) { + // It's possible that a prior call to this property + // has already added some/all of the extensions to the message. + // We don't have to worry about deleting old ones because + // this class provides no facility for removing extensions + // that are previously added. + if (!extensibleResponse.Extensions.Contains(extension)) { + extensibleResponse.Extensions.Add(extension); + } + } + } + + return await this.GetResponseMessageAsync(cancellationToken); + } + + /// <summary> + /// Gets the response message, once <see cref="IsResponseReady" /> is <c>true</c>. + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The response message.</returns> + protected abstract Task<IProtocolMessage> GetResponseMessageAsync(CancellationToken cancellationToken); } } diff --git a/src/DotNetOpenAuth.OpenId.Provider/packages.config b/src/DotNetOpenAuth.OpenId.Provider/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OpenId.Provider/packages.config +++ b/src/DotNetOpenAuth.OpenId.Provider/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj index 0d83940..726d25d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/DotNetOpenAuth.OpenId.RelyingParty.UI.csproj @@ -67,33 +67,35 @@ <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath> </Reference> <Reference Include="System" /> - <Reference Include="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.Helpers.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.Helpers.dll</HintPath> </Reference> - <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.Mvc.3.0.20105.1\lib\net40\System.Web.Mvc.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.Mvc.4.0.20710.0\lib\net40\System.Web.Mvc.dll</HintPath> </Reference> - <Reference Include="System.Web.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.Razor.1.0.20105.408\lib\net40\System.Web.Razor.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.Razor.2.0.20715.0\lib\net40\System.Web.Razor.dll</HintPath> </Reference> - <Reference Include="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.WebPages.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.dll</HintPath> </Reference> - <Reference Include="System.Web.WebPages.Deployment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Deployment.dll</HintPath> </Reference> - <Reference Include="System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> + <Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <Private>True</Private> - <HintPath>..\packages\Microsoft.AspNet.WebPages.1.0.20105.408\lib\net40\System.Web.WebPages.Razor.dll</HintPath> + <HintPath>..\packages\Microsoft.AspNet.WebPages.2.0.20710.0\lib\net40\System.Web.WebPages.Razor.dll</HintPath> </Reference> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs index 918efdf..52a204d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs @@ -11,11 +11,14 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Globalization; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Script.Serialization; - using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions; @@ -51,20 +54,22 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// your realm would typically be https://www.example.com/.</param> /// <param name="returnToUrl">The URL of the login page, or the page prepared to receive authentication /// responses from the OpenID Provider.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier. /// Never null, but may be empty. /// </returns> /// <remarks> - /// <para>Any individual generated request can satisfy the authentication. + /// <para>Any individual generated request can satisfy the authentication. /// The generated requests are sorted in preferred order. /// Each request is generated as it is enumerated to. Associations are created only as - /// <see cref="IAuthenticationRequest.RedirectingResponse"/> is called.</para> - /// <para>No exception is thrown if no OpenID endpoints were discovered. + /// <see cref="IAuthenticationRequest.GetRedirectingResponseAsync" /> is called.</para> + /// <para>No exception is thrown if no OpenID endpoints were discovered. /// An empty enumerable is returned instead.</para> /// </remarks> - public override IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl) { - var requests = base.CreateRequests(userSuppliedIdentifier, realm, returnToUrl); + public override async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl, CancellationToken cancellationToken) { + var requests = await base.CreateRequestsAsync(userSuppliedIdentifier, realm, returnToUrl, cancellationToken); + var results = new List<IAuthenticationRequest>(); // Alter the requests so that have AJAX characteristics. // Some OPs may be listed multiple times (one with HTTPS and the other with HTTP, for example). @@ -113,14 +118,17 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // http://www.nabble.com/Re:-Defining-how-OpenID-should-behave-with-fragments-in-the-return_to-url-p22694227.html ////TODO: - yield return req; + results.Add(req); } + + return results; } /// <summary> /// Serializes discovery results on some <i>single</i> identifier on behalf of Javascript running on the browser. /// </summary> /// <param name="requests">The discovery results from just <i>one</i> identifier to serialize as a JSON response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The JSON result to return to the user agent. /// </returns> @@ -142,13 +150,15 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// } /// </code> /// </remarks> - public OutgoingWebResponse AsAjaxDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { + public async Task<HttpResponseMessage> AsAjaxDiscoveryResultAsync(IEnumerable<IAuthenticationRequest> requests, CancellationToken cancellationToken) { Requires.NotNull(requests, "requests"); var serializer = new JavaScriptSerializer(); - return new OutgoingWebResponse { - Body = serializer.Serialize(this.AsJsonDiscoveryResult(requests)), + var response = new HttpResponseMessage { + Content = new StringContent(serializer.Serialize(await this.AsJsonDiscoveryResultAsync(requests, cancellationToken))), }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + return response; } /// <summary> @@ -156,14 +166,15 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// an AJAX-aware OpenID control. /// </summary> /// <param name="requests">The discovery results to serialize as a JSON response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The JSON result to return to the user agent. /// </returns> - public string AsAjaxPreloadedDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { + public async Task<string> AsAjaxPreloadedDiscoveryResultAsync(IEnumerable<IAuthenticationRequest> requests, CancellationToken cancellationToken) { Requires.NotNull(requests, "requests"); var serializer = new JavaScriptSerializer(); - string json = serializer.Serialize(this.AsJsonPreloadedDiscoveryResult(requests)); + string json = serializer.Serialize(await this.AsJsonPreloadedDiscoveryResultAsync(requests, cancellationToken)); string script = "window.dnoa_internal.loadPreloadedDiscoveryResults(" + json + ");"; return script; @@ -173,19 +184,29 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Converts a sequence of authentication requests to a JSON object for seeding an AJAX-enabled login page. /// </summary> /// <param name="requests">The discovery results from just <i>one</i> identifier to serialize as a JSON response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A JSON object, not yet serialized.</returns> - internal object AsJsonDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { + internal async Task<object> AsJsonDiscoveryResultAsync(IEnumerable<IAuthenticationRequest> requests, CancellationToken cancellationToken) { Requires.NotNull(requests, "requests"); requests = requests.CacheGeneratedResults(); if (requests.Any()) { + var requestUrls = + requests.Select( + req => + new { + endpoint = req.Provider.Uri.AbsoluteUri, + immediate = this.GetRedirectUrlAsync(req, true, cancellationToken), + setup = this.GetRedirectUrlAsync(req, false, cancellationToken), + }).ToList(); + await Task.WhenAll(requestUrls.Select(r => r.immediate).Concat(requestUrls.Select(r => r.setup))); return new { claimedIdentifier = (string)requests.First().ClaimedIdentifier, - requests = requests.Select(req => new { - endpoint = req.Provider.Uri.AbsoluteUri, - immediate = this.GetRedirectUrl(req, true), - setup = this.GetRedirectUrl(req, false), + requests = requestUrls.Select(req => new { + endpoint = req.endpoint, + immediate = req.immediate.Result, // await already took place + setup = req.setup.Result, // await already took place }).ToArray() }; } else { @@ -201,10 +222,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// an AJAX-aware OpenID control. /// </summary> /// <param name="requests">The discovery results to serialize as a JSON response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A JSON object, not yet serialized to a string. /// </returns> - private object AsJsonPreloadedDiscoveryResult(IEnumerable<IAuthenticationRequest> requests) { + private async Task<object> AsJsonPreloadedDiscoveryResultAsync(IEnumerable<IAuthenticationRequest> requests, CancellationToken cancellationToken) { Requires.NotNull(requests, "requests"); // We prepare a JSON object with this interface: @@ -214,13 +236,18 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // string userSuppliedIdentifier; // jsonResponse discoveryResult; // contains result of call to SerializeDiscoveryAsJson(Identifier) // } - var json = (from request in requests - group request by request.DiscoveryResult.UserSuppliedIdentifier into requestsByIdentifier - select new { - userSuppliedIdentifier = (string)requestsByIdentifier.Key, - discoveryResult = this.AsJsonDiscoveryResult(requestsByIdentifier), - }).ToArray(); - + var jsonAsync = (from request in requests + group request by request.DiscoveryResult.UserSuppliedIdentifier into requestsByIdentifier + select new { + userSuppliedIdentifier = (string)requestsByIdentifier.Key, + discoveryResult = this.AsJsonDiscoveryResultAsync(requestsByIdentifier, cancellationToken), + }).ToArray(); + await Task.WhenAll(jsonAsync.Select(j => j.discoveryResult)); + var json = from j in jsonAsync + select new { + userSuppliedIdentifier = j.userSuppliedIdentifier, + discoveryResult = j.discoveryResult.Result, // await happened previously + }; return json; } @@ -231,12 +258,16 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="request">The authentication request.</param> /// <param name="immediate"><c>true</c>to create a checkid_immediate request; /// <c>false</c> to create a checkid_setup request.</param> - /// <returns>The absolute URL that carries the entire OpenID message.</returns> - private Uri GetRedirectUrl(IAuthenticationRequest request, bool immediate) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The absolute URL that carries the entire OpenID message. + /// </returns> + private async Task<Uri> GetRedirectUrlAsync(IAuthenticationRequest request, bool immediate, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); request.Mode = immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup; - return request.RedirectingResponse.GetDirectUriRequest(this.Channel); + var response = await request.GetRedirectingResponseAsync(cancellationToken); + return response.GetDirectUriRequest(); } } } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs index b5b6162..4c988a8 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdAjaxTextBox.cs @@ -22,6 +22,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Drawing.Design; using System.Globalization; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web.UI; using System.Web.UI.HtmlControls; using DotNetOpenAuth.Messaging; @@ -716,7 +718,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { loader.insert(); } } catch (e) { }"; - this.Page.ClientScript.RegisterClientScriptInclude("yuiloader", this.Page.Request.Url.IsTransportSecure() ? YuiLoaderHttps : YuiLoaderHttp); + this.Page.ClientScript.RegisterClientScriptInclude( + "yuiloader", this.Page.Request.Url.IsTransportSecure() ? YuiLoaderHttps : YuiLoaderHttp); this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "requiredYuiComponents", yuiLoadScript, true); } @@ -737,9 +740,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // If an Identifier is preset on this control, preload discovery on that identifier, // but only if we're not already persisting an authentication result since that would // be redundant. - if (this.Identifier != null && this.AuthenticationResponse == null) { - this.PreloadDiscovery(this.Identifier); - } + this.Page.RegisterAsyncTask(new PageAsyncTask(async ct => { + var response = await this.GetAuthenticationResponseAsync(ct); + if (this.Identifier != null && response == null) { + await this.PreloadDiscoveryAsync(this.Identifier, ct); + } + })); } /// <summary> diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdButton.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdButton.cs index 505461a..d5e9e51 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdButton.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdButton.cs @@ -12,7 +12,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Drawing.Design; using System.Globalization; using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; + using System.Web; using System.Web.UI; using DotNetOpenAuth.Messaging; @@ -55,6 +59,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { #endregion /// <summary> + /// Stores the asynchronously created message that can be used to initiate a redirection-based authentication request. + /// </summary> + private HttpResponseMessage authenticationRequestRedirect; + + /// <summary> /// Initializes a new instance of the <see cref="OpenIdButton"/> class. /// </summary> public OpenIdButton() { @@ -116,12 +125,15 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="eventArgument">A <see cref="T:System.String"/> that represents an optional event argument to be passed to the event handler.</param> protected override void RaisePostBackEvent(string eventArgument) { if (!this.PrecreateRequest) { - try { - IAuthenticationRequest request = this.CreateRequests().First(); - request.RedirectToProvider(); - } catch (InvalidOperationException ex) { - throw ErrorUtilities.Wrap(ex, OpenIdStrings.OpenIdEndpointNotFound); - } + this.Page.RegisterAsyncTask(new PageAsyncTask(async ct => { + try { + var requests = await this.CreateRequestsAsync(ct); + var request = requests.First(); + await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), ct); + } catch (InvalidOperationException ex) { + throw ErrorUtilities.Wrap(ex, OpenIdStrings.OpenIdEndpointNotFound); + } + })); } } @@ -134,6 +146,15 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { if (!this.DesignMode) { ErrorUtilities.VerifyOperation(this.Identifier != null, OpenIdStrings.NoIdentifierSet); + + if (this.PrecreateRequest) { + this.Page.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var requests = await this.CreateRequestsAsync(ct); + this.authenticationRequestRedirect = await requests.FirstOrDefault().GetRedirectingResponseAsync(ct); + })); + } } } @@ -148,9 +169,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } else { string tooltip = this.Text; if (this.PrecreateRequest && !this.DesignMode) { - IAuthenticationRequest request = this.CreateRequests().FirstOrDefault(); - if (request != null) { - RenderOpenIdMessageTransmissionAsAnchorAttributes(writer, request, tooltip); + if (this.authenticationRequestRedirect != null) { + this.RenderOpenIdMessageTransmissionAsAnchorAttributes(writer, this.authenticationRequestRedirect, tooltip); } else { tooltip = OpenIdStrings.OpenIdEndpointNotFound; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs index 16f9462..2f0a65c 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs @@ -10,6 +10,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; + using System.Threading; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; @@ -934,19 +935,25 @@ idselector_input_id = '" + this.ClientID + @"'; /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void LoginButton_Click(object sender, EventArgs e) { - if (!this.Page.IsValid) { - return; - } - - IAuthenticationRequest request = this.CreateRequests().FirstOrDefault(); - if (request != null) { - this.LogOn(request); - } else { - if (!string.IsNullOrEmpty(this.FailedMessageText)) { - this.errorLabel.Text = string.Format(CultureInfo.CurrentCulture, this.FailedMessageText, OpenIdStrings.OpenIdEndpointNotFound); - this.errorLabel.Visible = true; - } - } + this.Page.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!this.Page.IsValid) { + return; + } + + var authenticationRequests = await this.CreateRequestsAsync(CancellationToken.None); + IAuthenticationRequest request = authenticationRequests.FirstOrDefault(); + if (request != null) { + await this.LogOnAsync(request, CancellationToken.None); + } else { + if (!string.IsNullOrEmpty(this.FailedMessageText)) { + this.errorLabel.Text = string.Format( + CultureInfo.CurrentCulture, this.FailedMessageText, OpenIdStrings.OpenIdEndpointNotFound); + this.errorLabel.Visible = true; + } + } + })); } /// <summary> diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs index 9b4d271..d7a052d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs @@ -13,7 +13,10 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; @@ -65,7 +68,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { private const string AuthDataViewStateKey = "AuthData"; /// <summary> - /// The viewstate key to use for storing the value of the <see cref="AuthenticationResponse"/> property. + /// The viewstate key to use for storing the value of the <see cref="GetAuthenticationResponseAsync"/> method. /// </summary> private const string AuthenticationResponseViewStateKey = "AuthenticationResponse"; @@ -167,43 +170,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> - /// Gets the completed authentication response. - /// </summary> - public IAuthenticationResponse AuthenticationResponse { - get { - if (this.authenticationResponse == null) { - // We will either validate a new response and return a live AuthenticationResponse - // or we will try to deserialize a previous IAuthenticationResponse (snapshot) - // from viewstate and return that. - IAuthenticationResponse viewstateResponse = this.ViewState[AuthenticationResponseViewStateKey] as IAuthenticationResponse; - string viewstateAuthData = this.ViewState[AuthDataViewStateKey] as string; - string formAuthData = this.Page.Request.Form[this.OpenIdAuthDataFormKey]; - - // First see if there is fresh auth data to be processed into a response. - if (!string.IsNullOrEmpty(formAuthData) && !string.Equals(viewstateAuthData, formAuthData, StringComparison.Ordinal)) { - this.ViewState[AuthDataViewStateKey] = formAuthData; - - HttpRequestBase clientResponseInfo = new HttpRequestInfo("GET", new Uri(formAuthData)); - this.authenticationResponse = this.RelyingParty.GetResponse(clientResponseInfo); - Logger.Controls.DebugFormat( - "The {0} control checked for an authentication response and found: {1}", - this.ID, - this.authenticationResponse.Status); - this.AuthenticationProcessedAlready = false; - - // Save out the authentication response to viewstate so we can find it on - // a subsequent postback. - this.ViewState[AuthenticationResponseViewStateKey] = new PositiveAuthenticationResponseSnapshot(this.authenticationResponse); - } else { - this.authenticationResponse = viewstateResponse; - } - } - - return this.authenticationResponse; - } - } - - /// <summary> /// Gets the relying party as its AJAX type. /// </summary> protected OpenIdAjaxRelyingParty AjaxRelyingParty { @@ -226,6 +192,43 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> + /// Gets the completed authentication response. + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The response message.</returns> + public async Task<IAuthenticationResponse> GetAuthenticationResponseAsync(CancellationToken cancellationToken) { + if (this.authenticationResponse == null) { + // We will either validate a new response and return a live AuthenticationResponse + // or we will try to deserialize a previous IAuthenticationResponse (snapshot) + // from viewstate and return that. + IAuthenticationResponse viewstateResponse = this.ViewState[AuthenticationResponseViewStateKey] as IAuthenticationResponse; + string viewstateAuthData = this.ViewState[AuthDataViewStateKey] as string; + string formAuthData = this.Page.Request.Form[this.OpenIdAuthDataFormKey]; + + // First see if there is fresh auth data to be processed into a response. + if (!string.IsNullOrEmpty(formAuthData) && !string.Equals(viewstateAuthData, formAuthData, StringComparison.Ordinal)) { + this.ViewState[AuthDataViewStateKey] = formAuthData; + + HttpRequestBase clientResponseInfo = new HttpRequestInfo("GET", new Uri(formAuthData)); + this.authenticationResponse = await this.RelyingParty.GetResponseAsync(clientResponseInfo, cancellationToken); + Logger.Controls.DebugFormat( + "The {0} control checked for an authentication response and found: {1}", + this.ID, + this.authenticationResponse.Status); + this.AuthenticationProcessedAlready = false; + + // Save out the authentication response to viewstate so we can find it on + // a subsequent postback. + this.ViewState[AuthenticationResponseViewStateKey] = new PositiveAuthenticationResponseSnapshot(this.authenticationResponse); + } else { + this.authenticationResponse = viewstateResponse; + } + } + + return this.authenticationResponse; + } + + /// <summary> /// Allows an OpenID extension to read data out of an unverified positive authentication assertion /// and send it down to the client browser so that Javascript running on the page can perform /// some preprocessing on the extension data. @@ -278,7 +281,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Processes a callback event that targets a control. /// </summary> /// <param name="eventArgument">A string that represents an event argument to pass to the event handler.</param> - [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", Justification = "We want to preserve the signature of the interface.")] + [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", + Justification = "We want to preserve the signature of the interface.")] protected virtual void RaiseCallbackEvent(string eventArgument) { string userSuppliedIdentifier = eventArgument; @@ -287,9 +291,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { this.Identifier = userSuppliedIdentifier; - var serializer = new JavaScriptSerializer(); - IEnumerable<IAuthenticationRequest> requests = this.CreateRequests(this.Identifier); - this.discoveryResult = serializer.Serialize(this.AjaxRelyingParty.AsJsonDiscoveryResult(requests)); + this.Page.RegisterAsyncTask(new PageAsyncTask(async ct => { + var serializer = new JavaScriptSerializer(); + IEnumerable<IAuthenticationRequest> requests = await this.CreateRequestsAsync(this.Identifier, ct); + this.discoveryResult = serializer.Serialize(await this.AjaxRelyingParty.AsJsonDiscoveryResultAsync(requests, ct)); + })); } /// <summary> @@ -306,8 +312,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// user agent for javascript as soon as the page loads. /// </summary> /// <param name="identifier">The identifier.</param> - protected void PreloadDiscovery(Identifier identifier) { - this.PreloadDiscovery(new[] { identifier }); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + protected Task PreloadDiscoveryAsync(Identifier identifier, CancellationToken cancellationToken) { + return this.PreloadDiscoveryAsync(new[] { identifier }, cancellationToken); } /// <summary> @@ -315,9 +325,13 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// user agent for javascript as soon as the page loads. /// </summary> /// <param name="identifiers">The identifiers to perform discovery on.</param> - protected void PreloadDiscovery(IEnumerable<Identifier> identifiers) { - string script = this.AjaxRelyingParty.AsAjaxPreloadedDiscoveryResult( - identifiers.SelectMany(id => this.CreateRequests(id))); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + protected async Task PreloadDiscoveryAsync(IEnumerable<Identifier> identifiers, CancellationToken cancellationToken) { + var requests = await Task.WhenAll(identifiers.Select(id => this.CreateRequestsAsync(id, cancellationToken))); + string script = await this.AjaxRelyingParty.AsAjaxPreloadedDiscoveryResultAsync(requests.SelectMany(r => r), cancellationToken); this.Page.ClientScript.RegisterClientScriptBlock(typeof(OpenIdRelyingPartyAjaxControlBase), this.ClientID, script, true); } @@ -342,15 +356,18 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // but our AJAX controls hide an old OpenID message in a postback payload, // so we deserialize it and process it when appropriate. if (this.Page.IsPostBack) { - if (this.AuthenticationResponse != null && !this.AuthenticationProcessedAlready) { - // Only process messages targeted at this control. - // Note that Stateless mode causes no receiver to be indicated. - string receiver = this.AuthenticationResponse.GetUntrustedCallbackArgument(ReturnToReceivingControlId); - if (receiver == null || receiver == this.ClientID) { - this.ProcessResponse(this.AuthenticationResponse); - this.AuthenticationProcessedAlready = true; + this.Page.RegisterAsyncTask(new PageAsyncTask(async ct => { + var response = await this.GetAuthenticationResponseAsync(ct); + if (response != null && !this.AuthenticationProcessedAlready) { + // Only process messages targeted at this control. + // Note that Stateless mode causes no receiver to be indicated. + string receiver = response.GetUntrustedCallbackArgument(ReturnToReceivingControlId); + if (receiver == null || receiver == this.ClientID) { + this.ProcessResponse(response); + this.AuthenticationProcessedAlready = true; + } } - } + })); } } @@ -413,18 +430,24 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <summary> /// Notifies the user agent via an AJAX response of a completed authentication attempt. /// </summary> - protected override void ScriptClosingPopupOrIFrame() { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + protected override async Task ScriptClosingPopupOrIFrameAsync(CancellationToken cancellationToken) { Action<AuthenticationStatus> callback = status => { if (status == AuthenticationStatus.Authenticated) { this.OnUnconfirmedPositiveAssertion(); // event handler will fill the clientScriptExtensions collection. } }; - OutgoingWebResponse response = this.RelyingParty.ProcessResponseFromPopup( - this.RelyingParty.Channel.GetRequestFromContext(), - callback); + HttpResponseMessage response = await this.RelyingParty.ProcessResponseFromPopupAsync( + new HttpRequestWrapper(this.Context.Request).AsHttpRequestMessage(), + callback, + cancellationToken); - response.Send(); + await response.SendAsync(new HttpContextWrapper(this.Context), cancellationToken); + this.Context.Response.End(); } /// <summary> diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs index 7d616d2..77a5b44 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs @@ -15,8 +15,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Drawing.Design; using System.Globalization; using System.Linq; + using System.Net.Http; using System.Text; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Security; using System.Web.UI; @@ -363,7 +366,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { if (Page != null && !DesignMode) { // Validate new value by trying to construct a Realm object based on it. - new Realm(OpenIdUtilities.GetResolvedRealm(this.Page, value, this.RelyingParty.Channel.GetRequestFromContext())); // throws an exception on failure. + new Realm(OpenIdUtilities.GetResolvedRealm(this.Page, value, new HttpRequestWrapper(this.Context.Request))); // throws an exception on failure. } else { // We can't fully test it, but it should start with either ~/ or a protocol. if (Regex.IsMatch(value, @"^https?://")) { @@ -395,7 +398,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { set { if (this.Page != null && !this.DesignMode) { // Validate new value by trying to construct a Uri based on it. - new Uri(this.RelyingParty.Channel.GetRequestFromContext().GetPublicFacingUrl(), this.Page.ResolveUrl(value)); // throws an exception on failure. + new Uri(new HttpRequestWrapper(this.Context.Request).GetPublicFacingUrl(), this.Page.ResolveUrl(value)); // throws an exception on failure. } else { // We can't fully test it, but it should start with either ~/ or a protocol. if (Regex.IsMatch(value, @"^https?://")) { @@ -510,10 +513,15 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Immediately redirects to the OpenID Provider to verify the Identifier /// provided in the text box. /// </summary> - public void LogOn() { - IAuthenticationRequest request = this.CreateRequests().FirstOrDefault(); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public async Task LogOnAsync(CancellationToken cancellationToken) { + var authenticationRequests = await this.CreateRequestsAsync(cancellationToken); + IAuthenticationRequest request = authenticationRequests.FirstOrDefault(); ErrorUtilities.VerifyProtocol(request != null, OpenIdStrings.OpenIdEndpointNotFound); - this.LogOn(request); + await this.LogOnAsync(request, cancellationToken); } /// <summary> @@ -521,13 +529,17 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// provided in the text box. /// </summary> /// <param name="request">The request.</param> - public void LogOn(IAuthenticationRequest request) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public async Task LogOnAsync(IAuthenticationRequest request, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); if (this.IsPopupAppropriate(request)) { - this.ScriptPopupWindow(request); + await this.ScriptPopupWindowAsync(request, cancellationToken); } else { - request.RedirectToProvider(); + await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), cancellationToken); } } @@ -557,21 +569,22 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Creates the authentication requests for a given user-supplied Identifier. /// </summary> /// <param name="identifier">The identifier to create a request for.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any one of which may be - /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>. + /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier" />. /// </returns> - protected internal virtual IEnumerable<IAuthenticationRequest> CreateRequests(Identifier identifier) { + protected internal virtual Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier identifier, CancellationToken cancellationToken) { Requires.NotNull(identifier, "identifier"); // If this control is actually a member of another OpenID RP control, // delegate creation of requests to the parent control. var parentOwner = this.ParentControls.OfType<OpenIdRelyingPartyControlBase>().FirstOrDefault(); if (parentOwner != null) { - return parentOwner.CreateRequests(identifier); + return parentOwner.CreateRequestsAsync(identifier, cancellationToken); } else { // Delegate to a private method to keep 'yield return' and Code Contract separate. - return this.CreateRequestsCore(identifier); + return this.CreateRequestsCoreAsync(identifier, cancellationToken); } } @@ -597,15 +610,16 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> - /// Creates the authentication requests for the value set in the <see cref="Identifier"/> property. + /// Creates the authentication requests for the value set in the <see cref="Identifier" /> property. /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any one of which may be - /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>. + /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier" />. /// </returns> - protected IEnumerable<IAuthenticationRequest> CreateRequests() { + protected Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(CancellationToken cancellationToken) { RequiresEx.ValidState(this.Identifier != null, OpenIdStrings.NoIdentifierSet); - return this.CreateRequests(this.Identifier); + return this.CreateRequestsAsync(this.Identifier, cancellationToken); } /// <summary> @@ -626,33 +640,44 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // Take an unreliable sneek peek to see if we're in a popup and an OpenID // assertion is coming in. We shouldn't process assertions in a popup window. - if (this.Page.Request.QueryString[UIPopupCallbackKey] == "1" && this.Page.Request.QueryString[UIPopupCallbackParentKey] == null) { + if (this.Page.Request.QueryString[UIPopupCallbackKey] == "1" + && this.Page.Request.QueryString[UIPopupCallbackParentKey] == null) { // We're in a popup window. We need to close it and pass the // message back to the parent window for processing. - this.ScriptClosingPopupOrIFrame(); - return; // don't do any more processing on it now - } - - // Only sniff for an OpenID response if it is targeted at this control. - // Note that Stateless mode causes no receiver to be indicated, and - // we want to handle that, but only if there isn't a parent control that - // will be handling that. - string receiver = this.Page.Request.QueryString[ReturnToReceivingControlId] ?? this.Page.Request.Form[ReturnToReceivingControlId]; - if (receiver == this.ClientID || (receiver == null && !this.IsEmbeddedInParentOpenIdControl)) { - var response = this.RelyingParty.GetResponse(); - Logger.Controls.DebugFormat( - "The {0} control checked for an authentication response and found: {1}", - this.ID, - response != null ? response.Status.ToString() : "nothing"); - this.ProcessResponse(response); + this.Page.RegisterAsyncTask(new PageAsyncTask(async ct => { + await this.ScriptClosingPopupOrIFrameAsync(ct); + })); + } else { + // Only sniff for an OpenID response if it is targeted at this control. + // Note that Stateless mode causes no receiver to be indicated, and + // we want to handle that, but only if there isn't a parent control that + // will be handling that. + string receiver = this.Page.Request.QueryString[ReturnToReceivingControlId] + ?? this.Page.Request.Form[ReturnToReceivingControlId]; + if (receiver == this.ClientID || (receiver == null && !this.IsEmbeddedInParentOpenIdControl)) { + this.Page.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + var response = await this.RelyingParty.GetResponseAsync(new HttpRequestWrapper(this.Context.Request), ct); + Logger.Controls.DebugFormat( + "The {0} control checked for an authentication response and found: {1}", + this.ID, + response != null ? response.Status.ToString() : "nothing"); + this.ProcessResponse(response); + })); + } } } /// <summary> /// Notifies the user agent via an AJAX response of a completed authentication attempt. /// </summary> - protected virtual void ScriptClosingPopupOrIFrame() { - this.RelyingParty.ProcessResponseFromPopup(); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + protected virtual Task ScriptClosingPopupOrIFrameAsync(CancellationToken cancellationToken) { + return this.RelyingParty.ProcessResponseFromPopupAsync(new HttpRequestWrapper(this.Context.Request).AsHttpRequestMessage(), cancellationToken); } /// <summary> @@ -792,7 +817,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <returns>The instantiated relying party.</returns> protected OpenIdRelyingParty CreateRelyingParty() { - IOpenIdApplicationStore store = this.Stateless ? null : OpenIdElement.Configuration.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore); + IOpenIdApplicationStore store = this.Stateless ? null : OpenIdElement.Configuration.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.GetHttpApplicationStore(new HttpContextWrapper(this.Context)), null); return this.CreateRelyingParty(store); } @@ -843,21 +868,21 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> - /// Adds attributes to an HTML <A> tag that will be written by the caller using - /// <see cref="HtmlTextWriter.RenderBeginTag(HtmlTextWriterTag)"/> after this method. + /// Adds attributes to an HTML <A> tag that will be written by the caller using + /// <see cref="HtmlTextWriter.RenderBeginTag(HtmlTextWriterTag)" /> after this method. /// </summary> /// <param name="writer">The HTML writer.</param> - /// <param name="request">The outgoing authentication request.</param> + /// <param name="response">The response.</param> /// <param name="windowStatus">The text to try to display in the status bar on mouse hover.</param> - protected void RenderOpenIdMessageTransmissionAsAnchorAttributes(HtmlTextWriter writer, IAuthenticationRequest request, string windowStatus) { + protected void RenderOpenIdMessageTransmissionAsAnchorAttributes(HtmlTextWriter writer, HttpResponseMessage response, string windowStatus) { Requires.NotNull(writer, "writer"); - Requires.NotNull(request, "request"); + Requires.NotNull(response, "response"); // We render a standard HREF attribute for non-javascript browsers. - writer.AddAttribute(HtmlTextWriterAttribute.Href, request.RedirectingResponse.GetDirectUriRequest(this.RelyingParty.Channel).AbsoluteUri); + writer.AddAttribute(HtmlTextWriterAttribute.Href, response.GetDirectUriRequest().AbsoluteUri); // And for the Javascript ones we do the extra work to use form POST where necessary. - writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.CreateGetOrPostAHrefValue(request) + " return false;"); + writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.CreateGetOrPostAHrefValue(response) + " return false;"); writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer"); if (!string.IsNullOrEmpty(windowStatus)) { @@ -906,20 +931,23 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Creates the authentication requests for a given user-supplied Identifier. /// </summary> /// <param name="identifier">The identifier to create a request for.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any one of which may be - /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>. + /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier" />. /// </returns> - private IEnumerable<IAuthenticationRequest> CreateRequestsCore(Identifier identifier) { + private async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsCoreAsync(Identifier identifier, CancellationToken cancellationToken) { ErrorUtilities.VerifyArgumentNotNull(identifier, "identifier"); // NO CODE CONTRACTS! (yield return used here) IEnumerable<IAuthenticationRequest> requests; + var requestContext = new HttpRequestWrapper(this.Context.Request); + var results = new List<IAuthenticationRequest>(); // Approximate the returnTo (either based on the customize property or the page URL) // so we can use it to help with Realm resolution. Uri returnToApproximation; if (this.ReturnToUrl != null) { string returnToResolvedPath = this.ResolveUrl(this.ReturnToUrl); - returnToApproximation = new Uri(this.RelyingParty.Channel.GetRequestFromContext().GetPublicFacingUrl(), returnToResolvedPath); + returnToApproximation = new Uri(requestContext.GetPublicFacingUrl(), returnToResolvedPath); } else { returnToApproximation = this.Page.Request.Url; } @@ -927,7 +955,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // Resolve the trust root, and swap out the scheme and port if necessary to match the // return_to URL, since this match is required by OpenID, and the consumer app // may be using HTTP at some times and HTTPS at others. - UriBuilder realm = OpenIdUtilities.GetResolvedRealm(this.Page, this.RealmUrl, this.RelyingParty.Channel.GetRequestFromContext()); + UriBuilder realm = OpenIdUtilities.GetResolvedRealm(this.Page, this.RealmUrl, requestContext); realm.Scheme = returnToApproximation.Scheme; realm.Port = returnToApproximation.Port; @@ -936,11 +964,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // might slip through our validator control if it is disabled. Realm typedRealm = new Realm(realm); if (string.IsNullOrEmpty(this.ReturnToUrl)) { - requests = this.RelyingParty.CreateRequests(identifier, typedRealm); + requests = await this.RelyingParty.CreateRequestsAsync(identifier, typedRealm, requestContext); } else { // Since the user actually gave us a return_to value, // the "approximation" is exactly what we want. - requests = this.RelyingParty.CreateRequests(identifier, typedRealm, returnToApproximation); + requests = await this.RelyingParty.CreateRequestsAsync(identifier, typedRealm, returnToApproximation, cancellationToken); } // Some OPs may be listed multiple times (one with HTTPS and the other with HTTP, for example). @@ -993,20 +1021,24 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // change its value and have that value saved. req.SetUntrustedCallbackArgument(UsePersistentCookieCallbackKey, this.UsePersistentCookie.ToString()); - yield return req; + results.Add(req); } } + + return results; } /// <summary> /// Gets the javascript to executee to redirect or POST an OpenID message to a remote party. /// </summary> - /// <param name="request">The authentication request to send.</param> - /// <returns>The javascript that should execute.</returns> - private string CreateGetOrPostAHrefValue(IAuthenticationRequest request) { - Requires.NotNull(request, "request"); + /// <param name="requestRedirectingResponse">The request redirecting response.</param> + /// <returns> + /// The javascript that should execute. + /// </returns> + private string CreateGetOrPostAHrefValue(HttpResponseMessage requestRedirectingResponse) { + Requires.NotNull(requestRedirectingResponse, "requestRedirectingResponse"); - Uri directUri = request.RedirectingResponse.GetDirectUriRequest(this.RelyingParty.Channel); + Uri directUri = requestRedirectingResponse.GetDirectUriRequest(); return "window.dnoa_internal.GetOrPost(" + MessagingUtilities.GetSafeJavascriptValue(directUri.AbsoluteUri) + ");"; } @@ -1014,7 +1046,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Wires the return page to immediately display a popup window with the Provider in it. /// </summary> /// <param name="request">The request.</param> - private void ScriptPopupWindow(IAuthenticationRequest request) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + private async Task ScriptPopupWindowAsync(IAuthenticationRequest request, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); RequiresEx.ValidState(this.RelyingParty != null); @@ -1027,7 +1063,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { startupScript.AppendLine("window.dnoa_internal.popupWindow = function() {"); startupScript.AppendFormat( @"\tvar openidPopup = {0}", - OpenId.RelyingParty.Extensions.UI.UIUtilities.GetWindowPopupScript(this.RelyingParty, request, "openidPopup")); + await OpenId.RelyingParty.Extensions.UI.UIUtilities.GetWindowPopupScriptAsync(this.RelyingParty, request, "openidPopup", cancellationToken)); startupScript.AppendLine("};"); this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "loginPopup", startupScript.ToString(), true); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.cs index 7881a8b..47984b4 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdSelector.cs @@ -16,6 +16,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.IdentityModel.Claims; using System.Linq; using System.Text; + using System.Threading; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; @@ -317,7 +318,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { this.positiveAssertionField.ClientID); this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Postback", script, true); - this.PreloadDiscovery(this.Buttons.OfType<SelectorProviderButton>().Select(op => op.OPIdentifier).Where(id => id != null)); + this.Page.RegisterAsyncTask(new PageAsyncTask(async ct => { + await this.PreloadDiscoveryAsync( + this.Buttons.OfType<SelectorProviderButton>().Select(op => op.OPIdentifier).Where(id => id != null), + ct); + })); this.textBox.Visible = this.OpenIdTextBoxVisible; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs index 7474854..d566afa 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdTextBox.cs @@ -20,6 +20,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Net; using System.Text; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.Security; using System.Web.UI; @@ -546,16 +548,17 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Creates the authentication requests for a given user-supplied Identifier. /// </summary> /// <param name="identifier">The identifier to create a request for.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any one of which may be - /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier"/>. + /// used to determine the user's control of the <see cref="IAuthenticationRequest.ClaimedIdentifier" />. /// </returns> - protected internal override IEnumerable<IAuthenticationRequest> CreateRequests(Identifier identifier) { + protected internal override async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier identifier, CancellationToken cancellationToken) { ErrorUtilities.VerifyArgumentNotNull(identifier, "identifier"); // We delegate all our logic to another method, since invoking base. methods // within an iterator method results in unverifiable code. - return this.CreateRequestsCore(base.CreateRequests(identifier)); + return this.CreateRequestsCore(await base.CreateRequestsAsync(identifier, cancellationToken)); } /// <summary> @@ -696,7 +699,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { Language = this.RequestLanguage, TimeZone = this.RequestTimeZone, PolicyUrl = string.IsNullOrEmpty(this.PolicyUrl) ? - null : new Uri(this.RelyingParty.Channel.GetRequestFromContext().GetPublicFacingUrl(), this.Page.ResolveUrl(this.PolicyUrl)), + null : new Uri(new HttpRequestWrapper(this.Context.Request).GetPublicFacingUrl(), this.Page.ResolveUrl(this.PolicyUrl)), }; // Only actually add the extension request if fields are actually being requested. diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/packages.config b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/packages.config index e68b4a4..442617c 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/packages.config +++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/packages.config @@ -1,8 +1,9 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Microsoft.AspNet.Mvc" version="3.0.20105.1" targetFramework="net45" /> - <package id="Microsoft.AspNet.Razor" version="1.0.20105.408" targetFramework="net45" /> - <package id="Microsoft.AspNet.WebPages" version="1.0.20105.408" targetFramework="net45" /> + <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Razor" version="2.0.20715.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj b/src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj index 43fd0ae..8177049 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/DotNetOpenAuth.OpenId.RelyingParty.csproj @@ -79,9 +79,11 @@ </ItemGroup> <ItemGroup> <Reference Include="System" /> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs index e65409a..f9c91b6 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/OpenIdRelyingPartyChannel.cs @@ -20,26 +20,28 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </summary> internal class OpenIdRelyingPartyChannel : OpenIdChannel { /// <summary> - /// Initializes a new instance of the <see cref="OpenIdRelyingPartyChannel"/> class. + /// Initializes a new instance of the <see cref="OpenIdRelyingPartyChannel" /> class. /// </summary> /// <param name="cryptoKeyStore">The association store to use.</param> /// <param name="nonceStore">The nonce store to use.</param> /// <param name="securitySettings">The security settings to apply.</param> - internal OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings) - : this(cryptoKeyStore, nonceStore, new OpenIdRelyingPartyMessageFactory(), securitySettings, false) { + /// <param name="hostFactories">The host factories.</param> + internal OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings, IHostFactories hostFactories) + : this(cryptoKeyStore, nonceStore, new OpenIdRelyingPartyMessageFactory(), securitySettings, false, hostFactories) { Requires.NotNull(securitySettings, "securitySettings"); } /// <summary> - /// Initializes a new instance of the <see cref="OpenIdRelyingPartyChannel"/> class. + /// Initializes a new instance of the <see cref="OpenIdRelyingPartyChannel" /> class. /// </summary> /// <param name="cryptoKeyStore">The association store to use.</param> /// <param name="nonceStore">The nonce store to use.</param> /// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param> /// <param name="securitySettings">The security settings to apply.</param> /// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param> - private OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, RelyingPartySecuritySettings securitySettings, bool nonVerifying) : - base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings, nonVerifying)) { + /// <param name="hostFactories">The host factories.</param> + private OpenIdRelyingPartyChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, RelyingPartySecuritySettings securitySettings, bool nonVerifying, IHostFactories hostFactories) : + base(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings, nonVerifying), hostFactories) { Requires.NotNull(messageTypeProvider, "messageTypeProvider"); Requires.NotNull(securitySettings, "securitySettings"); Assumes.True(!nonVerifying || securitySettings is RelyingPartySecuritySettings); @@ -58,7 +60,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// messages, and will validate them later.</para> /// </remarks> internal static OpenIdChannel CreateNonVerifyingChannel() { - return new OpenIdRelyingPartyChannel(null, null, new OpenIdRelyingPartyMessageFactory(), new RelyingPartySecuritySettings(), true); + return new OpenIdRelyingPartyChannel(null, null, new OpenIdRelyingPartyMessageFactory(), new RelyingPartySecuritySettings(), true, new DefaultOpenIdHostFactories()); } /// <summary> diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySecurityOptions.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySecurityOptions.cs index b9328dd..b3a3f79 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySecurityOptions.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySecurityOptions.cs @@ -5,6 +5,8 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.OpenId.ChannelElements { + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.RelyingParty; @@ -14,6 +16,17 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </summary> internal class RelyingPartySecurityOptions : IChannelBindingElement { /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NoneTask = + Task.FromResult<MessageProtections?>(MessageProtections.None); + + /// <summary> /// The security settings that are active on the relying party. /// </summary> private RelyingPartySecuritySettings securitySettings; @@ -50,6 +63,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -58,8 +72,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { - return null; + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { + return NullTask; } /// <summary> @@ -67,6 +81,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -79,7 +94,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var positiveAssertion = message as PositiveAssertionResponse; if (positiveAssertion != null) { ErrorUtilities.VerifyProtocol( @@ -87,10 +102,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { positiveAssertion.LocalIdentifier == positiveAssertion.ClaimedIdentifier, OpenIdStrings.DelegatingIdentifiersNotAllowed); - return MessageProtections.None; + return NoneTask; } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs index 3ec2eee..625a7e4 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/RelyingPartySigningBindingElement.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId.Messages; @@ -75,15 +77,16 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="message">The message.</param> /// <param name="signedMessage">The signed message.</param> /// <param name="protectionsApplied">The protections applied.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The applied protections. /// </returns> - protected override MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied) { + protected override async Task<MessageProtections> VerifySignatureByUnrecognizedHandleAsync(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied, CancellationToken cancellationToken) { // We did not recognize the association the provider used to sign the message. // Ask the provider to check the signature then. var indirectSignedResponse = (IndirectSignedResponse)signedMessage; var checkSignatureRequest = new CheckAuthenticationRequest(indirectSignedResponse, this.Channel); - var checkSignatureResponse = this.Channel.Request<CheckAuthenticationResponse>(checkSignatureRequest); + var checkSignatureResponse = await this.Channel.RequestAsync<CheckAuthenticationResponse>(checkSignatureRequest, cancellationToken); if (!checkSignatureResponse.IsValid) { Logger.Bindings.Error("Provider reports signature verification failed."); throw new InvalidSignatureException(message); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs index c459487..a919560 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/ChannelElements/ReturnToNonceBindingElement.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId.Messages; @@ -47,6 +49,17 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </remarks> internal class ReturnToNonceBindingElement : IChannelBindingElement { /// <summary> + /// A reusable, precompleted task that can be returned many times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A reusable, precompleted task that can be returned many times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> ReplayProtectionTask = + Task.FromResult<MessageProtections?>(MessageProtections.ReplayProtection); + + /// <summary> /// The context within which return_to nonces must be unique -- they all go into the same bucket. /// </summary> private const string ReturnToNonceContext = "https://localhost/dnoa/return_to_nonce"; @@ -128,6 +141,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -136,17 +150,17 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { // We only add a nonce to some auth requests. SignedResponseRequest request = message as SignedResponseRequest; if (this.UseRequestNonce(request)) { request.AddReturnToArguments(Protocol.ReturnToNonceParameter, CustomNonce.NewNonce().Serialize()); request.SignReturnTo = true; // a nonce without a signature is completely pointless - return MessageProtections.ReplayProtection; + return ReplayProtectionTask; } - return null; + return NullTask; } /// <summary> @@ -154,6 +168,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -166,7 +181,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { IndirectSignedResponse response = message as IndirectSignedResponse; if (this.UseRequestNonce(response)) { if (!response.ReturnToParametersSignatureValidated) { @@ -190,10 +205,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { throw new ReplayedMessageException(message); } - return MessageProtections.ReplayProtection; + return ReplayProtectionTask; } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs index 1871f19..80a1665 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/HostMetaDiscoveryService.cs @@ -13,12 +13,17 @@ namespace DotNetOpenAuth.OpenId { using System.IO; using System.Linq; using System.Net; + using System.Net.Cache; + using System.Net.Http; + using System.Net.Http.Headers; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; using DotNetOpenAuth.Configuration; @@ -37,7 +42,7 @@ namespace DotNetOpenAuth.OpenId { /// and the XMLDSig spec referenced in that spec can be found at: /// http://wiki.oasis-open.org/xri/XrdOne/XmlDsigProfile /// </remarks> - public class HostMetaDiscoveryService : IIdentifierDiscoveryService { + public class HostMetaDiscoveryService : IIdentifierDiscoveryService, IRequireHostFactories { /// <summary> /// The URI template for discovery host-meta on domains hosted by /// Google Apps for Domains. @@ -67,6 +72,14 @@ namespace DotNetOpenAuth.OpenId { } /// <summary> + /// Gets or sets the host factories used by this instance. + /// </summary> + /// <value> + /// The host factories. + /// </value> + public IHostFactories HostFactories { get; set; } + + /// <summary> /// Gets the set of URI templates to use to contact host-meta hosting proxies /// for domain discovery. /// </summary> @@ -101,32 +114,33 @@ namespace DotNetOpenAuth.OpenId { /// Performs discovery on the specified identifier. /// </summary> /// <param name="identifier">The identifier to perform discovery on.</param> - /// <param name="requestHandler">The means to place outgoing HTTP requests.</param> - /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty. /// </returns> - public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) { - abortDiscoveryChain = false; + public async Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) { + Requires.NotNull(identifier, "identifier"); + Verify.Operation(this.HostFactories != null, Strings.HostFactoriesRequired); + cancellationToken.ThrowIfCancellationRequested(); // Google Apps are always URIs -- not XRIs. var uriIdentifier = identifier as UriIdentifier; if (uriIdentifier == null) { - return Enumerable.Empty<IdentifierDiscoveryResult>(); + return new IdentifierDiscoveryServiceResult(Enumerable.Empty<IdentifierDiscoveryResult>()); } var results = new List<IdentifierDiscoveryResult>(); - string signingHost; - using (var response = GetXrdsResponse(uriIdentifier, requestHandler, out signingHost)) { - if (response != null) { + using (var response = await this.GetXrdsResponseAsync(uriIdentifier, cancellationToken)) { + if (response.Result != null) { try { var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings(); - var document = new XrdsDocument(XmlReader.Create(response.ResponseStream, readerSettings)); - ValidateXmlDSig(document, uriIdentifier, response, signingHost); + var responseStream = await response.Result.Content.ReadAsStreamAsync(); + var document = new XrdsDocument(XmlReader.Create(responseStream, readerSettings)); + await ValidateXmlDSigAsync(document, uriIdentifier, response.Result, response.SigningHost); var xrds = GetXrdElements(document, uriIdentifier.Uri.Host); // Look for claimed identifier template URIs for an additional XRDS document. - results.AddRange(GetExternalServices(xrds, uriIdentifier, requestHandler)); + results.AddRange(await this.GetExternalServicesAsync(xrds, uriIdentifier, cancellationToken)); // If we couldn't find any claimed identifiers, look for OP identifiers. // Normally this would be the opposite (OP Identifiers take precedence over @@ -136,15 +150,13 @@ namespace DotNetOpenAuth.OpenId { if (results.Count == 0) { results.AddRange(xrds.CreateServiceEndpoints(uriIdentifier, uriIdentifier)); } - - abortDiscoveryChain = true; } catch (XmlException ex) { - Logger.Yadis.ErrorFormat("Error while parsing XRDS document at {0} pointed to by host-meta: {1}", response.FinalUri, ex); + Logger.Yadis.ErrorFormat("Error while parsing XRDS document at {0} pointed to by host-meta: {1}", response.Result.RequestMessage.RequestUri, ex); } } } - return results; + return new IdentifierDiscoveryServiceResult(results, abortDiscoveryChain: true); } #endregion @@ -175,52 +187,18 @@ namespace DotNetOpenAuth.OpenId { } /// <summary> - /// Gets the services for an identifier that are described by an external XRDS document. - /// </summary> - /// <param name="xrds">The XRD elements to search for described-by services.</param> - /// <param name="identifier">The identifier under discovery.</param> - /// <param name="requestHandler">The request handler.</param> - /// <returns>The discovered services.</returns> - private static IEnumerable<IdentifierDiscoveryResult> GetExternalServices(IEnumerable<XrdElement> xrds, UriIdentifier identifier, IDirectWebRequestHandler requestHandler) { - Requires.NotNull(xrds, "xrds"); - Requires.NotNull(identifier, "identifier"); - Requires.NotNull(requestHandler, "requestHandler"); - - var results = new List<IdentifierDiscoveryResult>(); - foreach (var serviceElement in GetDescribedByServices(xrds)) { - var templateNode = serviceElement.Node.SelectSingleNode("google:URITemplate", serviceElement.XmlNamespaceResolver); - var nextAuthorityNode = serviceElement.Node.SelectSingleNode("google:NextAuthority", serviceElement.XmlNamespaceResolver); - if (templateNode != null) { - Uri externalLocation = new Uri(templateNode.Value.Trim().Replace("{%uri}", Uri.EscapeDataString(identifier.Uri.AbsoluteUri))); - string nextAuthority = nextAuthorityNode != null ? nextAuthorityNode.Value.Trim() : identifier.Uri.Host; - try { - using (var externalXrdsResponse = GetXrdsResponse(identifier, requestHandler, externalLocation)) { - var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings(); - XrdsDocument externalXrds = new XrdsDocument(XmlReader.Create(externalXrdsResponse.ResponseStream, readerSettings)); - ValidateXmlDSig(externalXrds, identifier, externalXrdsResponse, nextAuthority); - results.AddRange(GetXrdElements(externalXrds, identifier).CreateServiceEndpoints(identifier, identifier)); - } - } catch (ProtocolException ex) { - Logger.Yadis.WarnFormat("HTTP GET error while retrieving described-by XRDS document {0}: {1}", externalLocation.AbsoluteUri, ex); - } catch (XmlException ex) { - Logger.Yadis.ErrorFormat("Error while parsing described-by XRDS document {0}: {1}", externalLocation.AbsoluteUri, ex); - } - } - } - - return results; - } - - /// <summary> /// Validates the XML digital signature on an XRDS document. /// </summary> /// <param name="document">The XRDS document whose signature should be validated.</param> /// <param name="identifier">The identifier under discovery.</param> /// <param name="response">The response.</param> /// <param name="signingHost">The host name on the certificate that should be used to verify the signature in the XRDS.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> /// <exception cref="ProtocolException">Thrown if the XRDS document has an invalid or a missing signature.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "XmlDSig", Justification = "xml")] - private static void ValidateXmlDSig(XrdsDocument document, UriIdentifier identifier, IncomingWebResponse response, string signingHost) { + private static async Task ValidateXmlDSigAsync(XrdsDocument document, UriIdentifier identifier, HttpResponseMessage response, string signingHost) { Requires.NotNull(document, "document"); Requires.NotNull(identifier, "identifier"); Requires.NotNull(response, "response"); @@ -246,11 +224,12 @@ namespace DotNetOpenAuth.OpenId { ErrorUtilities.VerifyProtocol(string.Equals(hostName, signingHost, StringComparison.OrdinalIgnoreCase), OpenIdStrings.MisdirectedSigningCertificate, hostName, signingHost); // Verify the signature itself - byte[] signature = Convert.FromBase64String(response.Headers["Signature"]); + byte[] signature = Convert.FromBase64String(response.Headers.GetValues("Signature").First()); var provider = (RSACryptoServiceProvider)certs.First().PublicKey.Key; - byte[] data = new byte[response.ResponseStream.Length]; - response.ResponseStream.Seek(0, SeekOrigin.Begin); - response.ResponseStream.Read(data, 0, data.Length); + var responseStream = await response.Content.ReadAsStreamAsync(); + byte[] data = new byte[responseStream.Length]; + responseStream.Seek(0, SeekOrigin.Begin); + await responseStream.ReadAsync(data, 0, data.Length); ErrorUtilities.VerifyProtocol(provider.VerifyData(data, "SHA1", signature), OpenIdStrings.InvalidDSig); } @@ -283,33 +262,6 @@ namespace DotNetOpenAuth.OpenId { } /// <summary> - /// Gets the XRDS HTTP response for a given identifier. - /// </summary> - /// <param name="identifier">The identifier.</param> - /// <param name="requestHandler">The request handler.</param> - /// <param name="xrdsLocation">The location of the XRDS document to retrieve.</param> - /// <returns> - /// A HTTP response carrying an XRDS document. - /// </returns> - /// <exception cref="ProtocolException">Thrown if the XRDS document could not be obtained.</exception> - private static IncomingWebResponse GetXrdsResponse(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, Uri xrdsLocation) { - Requires.NotNull(identifier, "identifier"); - Requires.NotNull(requestHandler, "requestHandler"); - Requires.NotNull(xrdsLocation, "xrdsLocation"); - - var request = (HttpWebRequest)WebRequest.Create(xrdsLocation); - request.CachePolicy = Yadis.IdentifierDiscoveryCachePolicy; - request.Accept = ContentTypes.Xrds; - var options = identifier.IsDiscoverySecureEndToEnd ? DirectWebRequestOptions.RequireSsl : DirectWebRequestOptions.None; - var response = requestHandler.GetResponse(request, options).GetSnapshot(Yadis.MaximumResultToScan); - if (!string.Equals(response.ContentType.MediaType, ContentTypes.Xrds, StringComparison.Ordinal)) { - Logger.Yadis.WarnFormat("Host-meta pointed to XRDS at {0}, but Content-Type at that URL was unexpected value '{1}'.", xrdsLocation, response.ContentType); - } - - return response; - } - - /// <summary> /// Verifies that a certificate chain is trusted. /// </summary> /// <param name="certificates">The chain of certificates to verify.</param> @@ -351,53 +303,127 @@ namespace DotNetOpenAuth.OpenId { } /// <summary> + /// Gets the services for an identifier that are described by an external XRDS document. + /// </summary> + /// <param name="xrds">The XRD elements to search for described-by services.</param> + /// <param name="identifier">The identifier under discovery.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The discovered services. + /// </returns> + private async Task<IEnumerable<IdentifierDiscoveryResult>> GetExternalServicesAsync(IEnumerable<XrdElement> xrds, UriIdentifier identifier, CancellationToken cancellationToken) { + Requires.NotNull(xrds, "xrds"); + Requires.NotNull(identifier, "identifier"); + + var results = new List<IdentifierDiscoveryResult>(); + foreach (var serviceElement in GetDescribedByServices(xrds)) { + var templateNode = serviceElement.Node.SelectSingleNode("google:URITemplate", serviceElement.XmlNamespaceResolver); + var nextAuthorityNode = serviceElement.Node.SelectSingleNode("google:NextAuthority", serviceElement.XmlNamespaceResolver); + if (templateNode != null) { + Uri externalLocation = new Uri(templateNode.Value.Trim().Replace("{%uri}", Uri.EscapeDataString(identifier.Uri.AbsoluteUri))); + string nextAuthority = nextAuthorityNode != null ? nextAuthorityNode.Value.Trim() : identifier.Uri.Host; + try { + using (var externalXrdsResponse = await this.GetXrdsResponseAsync(identifier, externalLocation, cancellationToken)) { + var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings(); + var responseStream = await externalXrdsResponse.Content.ReadAsStreamAsync(); + XrdsDocument externalXrds = new XrdsDocument(XmlReader.Create(responseStream, readerSettings)); + await ValidateXmlDSigAsync(externalXrds, identifier, externalXrdsResponse, nextAuthority); + results.AddRange(GetXrdElements(externalXrds, identifier).CreateServiceEndpoints(identifier, identifier)); + } + } catch (ProtocolException ex) { + Logger.Yadis.WarnFormat("HTTP GET error while retrieving described-by XRDS document {0}: {1}", externalLocation.AbsoluteUri, ex); + } catch (XmlException ex) { + Logger.Yadis.ErrorFormat("Error while parsing described-by XRDS document {0}: {1}", externalLocation.AbsoluteUri, ex); + } + } + } + + return results; + } + + /// <summary> /// Gets the XRDS HTTP response for a given identifier. /// </summary> /// <param name="identifier">The identifier.</param> - /// <param name="requestHandler">The request handler.</param> - /// <param name="signingHost">The host name on the certificate that should be used to verify the signature in the XRDS.</param> - /// <returns>A HTTP response carrying an XRDS document, or <c>null</c> if one could not be obtained.</returns> + /// <param name="xrdsLocation">The location of the XRDS document to retrieve.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A HTTP response carrying an XRDS document. + /// </returns> /// <exception cref="ProtocolException">Thrown if the XRDS document could not be obtained.</exception> - private IncomingWebResponse GetXrdsResponse(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) { + private async Task<HttpResponseMessage> GetXrdsResponseAsync(UriIdentifier identifier, Uri xrdsLocation, CancellationToken cancellationToken) { Requires.NotNull(identifier, "identifier"); - Requires.NotNull(requestHandler, "requestHandler"); - Uri xrdsLocation = this.GetXrdsLocation(identifier, requestHandler, out signingHost); - if (xrdsLocation == null) { - return null; + Requires.NotNull(xrdsLocation, "xrdsLocation"); + + using (var httpClient = this.HostFactories.CreateHttpClient(identifier.IsDiscoverySecureEndToEnd, Yadis.IdentifierDiscoveryCachePolicy)) { + var request = new HttpRequestMessage(HttpMethod.Get, xrdsLocation); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(ContentTypes.Xrds)); + var response = await httpClient.SendAsync(request, cancellationToken); + try { + if (!string.Equals(response.Content.Headers.ContentType.MediaType, ContentTypes.Xrds, StringComparison.Ordinal)) { + Logger.Yadis.WarnFormat( + "Host-meta pointed to XRDS at {0}, but Content-Type at that URL was unexpected value '{1}'.", + xrdsLocation, + response.Content.Headers.ContentType); + } + + return response; + } catch { + response.Dispose(); + throw; + } } + } - var response = GetXrdsResponse(identifier, requestHandler, xrdsLocation); + /// <summary> + /// Gets the XRDS HTTP response for a given identifier. + /// </summary> + /// <param name="identifier">The identifier.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A HTTP response carrying an XRDS document, or <c>null</c> if one could not be obtained. + /// </returns> + /// <exception cref="ProtocolException">Thrown if the XRDS document could not be obtained.</exception> + private async Task<ResultWithSigningHost<HttpResponseMessage>> GetXrdsResponseAsync(UriIdentifier identifier, CancellationToken cancellationToken) { + Requires.NotNull(identifier, "identifier"); - return response; + var result = await this.GetXrdsLocationAsync(identifier, cancellationToken); + if (result.Result == null) { + return new ResultWithSigningHost<HttpResponseMessage>(); + } + + var response = await this.GetXrdsResponseAsync(identifier, result.Result, cancellationToken); + return new ResultWithSigningHost<HttpResponseMessage>(response, result.SigningHost); } /// <summary> /// Gets the location of the XRDS document that describes a given identifier. /// </summary> /// <param name="identifier">The identifier under discovery.</param> - /// <param name="requestHandler">The request handler.</param> - /// <param name="signingHost">The host name on the certificate that should be used to verify the signature in the XRDS.</param> - /// <returns>An absolute URI, or <c>null</c> if one could not be determined.</returns> - private Uri GetXrdsLocation(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// An absolute URI, or <c>null</c> if one could not be determined. + /// </returns> + private async Task<ResultWithSigningHost<Uri>> GetXrdsLocationAsync(UriIdentifier identifier, CancellationToken cancellationToken) { Requires.NotNull(identifier, "identifier"); - Requires.NotNull(requestHandler, "requestHandler"); - using (var hostMetaResponse = this.GetHostMeta(identifier, requestHandler, out signingHost)) { - if (hostMetaResponse == null) { - return null; + + using (var hostMetaResponse = await this.GetHostMetaAsync(identifier, cancellationToken)) { + if (hostMetaResponse.Result == null) { + return new ResultWithSigningHost<Uri>(); } - using (var sr = hostMetaResponse.GetResponseReader()) { - string line = sr.ReadLine(); + using (var sr = new StreamReader(await hostMetaResponse.Result.Content.ReadAsStreamAsync())) { + string line = await sr.ReadLineAsync(); Match m = HostMetaLink.Match(line); if (m.Success) { Uri location = new Uri(m.Groups["location"].Value); - Logger.Yadis.InfoFormat("Found link to XRDS at {0} in host-meta document {1}.", location, hostMetaResponse.FinalUri); - return location; + Logger.Yadis.InfoFormat("Found link to XRDS at {0} in host-meta document {1}.", location, hostMetaResponse.Result.RequestMessage.RequestUri); + return new ResultWithSigningHost<Uri>(location, hostMetaResponse.SigningHost); } } - Logger.Yadis.WarnFormat("Could not find link to XRDS in host-meta document: {0}", hostMetaResponse.FinalUri); - return null; + Logger.Yadis.WarnFormat("Could not find link to XRDS in host-meta document: {0}", hostMetaResponse.Result.RequestMessage.RequestUri); + return new ResultWithSigningHost<Uri>(); } } @@ -405,40 +431,33 @@ namespace DotNetOpenAuth.OpenId { /// Gets the host-meta for a given identifier. /// </summary> /// <param name="identifier">The identifier.</param> - /// <param name="requestHandler">The request handler.</param> - /// <param name="signingHost">The host name on the certificate that should be used to verify the signature in the XRDS.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The host-meta response, or <c>null</c> if no host-meta document could be obtained. /// </returns> - private IncomingWebResponse GetHostMeta(UriIdentifier identifier, IDirectWebRequestHandler requestHandler, out string signingHost) { + private async Task<ResultWithSigningHost<HttpResponseMessage>> GetHostMetaAsync(UriIdentifier identifier, CancellationToken cancellationToken) { Requires.NotNull(identifier, "identifier"); - Requires.NotNull(requestHandler, "requestHandler"); - foreach (var hostMetaProxy in this.GetHostMetaLocations(identifier)) { - var hostMetaLocation = hostMetaProxy.GetProxy(identifier); - var request = (HttpWebRequest)WebRequest.Create(hostMetaLocation); - request.CachePolicy = Yadis.IdentifierDiscoveryCachePolicy; - var options = DirectWebRequestOptions.AcceptAllHttpResponses; - if (identifier.IsDiscoverySecureEndToEnd) { - options |= DirectWebRequestOptions.RequireSsl; - } - var response = requestHandler.GetResponse(request, options).GetSnapshot(Yadis.MaximumResultToScan); - try { - if (response.Status == HttpStatusCode.OK) { - Logger.Yadis.InfoFormat("Found host-meta for {0} at: {1}", identifier.Uri.Host, hostMetaLocation); - signingHost = hostMetaProxy.GetSigningHost(identifier); - return response; - } else { - Logger.Yadis.InfoFormat("Could not obtain host-meta for {0} from {1}", identifier.Uri.Host, hostMetaLocation); + + using (var httpClient = this.HostFactories.CreateHttpClient(identifier.IsDiscoverySecureEndToEnd, Yadis.IdentifierDiscoveryCachePolicy)) { + foreach (var hostMetaProxy in this.GetHostMetaLocations(identifier)) { + var hostMetaLocation = hostMetaProxy.GetProxy(identifier); + var response = await httpClient.GetAsync(hostMetaLocation, cancellationToken); + try { + if (response.IsSuccessStatusCode) { + Logger.Yadis.InfoFormat("Found host-meta for {0} at: {1}", identifier.Uri.Host, hostMetaLocation); + return new ResultWithSigningHost<HttpResponseMessage>(response, hostMetaProxy.GetSigningHost(identifier)); + } else { + Logger.Yadis.InfoFormat("Could not obtain host-meta for {0} from {1}", identifier.Uri.Host, hostMetaLocation); + response.Dispose(); + } + } catch { response.Dispose(); + throw; } - } catch { - response.Dispose(); - throw; } } - signingHost = null; - return null; + return new ResultWithSigningHost<HttpResponseMessage>(); } /// <summary> @@ -464,6 +483,41 @@ namespace DotNetOpenAuth.OpenId { } /// <summary> + /// A compound result of some value with the signing host. + /// </summary> + /// <typeparam name="T">The type of the primary result.</typeparam> + private struct ResultWithSigningHost<T> : IDisposable { + /// <summary> + /// Initializes a new instance of the <see cref="ResultWithSigningHost{T}"/> struct. + /// </summary> + /// <param name="result">The result.</param> + /// <param name="signingHost">The signing host.</param> + internal ResultWithSigningHost(T result, string signingHost) + : this() { + this.Result = result; + this.SigningHost = signingHost; + } + + /// <summary> + /// Gets the result. + /// </summary> + public T Result { get; private set; } + + /// <summary> + /// Gets the signing host. + /// </summary> + public string SigningHost { get; private set; } + + /// <summary> + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// </summary> + public void Dispose() { + var disposable = this.Result as IDisposable; + disposable.DisposeIfNotNull(); + } + } + + /// <summary> /// A description of a web server that hosts host-meta documents. /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "By design")] diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/OpenIdRelyingPartyShim.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/OpenIdRelyingPartyShim.cs index eb37d86..9568c1d 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/OpenIdRelyingPartyShim.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/Interop/OpenIdRelyingPartyShim.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.OpenId.Interop { using System.IO; using System.Runtime.InteropServices; using System.Text; + using System.Threading; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; @@ -68,8 +69,9 @@ namespace DotNetOpenAuth.OpenId.Interop { /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "COM requires primitive types")] public string CreateRequest(string userSuppliedIdentifier, string realm, string returnToUrl) { - var request = relyingParty.CreateRequest(userSuppliedIdentifier, realm, new Uri(returnToUrl)); - return request.RedirectingResponse.GetDirectUriRequest(relyingParty.Channel).AbsoluteUri; + var request = relyingParty.CreateRequestAsync(userSuppliedIdentifier, realm, new Uri(returnToUrl)).Result; + var response = request.GetRedirectingResponseAsync(CancellationToken.None).Result; + return response.GetDirectUriRequest().AbsoluteUri; } /// <summary> @@ -91,7 +93,7 @@ namespace DotNetOpenAuth.OpenId.Interop { /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "COM requires primitive types")] public string CreateRequestWithSimpleRegistration(string userSuppliedIdentifier, string realm, string returnToUrl, string optionalSreg, string requiredSreg) { - var request = relyingParty.CreateRequest(userSuppliedIdentifier, realm, new Uri(returnToUrl)); + var request = relyingParty.CreateRequestAsync(userSuppliedIdentifier, realm, new Uri(returnToUrl)).Result; ClaimsRequest sreg = new ClaimsRequest(); if (!string.IsNullOrEmpty(optionalSreg)) { @@ -101,7 +103,8 @@ namespace DotNetOpenAuth.OpenId.Interop { sreg.SetProfileRequestFromList(requiredSreg.Split(','), DemandLevel.Require); } request.AddExtension(sreg); - return request.RedirectingResponse.GetDirectUriRequest(relyingParty.Channel).AbsoluteUri; + var response = request.GetRedirectingResponseAsync(CancellationToken.None).Result; + return response.GetDirectUriRequest().AbsoluteUri; } /// <summary> @@ -120,7 +123,7 @@ namespace DotNetOpenAuth.OpenId.Interop { } HttpRequestBase requestInfo = new HttpRequestInfo(method, new Uri(url), form: formMap); - var response = relyingParty.GetResponse(requestInfo); + var response = relyingParty.GetResponseAsync(requestInfo, CancellationToken.None).Result; if (response != null) { return new AuthenticationResponseShim(response); } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs index dfb307b..86f178b 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AssociationManager.cs @@ -11,6 +11,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Net; using System.Security; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Messages; @@ -130,15 +132,17 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// a new association of one does not already exist. /// </summary> /// <param name="provider">The provider to get an association for.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The existing or new association; <c>null</c> if none existed and one could not be created.</returns> - internal Association GetOrCreateAssociation(IProviderEndpoint provider) { - return this.GetExistingAssociation(provider) ?? this.CreateNewAssociation(provider); + internal async Task<Association> GetOrCreateAssociationAsync(IProviderEndpoint provider, CancellationToken cancellationToken) { + return this.GetExistingAssociation(provider) ?? await this.CreateNewAssociationAsync(provider, cancellationToken); } /// <summary> /// Creates a new association with a given Provider. /// </summary> /// <param name="provider">The provider to create an association with.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The newly created association, or null if no association can be created with /// the given Provider given the current security settings. @@ -146,9 +150,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <remarks> /// A new association is created and returned even if one already exists in the /// association store. - /// Any new association is automatically added to the <see cref="associationStore"/>. + /// Any new association is automatically added to the <see cref="associationStore" />. /// </remarks> - private Association CreateNewAssociation(IProviderEndpoint provider) { + private async Task<Association> CreateNewAssociationAsync(IProviderEndpoint provider, CancellationToken cancellationToken) { Requires.NotNull(provider, "provider"); // If there is no association store, there is no point in creating an association. @@ -160,7 +164,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { var associateRequest = AssociateRequestRelyingParty.Create(this.securitySettings, provider); const int RenegotiateRetries = 1; - return this.CreateNewAssociation(provider, associateRequest, RenegotiateRetries); + return await this.CreateNewAssociationAsync(provider, associateRequest, RenegotiateRetries, cancellationToken); } catch (VerificationException ex) { // See Trac ticket #163. In partial trust host environments, the // Diffie-Hellman implementation we're using for HTTP OP endpoints @@ -178,11 +182,13 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="provider">The provider to create an association with.</param> /// <param name="associateRequest">The associate request. May be <c>null</c>, which will always result in a <c>null</c> return value..</param> /// <param name="retriesRemaining">The number of times to try the associate request again if the Provider suggests it.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The newly created association, or null if no association can be created with /// the given Provider given the current security settings. /// </returns> - private Association CreateNewAssociation(IProviderEndpoint provider, AssociateRequest associateRequest, int retriesRemaining) { + /// <exception cref="ProtocolException">Create if an error occurs while creating the new association.</exception> + private async Task<Association> CreateNewAssociationAsync(IProviderEndpoint provider, AssociateRequest associateRequest, int retriesRemaining, CancellationToken cancellationToken) { Requires.NotNull(provider, "provider"); if (associateRequest == null || retriesRemaining < 0) { @@ -191,8 +197,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { return null; } + Exception exception = null; try { - var associateResponse = this.channel.Request(associateRequest); + var associateResponse = await this.channel.RequestAsync(associateRequest, cancellationToken); var associateSuccessfulResponse = associateResponse as IAssociateSuccessfulResponseRelyingParty; var associateUnsuccessfulResponse = associateResponse as AssociateUnsuccessfulResponse; if (associateSuccessfulResponse != null) { @@ -224,23 +231,27 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { associateUnsuccessfulResponse.SessionType); associateRequest = AssociateRequestRelyingParty.Create(this.securitySettings, provider, associateUnsuccessfulResponse.AssociationType, associateUnsuccessfulResponse.SessionType); - return this.CreateNewAssociation(provider, associateRequest, retriesRemaining - 1); + return await this.CreateNewAssociationAsync(provider, associateRequest, retriesRemaining - 1, cancellationToken); } else { throw new ProtocolException(MessagingStrings.UnexpectedMessageReceivedOfMany); } } catch (ProtocolException ex) { - // If the association failed because the remote server can't handle Expect: 100 Continue headers, - // then our web request handler should have already accomodated for future calls. Go ahead and - // immediately make one of those future calls now to try to get the association to succeed. - if (StandardWebRequestHandler.IsExceptionFrom417ExpectationFailed(ex)) { - return this.CreateNewAssociation(provider, associateRequest, retriesRemaining - 1); - } + exception = ex; + } - // Since having associations with OPs is not totally critical, we'll log and eat - // the exception so that auth may continue in dumb mode. - Logger.OpenId.ErrorFormat("An error occurred while trying to create an association with {0}. {1}", provider.Uri, ex); - return null; + Assumes.NotNull(exception); + + // If the association failed because the remote server can't handle Expect: 100 Continue headers, + // then our web request handler should have already accomodated for future calls. Go ahead and + // immediately make one of those future calls now to try to get the association to succeed. + if (UntrustedWebRequestHandler.IsExceptionFrom417ExpectationFailed(exception)) { + return await this.CreateNewAssociationAsync(provider, associateRequest, retriesRemaining - 1, cancellationToken); } + + // Since having associations with OPs is not totally critical, we'll log and eat + // the exception so that auth may continue in dumb mode. + Logger.OpenId.ErrorFormat("An error occurred while trying to create an association with {0}. {1}", provider.Uri, exception); + return null; } } } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs index 92af297..c7c1fe3 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/AuthenticationRequest.cs @@ -9,10 +9,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; + using System.Net.Http; + using System.ServiceModel.Channels; using System.Text; using System.Threading; + using System.Threading.Tasks; using System.Web; - using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.ChannelElements; @@ -91,21 +93,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { public AuthenticationRequestMode Mode { get; set; } /// <summary> - /// Gets the HTTP response the relying party should send to the user agent - /// to redirect it to the OpenID Provider to start the OpenID authentication process. - /// </summary> - /// <value></value> - public OutgoingWebResponse RedirectingResponse { - get { - foreach (var behavior in this.RelyingParty.Behaviors) { - behavior.OnOutgoingAuthenticationRequest(this); - } - - return this.RelyingParty.Channel.PrepareResponse(this.CreateRequestMessage()); - } - } - - /// <summary> /// Gets the URL that the user agent will return to after authentication /// completes or fails at the Provider. /// </summary> @@ -198,6 +185,23 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { #region IAuthenticationRequest methods /// <summary> + /// Gets the HTTP response the relying party should send to the user agent + /// to redirect it to the OpenID Provider to start the OpenID authentication process. + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The response message that will cause the client to redirect to the Provider. + /// </returns> + public async Task<HttpResponseMessage> GetRedirectingResponseAsync(CancellationToken cancellationToken) { + foreach (var behavior in this.RelyingParty.Behaviors) { + behavior.OnOutgoingAuthenticationRequest(this); + } + + var request = await this.CreateRequestMessageAsync(cancellationToken); + return await this.RelyingParty.Channel.PrepareResponseAsync(request, cancellationToken); + } + + /// <summary> /// Makes a dictionary of key/value pairs available when the authentication is completed. /// </summary> /// <param name="arguments">The arguments to add to the request's return_to URI.</param> @@ -293,16 +297,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { this.extensions.Add(extension); } - /// <summary> - /// Redirects the user agent to the provider for authentication. - /// </summary> - /// <remarks> - /// This method requires an ASP.NET HttpContext. - /// </remarks> - public void RedirectToProvider() { - this.RedirectingResponse.Send(); - } - #endregion /// <summary> @@ -314,11 +308,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="realm">The realm.</param> /// <param name="returnToUrl">The return_to base URL.</param> /// <param name="createNewAssociationsAsNeeded">if set to <c>true</c>, associations that do not exist between this Relying Party and the asserting Providers are created before the authentication request is created.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier. /// Never null, but may be empty. /// </returns> - internal static IEnumerable<AuthenticationRequest> Create(Identifier userSuppliedIdentifier, OpenIdRelyingParty relyingParty, Realm realm, Uri returnToUrl, bool createNewAssociationsAsNeeded) { + internal static async Task<IEnumerable<AuthenticationRequest>> CreateAsync(Identifier userSuppliedIdentifier, OpenIdRelyingParty relyingParty, Realm realm, Uri returnToUrl, bool createNewAssociationsAsNeeded, CancellationToken cancellationToken) { Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Requires.NotNull(relyingParty, "relyingParty"); Requires.NotNull(realm, "realm"); @@ -360,7 +355,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // Perform discovery right now (not deferred). IEnumerable<IdentifierDiscoveryResult> serviceEndpoints; try { - var results = relyingParty.Discover(userSuppliedIdentifier).CacheGeneratedResults(); + var identifierDiscoveryResults = await relyingParty.DiscoverAsync(userSuppliedIdentifier, cancellationToken); + var results = identifierDiscoveryResults.CacheGeneratedResults(); // If any OP Identifier service elements were found, we must not proceed // to use any Claimed Identifier services, per OpenID 2.0 sections 7.3.2.2 and 11.2. @@ -381,7 +377,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { serviceEndpoints = relyingParty.SecuritySettings.FilterEndpoints(serviceEndpoints); // Call another method that defers request generation. - return CreateInternal(userSuppliedIdentifier, relyingParty, realm, returnToUrl, serviceEndpoints, createNewAssociationsAsNeeded); + return await CreateInternalAsync(userSuppliedIdentifier, relyingParty, realm, returnToUrl, serviceEndpoints, createNewAssociationsAsNeeded, cancellationToken); } /// <summary> @@ -400,14 +396,16 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Creates the request message to send to the Provider, /// based on the properties in this instance. /// </summary> - /// <returns>The message to send to the Provider.</returns> - internal SignedResponseRequest CreateRequestMessageTestHook() - { - return this.CreateRequestMessage(); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The message to send to the Provider. + /// </returns> + internal Task<SignedResponseRequest> CreateRequestMessageTestHookAsync(CancellationToken cancellationToken) { + return this.CreateRequestMessageAsync(cancellationToken); } /// <summary> - /// Performs deferred request generation for the <see cref="Create"/> method. + /// Performs deferred request generation for the <see cref="CreateAsync" /> method. /// </summary> /// <param name="userSuppliedIdentifier">The user supplied identifier.</param> /// <param name="relyingParty">The relying party.</param> @@ -415,6 +413,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="returnToUrl">The return_to base URL.</param> /// <param name="serviceEndpoints">The discovered service endpoints on the Claimed Identifier.</param> /// <param name="createNewAssociationsAsNeeded">if set to <c>true</c>, associations that do not exist between this Relying Party and the asserting Providers are created before the authentication request is created.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier. /// Never null, but may be empty. @@ -423,12 +422,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// All data validation and cleansing steps must have ALREADY taken place /// before calling this method. /// </remarks> - private static IEnumerable<AuthenticationRequest> CreateInternal(Identifier userSuppliedIdentifier, OpenIdRelyingParty relyingParty, Realm realm, Uri returnToUrl, IEnumerable<IdentifierDiscoveryResult> serviceEndpoints, bool createNewAssociationsAsNeeded) { - // DO NOT USE CODE CONTRACTS IN THIS METHOD, since it uses yield return - ErrorUtilities.VerifyArgumentNotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); - ErrorUtilities.VerifyArgumentNotNull(relyingParty, "relyingParty"); - ErrorUtilities.VerifyArgumentNotNull(realm, "realm"); - ErrorUtilities.VerifyArgumentNotNull(serviceEndpoints, "serviceEndpoints"); + private static async Task<IEnumerable<AuthenticationRequest>> CreateInternalAsync(Identifier userSuppliedIdentifier, OpenIdRelyingParty relyingParty, Realm realm, Uri returnToUrl, IEnumerable<IdentifierDiscoveryResult> serviceEndpoints, bool createNewAssociationsAsNeeded, CancellationToken cancellationToken) { + Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); + Requires.NotNull(relyingParty, "relyingParty"); + Requires.NotNull(realm, "realm"); + Requires.NotNull(serviceEndpoints, "serviceEndpoints"); //// // If shared associations are required, then we had better have an association store. ErrorUtilities.VerifyOperation(!relyingParty.SecuritySettings.RequireAssociation || relyingParty.AssociationManager.HasAssociationStore, OpenIdStrings.AssociationStoreRequired); @@ -436,12 +434,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { Logger.Yadis.InfoFormat("Performing discovery on user-supplied identifier: {0}", userSuppliedIdentifier); IEnumerable<IdentifierDiscoveryResult> endpoints = FilterAndSortEndpoints(serviceEndpoints, relyingParty); - // Maintain a list of endpoints that we could not form an association with. - // We'll fallback to generating requests to these if the ones we CAN create - // an association with run out. - var failedAssociationEndpoints = new List<IdentifierDiscoveryResult>(0); - - foreach (var endpoint in endpoints) { + var authRequestResults = await endpoints.ToDictionaryAsync(async endpoint => { Logger.OpenId.DebugFormat("Creating authentication request for user supplied Identifier: {0}", userSuppliedIdentifier); // The strategy here is to prefer endpoints with whom we can create associations. @@ -450,19 +443,25 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // In some scenarios (like the AJAX control wanting ALL auth requests possible), // we don't want to create associations with every Provider. But we'll use // associations where they are already formed from previous authentications. - association = createNewAssociationsAsNeeded ? relyingParty.AssociationManager.GetOrCreateAssociation(endpoint) : relyingParty.AssociationManager.GetExistingAssociation(endpoint); + association = createNewAssociationsAsNeeded ? await relyingParty.AssociationManager.GetOrCreateAssociationAsync(endpoint, cancellationToken) : relyingParty.AssociationManager.GetExistingAssociation(endpoint); if (association == null && createNewAssociationsAsNeeded) { Logger.OpenId.WarnFormat("Failed to create association with {0}. Skipping to next endpoint.", endpoint.ProviderEndpoint); // No association could be created. Add it to the list of failed association // endpoints and skip to the next available endpoint. - failedAssociationEndpoints.Add(endpoint); - continue; + return null; } } - yield return new AuthenticationRequest(endpoint, realm, returnToUrl, relyingParty); - } + return new AuthenticationRequest(endpoint, realm, returnToUrl, relyingParty); + }); + + var results = (from pair in authRequestResults where pair.Value != null select pair.Value).ToList(); + + // Maintain a list of endpoints that we could not form an association with. + // We'll fallback to generating requests to these if the ones we CAN create + // an association with run out. + var failedAssociationEndpoints = (from pair in authRequestResults where pair.Value == null select pair.Key).ToList(); // Now that we've run out of endpoints that respond to association requests, // since we apparently are still running, the caller must want another request. @@ -481,10 +480,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // because we've already tried. Let's not have it waste time trying again. var authRequest = new AuthenticationRequest(endpoint, realm, returnToUrl, relyingParty); authRequest.associationPreference = AssociationPreference.IfAlreadyEstablished; - yield return authRequest; + results.Add(authRequest); } } } + + return results; } /// <summary> @@ -534,9 +535,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Creates the request message to send to the Provider, /// based on the properties in this instance. /// </summary> - /// <returns>The message to send to the Provider.</returns> - private SignedResponseRequest CreateRequestMessage() { - Association association = this.GetAssociation(); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The message to send to the Provider. + /// </returns> + private async Task<SignedResponseRequest> CreateRequestMessageAsync(CancellationToken cancellationToken) { + Association association = await this.GetAssociationAsync(cancellationToken); SignedResponseRequest request; if (!this.IsExtensionOnly) { @@ -565,12 +569,15 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <summary> /// Gets the association to use for this authentication request. /// </summary> - /// <returns>The association to use; <c>null</c> to use 'dumb mode'.</returns> - private Association GetAssociation() { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The association to use; <c>null</c> to use 'dumb mode'. + /// </returns> + private async Task<Association> GetAssociationAsync(CancellationToken cancellationToken) { Association association = null; switch (this.associationPreference) { case AssociationPreference.IfPossible: - association = this.RelyingParty.AssociationManager.GetOrCreateAssociation(this.DiscoveryResult); + association = await this.RelyingParty.AssociationManager.GetOrCreateAssociationAsync(this.DiscoveryResult, cancellationToken); if (association == null) { // Avoid trying to create the association again if the redirecting response // is generated again. diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/UIUtilities.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/UIUtilities.cs index a5de08b..4e138ee 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/UIUtilities.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/Extensions/UIUtilities.cs @@ -6,10 +6,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty.Extensions.UI { using System; - using System.Globalization; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OpenId.RelyingParty; - using Validation; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using DotNetOpenAuth.Messaging; +using DotNetOpenAuth.OpenId.RelyingParty; +using Validation; /// <summary> /// Constants used in implementing support for the UI extension. @@ -22,13 +24,17 @@ namespace DotNetOpenAuth.OpenId.RelyingParty.Extensions.UI { /// <param name="relyingParty">The relying party.</param> /// <param name="request">The authentication request to place in the window.</param> /// <param name="windowName">The name to assign to the popup window.</param> - /// <returns>A string starting with 'window.open' and forming just that one method call.</returns> - internal static string GetWindowPopupScript(OpenIdRelyingParty relyingParty, IAuthenticationRequest request, string windowName) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A string starting with 'window.open' and forming just that one method call. + /// </returns> + internal static async Task<string> GetWindowPopupScriptAsync(OpenIdRelyingParty relyingParty, IAuthenticationRequest request, string windowName, CancellationToken cancellationToken) { Requires.NotNull(relyingParty, "relyingParty"); Requires.NotNull(request, "request"); Requires.NotNullOrEmpty(windowName, "windowName"); - Uri popupUrl = request.RedirectingResponse.GetDirectUriRequest(relyingParty.Channel); + var response = await request.GetRedirectingResponseAsync(cancellationToken); + Uri popupUrl = response.GetDirectUriRequest(); return string.Format( CultureInfo.InvariantCulture, diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs index 4fc459f..f4fdeb1 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/ISetupRequiredAuthenticationResponse.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System; + using System.Threading; + using System.Web; /// <summary> /// An interface to expose useful properties and functionality for handling @@ -14,7 +16,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> public interface ISetupRequiredAuthenticationResponse { /// <summary> - /// Gets the <see cref="Identifier"/> to pass to <see cref="OpenIdRelyingParty.CreateRequest(Identifier)"/> + /// Gets the <see cref="Identifier"/> to pass to <see cref="OpenIdRelyingParty.CreateRequestAsync(Identifier, HttpRequestBase, CancellationToken)"/> /// in a subsequent authentication attempt. /// </summary> Identifier UserSuppliedIdentifier { get; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs index bf52060..fdd3529 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/NegativeAuthenticationResponse.cs @@ -8,6 +8,8 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System; using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; @@ -126,10 +128,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { #region ISetupRequiredAuthenticationResponse Members /// <summary> - /// Gets the <see cref="Identifier"/> to pass to <see cref="OpenIdRelyingParty.CreateRequest(Identifier)"/> + /// Gets the <see cref="Identifier"/> to pass to <see cref="OpenIdRelyingParty.CreateRequestAsync(Identifier, HttpRequestBase, CancellationToken)"/> /// in a subsequent authentication attempt. /// </summary> - /// <value></value> public Identifier UserSuppliedIdentifier { get { ErrorUtilities.VerifyOperation(((IAuthenticationResponse)this).Status == AuthenticationStatus.SetupRequired, OpenIdStrings.OperationOnlyValidForSetupRequiredState); diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs index 2177591..eeca146 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/OpenIdRelyingParty.cs @@ -14,8 +14,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System.Globalization; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; @@ -89,27 +93,30 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { private Channel channel; /// <summary> - /// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class. + /// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class + /// such that it uses a memory store for things it must remember across logins. /// </summary> public OpenIdRelyingParty() - : this(OpenIdElement.Configuration.RelyingParty.ApplicationStore.CreateInstance(HttpApplicationStore)) { + : this(OpenIdElement.Configuration.RelyingParty.ApplicationStore.CreateInstance(GetHttpApplicationStore(), null)) { } /// <summary> - /// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class. + /// Initializes a new instance of the <see cref="OpenIdRelyingParty" /> class. /// </summary> /// <param name="applicationStore">The application store. If <c>null</c>, the relying party will always operate in "stateless/dumb mode".</param> - public OpenIdRelyingParty(IOpenIdApplicationStore applicationStore) - : this(applicationStore, applicationStore) { + /// <param name="hostFactories">The host factories.</param> + public OpenIdRelyingParty(IOpenIdApplicationStore applicationStore, IHostFactories hostFactories = null) + : this(applicationStore, applicationStore, hostFactories) { } /// <summary> - /// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class. + /// Initializes a new instance of the <see cref="OpenIdRelyingParty" /> class. /// </summary> /// <param name="cryptoKeyStore">The association store. If <c>null</c>, the relying party will always operate in "stateless/dumb mode".</param> /// <param name="nonceStore">The nonce store to use. If <c>null</c>, the relying party will always operate in "stateless/dumb mode".</param> + /// <param name="hostFactories">The host factories.</param> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Unavoidable")] - private OpenIdRelyingParty(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore) { + private OpenIdRelyingParty(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, IHostFactories hostFactories) { // If we are a smart-mode RP (supporting associations), then we MUST also be // capable of storing nonces to prevent replay attacks. // If we're a dumb-mode RP, then 2.0 OPs are responsible for preventing replays. @@ -118,7 +125,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { this.securitySettings = OpenIdElement.Configuration.RelyingParty.SecuritySettings.CreateSecuritySettings(); this.behaviors.CollectionChanged += this.OnBehaviorsChanged; - foreach (var behavior in OpenIdElement.Configuration.RelyingParty.Behaviors.CreateInstances(false)) { + foreach (var behavior in OpenIdElement.Configuration.RelyingParty.Behaviors.CreateInstances(false, null)) { this.behaviors.Add(behavior); } @@ -132,7 +139,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { this.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20; } - this.channel = new OpenIdRelyingPartyChannel(cryptoKeyStore, nonceStore, this.SecuritySettings); + this.channel = new OpenIdRelyingPartyChannel(cryptoKeyStore, nonceStore, this.SecuritySettings, hostFactories); var associationStore = cryptoKeyStore != null ? new CryptoKeyStoreAsRelyingPartyAssociationStore(cryptoKeyStore) : null; this.AssociationManager = new AssociationManager(this.Channel, associationStore, this.SecuritySettings); this.discoveryServices = new IdentifierDiscoveryServices(this); @@ -153,31 +160,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> - /// Gets the standard state storage mechanism that uses ASP.NET's - /// HttpApplication state dictionary to store associations and nonces. - /// </summary> - [EditorBrowsable(EditorBrowsableState.Advanced)] - public static IOpenIdApplicationStore HttpApplicationStore { - get { - HttpContext context = HttpContext.Current; - ErrorUtilities.VerifyOperation(context != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(IOpenIdApplicationStore).Name); - var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]; - if (store == null) { - context.Application.Lock(); - try { - if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) { - context.Application[ApplicationStoreKey] = store = new StandardRelyingPartyApplicationStore(); - } - } finally { - context.Application.UnLock(); - } - } - - return store; - } - } - - /// <summary> /// Gets or sets the channel to use for sending/receiving messages. /// </summary> public Channel Channel { @@ -272,11 +254,10 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> - /// Gets the web request handler to use for discovery and the part of - /// authentication where direct messages are sent to an untrusted remote party. + /// Gets the factory for various dependencies. /// </summary> - IDirectWebRequestHandler IOpenIdHost.WebRequestHandler { - get { return this.Channel.WebRequestHandler; } + IHostFactories IOpenIdHost.HostFactories { + get { return this.channel.HostFactories; } } /// <summary> @@ -288,14 +269,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> - /// Gets the web request handler to use for discovery and the part of - /// authentication where direct messages are sent to an untrusted remote party. - /// </summary> - internal IDirectWebRequestHandler WebRequestHandler { - get { return this.Channel.WebRequestHandler; } - } - - /// <summary> /// Gets the association manager. /// </summary> internal AssociationManager AssociationManager { get; private set; } @@ -319,32 +292,55 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> + /// Gets the standard state storage mechanism that uses ASP.NET's + /// HttpApplication state dictionary to store associations and nonces. + /// </summary> + /// <param name="context">The context.</param> + /// <returns>The application store.</returns> + public static IOpenIdApplicationStore GetHttpApplicationStore(HttpContextBase context = null) { + if (context == null) { + ErrorUtilities.VerifyOperation(HttpContext.Current != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(IOpenIdApplicationStore).Name); + context = new HttpContextWrapper(HttpContext.Current); + } + + var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]; + if (store == null) { + context.Application.Lock(); + try { + if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) { + context.Application[ApplicationStoreKey] = store = new StandardRelyingPartyApplicationStore(); + } + } finally { + context.Application.UnLock(); + } + } + + return store; + } + + /// <summary> /// Creates an authentication request to verify that a user controls /// some given Identifier. /// </summary> - /// <param name="userSuppliedIdentifier"> - /// The Identifier supplied by the user. This may be a URL, an XRI or i-name. - /// </param> - /// <param name="realm"> - /// The shorest URL that describes this relying party web site's address. + /// <param name="userSuppliedIdentifier">The Identifier supplied by the user. This may be a URL, an XRI or i-name.</param> + /// <param name="realm">The shorest URL that describes this relying party web site's address. /// For example, if your login page is found at https://www.example.com/login.aspx, - /// your realm would typically be https://www.example.com/. - /// </param> - /// <param name="returnToUrl"> - /// The URL of the login page, or the page prepared to receive authentication - /// responses from the OpenID Provider. - /// </param> + /// your realm would typically be https://www.example.com/.</param> + /// <param name="returnToUrl">The URL of the login page, or the page prepared to receive authentication + /// responses from the OpenID Provider.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// An authentication request object to customize the request and generate /// an object to send to the user agent to initiate the authentication. /// </returns> /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> - public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl) { + public async Task<IAuthenticationRequest> CreateRequestAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Requires.NotNull(realm, "realm"); Requires.NotNull(returnToUrl, "returnToUrl"); try { - return this.CreateRequests(userSuppliedIdentifier, realm, returnToUrl).First(); + var requests = await this.CreateRequestsAsync(userSuppliedIdentifier, realm, returnToUrl); + return requests.First(); } catch (InvalidOperationException ex) { throw ErrorUtilities.Wrap(ex, OpenIdStrings.OpenIdEndpointNotFound); } @@ -354,28 +350,26 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Creates an authentication request to verify that a user controls /// some given Identifier. /// </summary> - /// <param name="userSuppliedIdentifier"> - /// The Identifier supplied by the user. This may be a URL, an XRI or i-name. - /// </param> - /// <param name="realm"> - /// The shorest URL that describes this relying party web site's address. + /// <param name="userSuppliedIdentifier">The Identifier supplied by the user. This may be a URL, an XRI or i-name.</param> + /// <param name="realm">The shorest URL that describes this relying party web site's address. /// For example, if your login page is found at https://www.example.com/login.aspx, - /// your realm would typically be https://www.example.com/. - /// </param> + /// your realm would typically be https://www.example.com/.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// An authentication request object that describes the HTTP response to /// send to the user agent to initiate the authentication. /// </returns> - /// <remarks> - /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> - /// </remarks> /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> - public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm) { + /// <remarks> + /// Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context. + /// </remarks> + public async Task<IAuthenticationRequest> CreateRequestAsync(Identifier userSuppliedIdentifier, Realm realm, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Requires.NotNull(realm, "realm"); try { - var result = this.CreateRequests(userSuppliedIdentifier, realm).First(); + var request = await this.CreateRequestsAsync(userSuppliedIdentifier, realm, cancellationToken: cancellationToken); + var result = request.First(); Assumes.True(result != null); return result; } catch (InvalidOperationException ex) { @@ -387,22 +381,23 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Creates an authentication request to verify that a user controls /// some given Identifier. /// </summary> - /// <param name="userSuppliedIdentifier"> - /// The Identifier supplied by the user. This may be a URL, an XRI or i-name. - /// </param> + /// <param name="userSuppliedIdentifier">The Identifier supplied by the user. This may be a URL, an XRI or i-name.</param> + /// <param name="requestContext">The request context.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// An authentication request object that describes the HTTP response to /// send to the user agent to initiate the authentication. /// </returns> - /// <remarks> - /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> - /// </remarks> /// <exception cref="ProtocolException">Thrown if no OpenID endpoint could be found.</exception> /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> - public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier) { + /// <remarks> + /// Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context. + /// </remarks> + public async Task<IAuthenticationRequest> CreateRequestAsync(Identifier userSuppliedIdentifier, HttpRequestBase requestContext = null, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); try { - return this.CreateRequests(userSuppliedIdentifier).First(); + var authenticationRequests = await this.CreateRequestsAsync(userSuppliedIdentifier, requestContext, cancellationToken); + return authenticationRequests.First(); } catch (InvalidOperationException ex) { throw ErrorUtilities.Wrap(ex, OpenIdStrings.OpenIdEndpointNotFound); } @@ -411,137 +406,139 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <summary> /// Generates the authentication requests that can satisfy the requirements of some OpenID Identifier. /// </summary> - /// <param name="userSuppliedIdentifier"> - /// The Identifier supplied by the user. This may be a URL, an XRI or i-name. - /// </param> - /// <param name="realm"> - /// The shorest URL that describes this relying party web site's address. + /// <param name="userSuppliedIdentifier">The Identifier supplied by the user. This may be a URL, an XRI or i-name.</param> + /// <param name="realm">The shorest URL that describes this relying party web site's address. /// For example, if your login page is found at https://www.example.com/login.aspx, - /// your realm would typically be https://www.example.com/. - /// </param> - /// <param name="returnToUrl"> - /// The URL of the login page, or the page prepared to receive authentication - /// responses from the OpenID Provider. - /// </param> + /// your realm would typically be https://www.example.com/.</param> + /// <param name="returnToUrl">The URL of the login page, or the page prepared to receive authentication + /// responses from the OpenID Provider.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier. /// Never null, but may be empty. /// </returns> /// <remarks> - /// <para>Any individual generated request can satisfy the authentication. + /// <para>Any individual generated request can satisfy the authentication. /// The generated requests are sorted in preferred order. /// Each request is generated as it is enumerated to. Associations are created only as - /// <see cref="IAuthenticationRequest.RedirectingResponse"/> is called.</para> - /// <para>No exception is thrown if no OpenID endpoints were discovered. + /// <see cref="IAuthenticationRequest.GetRedirectingResponseAsync" /> is called.</para> + /// <para>No exception is thrown if no OpenID endpoints were discovered. /// An empty enumerable is returned instead.</para> /// </remarks> - public virtual IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl) { + public virtual async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Requires.NotNull(realm, "realm"); Requires.NotNull(returnToUrl, "returnToUrl"); - return AuthenticationRequest.Create(userSuppliedIdentifier, this, realm, returnToUrl, true).Cast<IAuthenticationRequest>().CacheGeneratedResults(); + var requests = await AuthenticationRequest.CreateAsync(userSuppliedIdentifier, this, realm, returnToUrl, true, cancellationToken); + return requests.Cast<IAuthenticationRequest>().CacheGeneratedResults(); } /// <summary> /// Generates the authentication requests that can satisfy the requirements of some OpenID Identifier. /// </summary> - /// <param name="userSuppliedIdentifier"> - /// The Identifier supplied by the user. This may be a URL, an XRI or i-name. - /// </param> - /// <param name="realm"> - /// The shorest URL that describes this relying party web site's address. + /// <param name="userSuppliedIdentifier">The Identifier supplied by the user. This may be a URL, an XRI or i-name.</param> + /// <param name="realm">The shorest URL that describes this relying party web site's address. /// For example, if your login page is found at https://www.example.com/login.aspx, - /// your realm would typically be https://www.example.com/. - /// </param> + /// your realm would typically be https://www.example.com/.</param> + /// <param name="requestContext">The request context.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier. /// Never null, but may be empty. /// </returns> + /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> /// <remarks> - /// <para>Any individual generated request can satisfy the authentication. + /// <para>Any individual generated request can satisfy the authentication. /// The generated requests are sorted in preferred order. /// Each request is generated as it is enumerated to. Associations are created only as - /// <see cref="IAuthenticationRequest.RedirectingResponse"/> is called.</para> - /// <para>No exception is thrown if no OpenID endpoints were discovered. + /// <see cref="IAuthenticationRequest.GetRedirectingResponseAsync" /> is called.</para> + /// <para>No exception is thrown if no OpenID endpoints were discovered. /// An empty enumerable is returned instead.</para> - /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> + /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> /// </remarks> - /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> - public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm) { - RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); + public async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, HttpRequestBase requestContext = null, CancellationToken cancellationToken = default(CancellationToken)) { + RequiresEx.ValidState(requestContext != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired); Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); Requires.NotNull(realm, "realm"); + requestContext = requestContext ?? this.channel.GetRequestFromContext(); + // This next code contract is a BAD idea, because it causes each authentication request to be generated // at least an extra time. //// // Build the return_to URL - UriBuilder returnTo = new UriBuilder(this.Channel.GetRequestFromContext().GetPublicFacingUrl()); + UriBuilder returnTo = new UriBuilder(requestContext.GetPublicFacingUrl()); // Trim off any parameters with an "openid." prefix, and a few known others // to avoid carrying state from a prior login attempt. returnTo.Query = string.Empty; - NameValueCollection queryParams = this.Channel.GetRequestFromContext().GetQueryStringBeforeRewriting(); + NameValueCollection queryParams = requestContext.GetQueryStringBeforeRewriting(); var returnToParams = new Dictionary<string, string>(queryParams.Count); foreach (string key in queryParams) { if (!IsOpenIdSupportingParameter(key) && key != null) { returnToParams.Add(key, queryParams[key]); } } + returnTo.AppendQueryArgs(returnToParams); - return this.CreateRequests(userSuppliedIdentifier, realm, returnTo.Uri); + return await this.CreateRequestsAsync(userSuppliedIdentifier, realm, returnTo.Uri, cancellationToken); } /// <summary> /// Generates the authentication requests that can satisfy the requirements of some OpenID Identifier. /// </summary> - /// <param name="userSuppliedIdentifier"> - /// The Identifier supplied by the user. This may be a URL, an XRI or i-name. - /// </param> + /// <param name="userSuppliedIdentifier">The Identifier supplied by the user. This may be a URL, an XRI or i-name.</param> + /// <param name="requestContext">The request context.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of authentication requests, any of which constitutes a valid identity assertion on the Claimed Identifier. /// Never null, but may be empty. /// </returns> + /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> /// <remarks> - /// <para>Any individual generated request can satisfy the authentication. + /// <para>Any individual generated request can satisfy the authentication. /// The generated requests are sorted in preferred order. /// Each request is generated as it is enumerated to. Associations are created only as - /// <see cref="IAuthenticationRequest.RedirectingResponse"/> is called.</para> - /// <para>No exception is thrown if no OpenID endpoints were discovered. + /// <see cref="IAuthenticationRequest.GetRedirectingResponseAsync" /> is called.</para> + /// <para>No exception is thrown if no OpenID endpoints were discovered. /// An empty enumerable is returned instead.</para> - /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> + /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> /// </remarks> - /// <exception cref="InvalidOperationException">Thrown if <see cref="HttpContext.Current">HttpContext.Current</see> == <c>null</c>.</exception> - public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier) { + public async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, HttpRequestBase requestContext = null, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier"); - RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - return this.CreateRequests(userSuppliedIdentifier, Realm.AutoDetect); + return await this.CreateRequestsAsync(userSuppliedIdentifier, Realm.AutoDetect, requestContext, cancellationToken); } /// <summary> /// Gets an authentication response from a Provider. /// </summary> - /// <returns>The processed authentication response if there is any; <c>null</c> otherwise.</returns> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The processed authentication response if there is any; <c>null</c> otherwise. + /// </returns> /// <remarks> - /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> + /// Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context. /// </remarks> - public IAuthenticationResponse GetResponse() { - RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - return this.GetResponse(this.Channel.GetRequestFromContext()); + public Task<IAuthenticationResponse> GetResponseAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.channel.GetRequestFromContext(); + return this.GetResponseAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> /// Gets an authentication response from a Provider. /// </summary> /// <param name="httpRequestInfo">The HTTP request that may be carrying an authentication response from the Provider.</param> - /// <returns>The processed authentication response if there is any; <c>null</c> otherwise.</returns> - public IAuthenticationResponse GetResponse(HttpRequestBase httpRequestInfo) { - Requires.NotNull(httpRequestInfo, "httpRequestInfo"); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The processed authentication response if there is any; <c>null</c> otherwise. + /// </returns> + public async Task<IAuthenticationResponse> GetResponseAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(request, "httpRequestInfo"); try { - var message = this.Channel.ReadFromRequest(httpRequestInfo); + var message = await this.Channel.ReadFromRequestAsync(request, cancellationToken); PositiveAssertionResponse positiveAssertion; NegativeAssertionResponse negativeAssertion; IndirectSignedResponse positiveExtensionOnly; @@ -554,7 +551,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { OpenIdStrings.PositiveAssertionFromNonQualifiedProvider, providerEndpoint.Uri); - var response = new PositiveAuthenticationResponse(positiveAssertion, this); + var response = await PositiveAuthenticationResponse.CreateAsync(positiveAssertion, this, cancellationToken); foreach (var behavior in this.Behaviors) { behavior.OnIncomingPositiveAssertion(response); } @@ -577,25 +574,30 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <summary> /// Processes the response received in a popup window or iframe to an AJAX-directed OpenID authentication. /// </summary> - /// <returns>The HTTP response to send to this HTTP request.</returns> + /// <param name="request">The request.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The HTTP response to send to this HTTP request. + /// </returns> /// <remarks> - /// <para>Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context.</para> + /// Requires an <see cref="HttpContext.Current">HttpContext.Current</see> context. /// </remarks> - public OutgoingWebResponse ProcessResponseFromPopup() { - RequiresEx.ValidState(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired); - - return this.ProcessResponseFromPopup(this.Channel.GetRequestFromContext()); + public Task<HttpResponseMessage> ProcessResponseFromPopupAsync(HttpRequestBase request = null, CancellationToken cancellationToken = default(CancellationToken)) { + request = request ?? this.Channel.GetRequestFromContext(); + return this.ProcessResponseFromPopupAsync(request.AsHttpRequestMessage(), cancellationToken); } /// <summary> /// Processes the response received in a popup window or iframe to an AJAX-directed OpenID authentication. /// </summary> /// <param name="request">The incoming HTTP request that is expected to carry an OpenID authentication response.</param> - /// <returns>The HTTP response to send to this HTTP request.</returns> - public OutgoingWebResponse ProcessResponseFromPopup(HttpRequestBase request) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The HTTP response to send to this HTTP request. + /// </returns> + public Task<HttpResponseMessage> ProcessResponseFromPopupAsync(HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(request, "request"); - - return this.ProcessResponseFromPopup(request, null); + return this.ProcessResponseFromPopupAsync(request, null, cancellationToken); } /// <summary> @@ -606,7 +608,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <typeparam name="T">The extension <i>response</i> type that will read data from the assertion.</typeparam> /// <param name="propertyName">The property name on the openid_identifier input box object that will be used to store the extension data. For example: sreg</param> /// <remarks> - /// This method should be called before <see cref="ProcessResponseFromPopup()"/>. + /// This method should be called before <see cref="ProcessResponseFromPopupAsync(CancellationToken)"/>. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "By design")] public void RegisterClientScriptExtension<T>(string propertyName) where T : IClientScriptExtensionResponse { @@ -674,15 +676,16 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// </summary> /// <param name="request">The incoming HTTP request that is expected to carry an OpenID authentication response.</param> /// <param name="callback">The callback fired after the response status has been determined but before the Javascript response is formulated.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The HTTP response to send to this HTTP request. /// </returns> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "OpenID", Justification = "real word"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "iframe", Justification = "Code contracts")] - internal OutgoingWebResponse ProcessResponseFromPopup(HttpRequestBase request, Action<AuthenticationStatus> callback) { + internal async Task<HttpResponseMessage> ProcessResponseFromPopupAsync(HttpRequestMessage request, Action<AuthenticationStatus> callback, CancellationToken cancellationToken) { Requires.NotNull(request, "request"); string extensionsJson = null; - var authResponse = this.NonVerifyingRelyingParty.GetResponse(); + var authResponse = await this.NonVerifyingRelyingParty.GetResponseAsync(request, cancellationToken); ErrorUtilities.VerifyProtocol(authResponse != null, OpenIdStrings.PopupRedirectMissingResponse); // Give the caller a chance to notify the hosting page and fill up the clientScriptExtensions collection. @@ -690,7 +693,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { callback(authResponse.Status); } - Logger.OpenId.DebugFormat("Popup or iframe callback from OP: {0}", request.Url); + Logger.OpenId.DebugFormat("Popup or iframe callback from OP: {0}", request.RequestUri); Logger.Controls.DebugFormat( "An authentication response was found in a popup window or iframe using a non-verifying RP with status: {0}", authResponse.Status); @@ -712,13 +715,13 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } string payload = "document.URL"; - if (request.HttpMethod == "POST") { + if (request.Method == HttpMethod.Post) { // Promote all form variables to the query string, but since it won't be passed // to any server (this is a javascript window-to-window transfer) the length of // it can be arbitrarily long, whereas it was POSTed here probably because it // was too long for HTTP transit. - UriBuilder payloadUri = new UriBuilder(request.Url); - payloadUri.AppendQueryArgs(request.Form.ToDictionary()); + UriBuilder payloadUri = new UriBuilder(request.RequestUri); + payloadUri.AppendQueryArgs(await Channel.ParseUrlEncodedFormContentAsync(request, cancellationToken)); payload = MessagingUtilities.GetSafeJavascriptValue(payloadUri.Uri.AbsoluteUri); } @@ -733,9 +736,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// Performs discovery on the specified identifier. /// </summary> /// <param name="identifier">The identifier to discover services for.</param> - /// <returns>A non-null sequence of services discovered for the identifier.</returns> - internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) { - return this.discoveryServices.Discover(identifier); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A non-null sequence of services discovered for the identifier. + /// </returns> + internal Task<IEnumerable<IdentifierDiscoveryResult>> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) { + return this.discoveryServices.DiscoverAsync(identifier, cancellationToken); } /// <summary> @@ -795,7 +801,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { /// <param name="methodCall">The method to call on the parent window, including /// parameters. (i.e. "callback('arg1', 2)"). No escaping is done by this method.</param> /// <returns>The entire HTTP response to send to the popup window or iframe to perform the invocation.</returns> - private static OutgoingWebResponse InvokeParentPageScript(string methodCall) { + private static HttpResponseMessage InvokeParentPageScript(string methodCall) { Requires.NotNullOrEmpty(methodCall, "methodCall"); Logger.OpenId.DebugFormat("Sending Javascript callback: {0}", methodCall); @@ -824,9 +830,9 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { builder.AppendLine("//]]>--></script>"); builder.AppendLine("</body></html>"); - var response = new OutgoingWebResponse(); - response.Body = builder.ToString(); - response.Headers.Add(HttpResponseHeader.ContentType, new ContentType("text/html").ToString()); + var response = new HttpResponseMessage(); + response.Content = new StringContent(builder.ToString()); + response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); return response; } diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs index 509eb60..89162ab 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/OpenId/RelyingParty/PositiveAuthenticationResponse.cs @@ -8,23 +8,25 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System; using System.Diagnostics; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using Validation; /// <summary> - /// Wraps a positive assertion response in an <see cref="IAuthenticationResponse"/> instance + /// Wraps a positive assertion response in an <see cref="IAuthenticationResponse" /> instance /// for public consumption by the host web site. /// </summary> [DebuggerDisplay("Status: {Status}, ClaimedIdentifier: {ClaimedIdentifier}")] internal class PositiveAuthenticationResponse : PositiveAnonymousResponse { /// <summary> - /// Initializes a new instance of the <see cref="PositiveAuthenticationResponse"/> class. + /// Initializes a new instance of the <see cref="PositiveAuthenticationResponse"/> class /// </summary> /// <param name="response">The positive assertion response that was just received by the Relying Party.</param> /// <param name="relyingParty">The relying party.</param> - internal PositiveAuthenticationResponse(PositiveAssertionResponse response, OpenIdRelyingParty relyingParty) + private PositiveAuthenticationResponse(PositiveAssertionResponse response, OpenIdRelyingParty relyingParty) : base(response) { Requires.NotNull(relyingParty, "relyingParty"); @@ -36,8 +38,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { null, null); - this.VerifyDiscoveryMatchesAssertion(relyingParty); - Logger.OpenId.InfoFormat("Received identity assertion for {0} via {1}.", this.Response.ClaimedIdentifier, this.Provider.Uri); } @@ -124,17 +124,34 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { } /// <summary> + /// Initializes a new instance of the <see cref="PositiveAuthenticationResponse"/> class + /// after verifying that discovery on the identifier matches the asserted data. + /// </summary> + /// <param name="response">The response.</param> + /// <param name="relyingParty">The relying party.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The newly initialized instance.</returns> + internal static async Task<PositiveAuthenticationResponse> CreateAsync( + PositiveAssertionResponse response, OpenIdRelyingParty relyingParty, CancellationToken cancellationToken) { + var result = new PositiveAuthenticationResponse(response, relyingParty); + await result.VerifyDiscoveryMatchesAssertionAsync(relyingParty, cancellationToken); + return result; + } + + /// <summary> /// Verifies that the positive assertion data matches the results of /// discovery on the Claimed Identifier. /// </summary> /// <param name="relyingParty">The relying party.</param> - /// <exception cref="ProtocolException"> - /// Thrown when the Provider is asserting that a user controls an Identifier + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + /// <exception cref="ProtocolException">Thrown when the Provider is asserting that a user controls an Identifier /// when discovery on that Identifier contradicts what the Provider says. /// This would be an indication of either a misconfigured Provider or - /// an attempt by someone to spoof another user's identity with a rogue Provider. - /// </exception> - private void VerifyDiscoveryMatchesAssertion(OpenIdRelyingParty relyingParty) { + /// an attempt by someone to spoof another user's identity with a rogue Provider.</exception> + private async Task VerifyDiscoveryMatchesAssertionAsync(OpenIdRelyingParty relyingParty, CancellationToken cancellationToken) { Logger.OpenId.Debug("Verifying assertion matches identifier discovery results..."); // Ensure that we abide by the RP's rules regarding RequireSsl for this discovery step. @@ -163,7 +180,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { // is signed by the RP before it's considered reliable. In 1.x stateless mode, this RP // doesn't (and can't) sign its own return_to URL, so its cached discovery information // is merely a hint that must be verified by performing discovery again here. - var discoveryResults = relyingParty.Discover(claimedId); + var discoveryResults = await relyingParty.DiscoverAsync(claimedId, cancellationToken); ErrorUtilities.VerifyProtocol( discoveryResults.Contains(this.Endpoint), OpenIdStrings.IssuedAssertionFailsIdentifierDiscovery, diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty/packages.config b/src/DotNetOpenAuth.OpenId.RelyingParty/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OpenId.RelyingParty/packages.config +++ b/src/DotNetOpenAuth.OpenId.RelyingParty/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj b/src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj index a01c541..a76cc66 100644 --- a/src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj +++ b/src/DotNetOpenAuth.OpenId.UI/DotNetOpenAuth.OpenId.UI.csproj @@ -39,9 +39,9 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenId.UI/packages.config b/src/DotNetOpenAuth.OpenId.UI/packages.config index 58890d8..e3309bc 100644 --- a/src/DotNetOpenAuth.OpenId.UI/packages.config +++ b/src/DotNetOpenAuth.OpenId.UI/packages.config @@ -1,4 +1,4 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenId/DefaultOpenIdHostFactories.cs b/src/DotNetOpenAuth.OpenId/DefaultOpenIdHostFactories.cs new file mode 100644 index 0000000..cd41c72 --- /dev/null +++ b/src/DotNetOpenAuth.OpenId/DefaultOpenIdHostFactories.cs @@ -0,0 +1,58 @@ +//----------------------------------------------------------------------- +// <copyright file="DefaultOpenIdHostFactories.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.OpenId { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Cache; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + + /// <summary> + /// Creates default instances of required dependencies. + /// </summary> + public class DefaultOpenIdHostFactories : IHostFactories { + /// <summary> + /// Initializes a new instance of a concrete derivation of <see cref="HttpMessageHandler" /> + /// to be used for outbound HTTP traffic. + /// </summary> + /// <returns>An instance of <see cref="HttpMessageHandler"/>.</returns> + /// <remarks> + /// An instance of <see cref="WebRequestHandler" /> is recommended where available; + /// otherwise an instance of <see cref="HttpClientHandler" /> is recommended. + /// </remarks> + public virtual HttpMessageHandler CreateHttpMessageHandler() { + var handler = new UntrustedWebRequestHandler(); + ((WebRequestHandler)handler.InnerHandler).CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); + return handler; + } + + /// <summary> + /// Initializes a new instance of the <see cref="HttpClient" /> class + /// to be used for outbound HTTP traffic. + /// </summary> + /// <param name="handler">The handler to pass to the <see cref="HttpClient" /> constructor. + /// May be null to use the default that would be provided by <see cref="CreateHttpMessageHandler" />.</param> + /// <returns> + /// An instance of <see cref="HttpClient" />. + /// </returns> + public HttpClient CreateHttpClient(HttpMessageHandler handler) { + handler = handler ?? this.CreateHttpMessageHandler(); + var untrustedHandler = handler as UntrustedWebRequestHandler; + HttpClient client; + if (untrustedHandler != null) { + client = untrustedHandler.CreateClient(); + } else { + client = new HttpClient(handler); + } + + client.DefaultRequestHeaders.UserAgent.Add(Util.LibraryVersionHeader); + return client; + } + } +} diff --git a/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj b/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj index e238d58..ab4b6a7 100644 --- a/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj +++ b/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj @@ -30,6 +30,7 @@ <Compile Include="Configuration\OpenIdRelyingPartyElement.cs" /> <Compile Include="Configuration\OpenIdRelyingPartySecuritySettingsElement.cs" /> <Compile Include="Configuration\XriResolverElement.cs" /> + <Compile Include="DefaultOpenIdHostFactories.cs" /> <Compile Include="OpenIdXrdsHelperRelyingParty.cs" /> <Compile Include="OpenId\Association.cs" /> <Compile Include="OpenId\AuthenticationRequestMode.cs" /> @@ -141,6 +142,7 @@ <Compile Include="OpenId\Protocol.cs" /> <Compile Include="OpenId\IOpenIdApplicationStore.cs" /> <Compile Include="OpenId\RelyingParty\RelyingPartySecuritySettings.cs" /> + <Compile Include="OpenId\UntrustedWebRequestHandler.cs" /> <Compile Include="OpenId\UriDiscoveryService.cs" /> <Compile Include="OpenId\XriDiscoveryProxyService.cs" /> <Compile Include="OpenId\SecuritySettings.cs" /> @@ -183,9 +185,11 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs index ff8a766..4c55360 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/BackwardCompatibilityBindingElement.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Messages; @@ -17,6 +19,17 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </summary> internal class BackwardCompatibilityBindingElement : IChannelBindingElement { /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NoneTask = + Task.FromResult<MessageProtections?>(MessageProtections.None); + + /// <summary> /// The "dnoa.op_endpoint" callback parameter that stores the Provider Endpoint URL /// to tack onto the return_to URI. /// </summary> @@ -51,6 +64,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -59,7 +73,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { SignedResponseRequest request = message as SignedResponseRequest; if (request != null && request.Version.Major < 2) { request.AddReturnToArguments(ProviderEndpointParameterName, request.Recipient.AbsoluteUri); @@ -69,10 +83,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { request.AddReturnToArguments(ClaimedIdentifierParameterName, authRequest.ClaimedIdentifier); } - return MessageProtections.None; + return NoneTask; } - return null; + return NullTask; } /// <summary> @@ -80,6 +94,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -92,7 +107,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { IndirectSignedResponse response = message as IndirectSignedResponse; if (response != null && response.Version.Major < 2) { // GetReturnToArgument may return parameters that are not signed, @@ -118,10 +133,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { } } - return MessageProtections.None; + return NoneTask; } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs index f24c8b4..727dad7 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ExtensionsBindingElement.cs @@ -10,6 +10,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.Extensions; @@ -22,6 +24,17 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </summary> internal class ExtensionsBindingElement : IChannelBindingElement { /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NoneTask = + Task.FromResult<MessageProtections?>(MessageProtections.None); + + /// <summary> /// False if unsigned extensions should be dropped. Must always be true on Providers, since RPs never sign extensions. /// </summary> private readonly bool receiveUnsignedExtensions; @@ -68,6 +81,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -77,7 +91,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "It doesn't look too bad to me. :)")] - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var extendableMessage = message as IProtocolMessageWithExtensions; if (extendableMessage != null) { Protocol protocol = Protocol.Lookup(message.Version); @@ -120,10 +134,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { // Add the extension parameters to the base message for transmission. baseMessageDictionary.AddExtraParameters(extensionManager.GetArgumentsToSend(includeOpenIdPrefix)); - return MessageProtections.None; + return NoneTask; } - return null; + return NullTask; } /// <summary> @@ -131,6 +145,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -143,7 +158,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var extendableMessage = message as IProtocolMessageWithExtensions; if (extendableMessage != null) { // First add the extensions that are signed by the Provider. @@ -164,10 +179,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { } } - return MessageProtections.None; + return NoneTask; } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs index 6ad66c0..9c06e6b 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs @@ -11,6 +11,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Globalization; using System.IO; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using Validation; @@ -131,12 +133,13 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="data">The stream of Key-Value Form encoded bytes.</param> /// <returns>The deserialized dictionary.</returns> /// <exception cref="FormatException">Thrown when the data is not in the expected format.</exception> - public IDictionary<string, string> GetDictionary(Stream data) { + public async Task<IDictionary<string, string>> GetDictionaryAsync(Stream data, CancellationToken cancellationToken) { using (StreamReader reader = new StreamReader(data, textEncoding)) { var dict = new Dictionary<string, string>(); int line_num = 0; string line; - while ((line = reader.ReadLine()) != null) { + while ((line = await reader.ReadLineAsync()) != null) { + cancellationToken.ThrowIfCancellationRequested(); line_num++; if (this.ConformanceLevel == KeyValueFormConformanceLevel.Loose) { line = line.Trim(); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs index 5a6b8bb..89bcd77 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs @@ -7,12 +7,19 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Text; + using System.Threading; + using System.Threading.Tasks; + + using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId.Extensions; @@ -40,13 +47,14 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { private KeyValueFormEncoding keyValueForm = new KeyValueFormEncoding(); /// <summary> - /// Initializes a new instance of the <see cref="OpenIdChannel"/> class. + /// Initializes a new instance of the <see cref="OpenIdChannel" /> class. /// </summary> /// <param name="messageTypeProvider">A class prepared to analyze incoming messages and indicate what concrete /// message types can deserialize from it.</param> /// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param> - protected OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements) - : base(messageTypeProvider, bindingElements) { + /// <param name="hostFactories">The host factories.</param> + protected OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements, IHostFactories hostFactories) + : base(messageTypeProvider, bindingElements, hostFactories ?? new DefaultOpenIdHostFactories()) { Requires.NotNull(messageTypeProvider, "messageTypeProvider"); // Customize the binding element order, since we play some tricks for higher @@ -68,33 +76,30 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { } this.CustomizeBindingElementOrder(outgoingBindingElements, incomingBindingElements); - - // Change out the standard web request handler to reflect the standard - // OpenID pattern that outgoing web requests are to unknown and untrusted - // servers on the Internet. - this.WebRequestHandler = new UntrustedWebRequestHandler(); } /// <summary> /// Verifies the integrity and applicability of an incoming message. /// </summary> /// <param name="message">The message just received.</param> - /// <exception cref="ProtocolException"> - /// Thrown when the message is somehow invalid, except for check_authentication messages. - /// This can be due to tampering, replay attack or expiration, among other things. - /// </exception> - protected override void ProcessIncomingMessage(IProtocolMessage message) { + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + /// <exception cref="ProtocolException">Thrown when the message is somehow invalid, except for check_authentication messages. + /// This can be due to tampering, replay attack or expiration, among other things.</exception> + protected override async Task ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var checkAuthRequest = message as CheckAuthenticationRequest; if (checkAuthRequest != null) { IndirectSignedResponse originalResponse = new IndirectSignedResponse(checkAuthRequest, this); try { - base.ProcessIncomingMessage(originalResponse); + await base.ProcessIncomingMessageAsync(originalResponse, cancellationToken); checkAuthRequest.IsValid = true; } catch (ProtocolException) { checkAuthRequest.IsValid = false; } } else { - base.ProcessIncomingMessage(message); + await base.ProcessIncomingMessageAsync(message, cancellationToken); } // Convert an OpenID indirect error message, which we never expect @@ -120,7 +125,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <returns> /// The <see cref="HttpWebRequest"/> prepared to send the request. /// </returns> - protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { + protected override HttpRequestMessage CreateHttpRequest(IDirectedProtocolMessage request) { return this.InitializeRequestAsPost(request); } @@ -128,13 +133,16 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Gets the protocol message that may be in the given HTTP response. /// </summary> /// <param name="response">The response that is anticipated to contain an protocol message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The deserialized message parts, if found. Null otherwise. /// </returns> /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception> - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + protected override async Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken) { try { - return this.keyValueForm.GetDictionary(response.ResponseStream); + using (var responseStream = await response.Content.ReadAsStreamAsync()) { + return await this.keyValueForm.GetDictionaryAsync(responseStream, cancellationToken); + } } catch (FormatException ex) { throw ErrorUtilities.Wrap(ex, ex.Message); } @@ -145,7 +153,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </summary> /// <param name="response">The HTTP direct response.</param> /// <param name="message">The newly instantiated message, prior to deserialization.</param> - protected override void OnReceivingDirectResponse(IncomingWebResponse response, IDirectResponseProtocolMessage message) { + protected override void OnReceivingDirectResponse(HttpResponseMessage response, IDirectResponseProtocolMessage message) { base.OnReceivingDirectResponse(response, message); // Verify that the expected HTTP status code was used for the message, @@ -155,10 +163,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { var httpDirectResponse = message as IHttpDirectResponse; if (httpDirectResponse != null) { ErrorUtilities.VerifyProtocol( - httpDirectResponse.HttpStatusCode == response.Status, + httpDirectResponse.HttpStatusCode == response.StatusCode, MessagingStrings.UnexpectedHttpStatusCode, (int)httpDirectResponse.HttpStatusCode, - (int)response.Status); + (int)response.StatusCode); } } } @@ -174,55 +182,81 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <remarks> /// This method implements spec V1.0 section 5.3. /// </remarks> - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) { var messageAccessor = this.MessageDescriptions.GetAccessor(response); var fields = messageAccessor.Serialize(); byte[] keyValueEncoding = KeyValueFormEncoding.GetBytes(fields); - OutgoingWebResponse preparedResponse = new OutgoingWebResponse(); + var preparedResponse = new HttpResponseMessage(); ApplyMessageTemplate(response, preparedResponse); - preparedResponse.Headers.Add(HttpResponseHeader.ContentType, KeyValueFormContentType); - preparedResponse.OriginalMessage = response; - preparedResponse.ResponseStream = new MemoryStream(keyValueEncoding); + var content = new StreamContent(new MemoryStream(keyValueEncoding)); + content.Headers.ContentType = new MediaTypeHeaderValue(KeyValueFormContentType); + preparedResponse.Content = content; IHttpDirectResponse httpMessage = response as IHttpDirectResponse; if (httpMessage != null) { - preparedResponse.Status = httpMessage.HttpStatusCode; + preparedResponse.StatusCode = httpMessage.HttpStatusCode; } return preparedResponse; } /// <summary> - /// Gets the direct response of a direct HTTP request. + /// Provides derived-types the opportunity to wrap an <see cref="HttpMessageHandler" /> with another one. + /// </summary> + /// <param name="innerHandler">The inner handler received from <see cref="IHostFactories" /></param> + /// <returns> + /// The handler to use in <see cref="HttpClient" /> instances. + /// </returns> + protected override HttpMessageHandler WrapMessageHandler(HttpMessageHandler innerHandler) { + return new ErrorFilteringMessageHandler(base.WrapMessageHandler(innerHandler)); + } + + /// <summary> + /// An HTTP handler that throws an exception if the response message's HTTP status code doesn't fall + /// within those allowed by the OpenID spec. /// </summary> - /// <param name="webRequest">The web request.</param> - /// <returns>The response to the web request.</returns> - /// <exception cref="ProtocolException">Thrown on network or protocol errors.</exception> - protected override IncomingWebResponse GetDirectResponse(HttpWebRequest webRequest) { - IncomingWebResponse response = this.WebRequestHandler.GetResponse(webRequest, DirectWebRequestOptions.AcceptAllHttpResponses); - - // Filter the responses to the allowable set of HTTP status codes. - if (response.Status != HttpStatusCode.OK && response.Status != HttpStatusCode.BadRequest) { - if (Logger.Channel.IsErrorEnabled) { - using (var reader = new StreamReader(response.ResponseStream)) { + private class ErrorFilteringMessageHandler : DelegatingHandler { + /// <summary> + /// Initializes a new instance of the <see cref="ErrorFilteringMessageHandler" /> class. + /// </summary> + /// <param name="innerHandler">The inner handler which is responsible for processing the HTTP response messages.</param> + internal ErrorFilteringMessageHandler(HttpMessageHandler innerHandler) + : base(innerHandler) { + } + + /// <summary> + /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. + /// </summary> + /// <param name="request">The HTTP request message to send to the server.</param> + /// <param name="cancellationToken">A cancellation token to cancel operation.</param> + /// <returns> + /// Returns <see cref="T:System.Threading.Tasks.Task`1" />. The task object representing the asynchronous operation. + /// </returns> + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { + var response = await base.SendAsync(request, cancellationToken); + + // Filter the responses to the allowable set of HTTP status codes. + if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.BadRequest) { + if (Logger.Channel.IsErrorEnabled) { + var content = await response.Content.ReadAsStringAsync(); Logger.Channel.ErrorFormat( "Unexpected HTTP status code {0} {1} received in direct response:{2}{3}", - (int)response.Status, - response.Status, + (int)response.StatusCode, + response.StatusCode, Environment.NewLine, - reader.ReadToEnd()); + content); } - } - // Call dispose before throwing since we're not including the response in the - // exception we're throwing. - response.Dispose(); + // Call dispose before throwing since we're not including the response in the + // exception we're throwing. + response.Dispose(); - ErrorUtilities.ThrowProtocol(OpenIdStrings.UnexpectedHttpStatusCode, (int)response.Status, response.Status); - } + ErrorUtilities.ThrowProtocol(OpenIdStrings.UnexpectedHttpStatusCode, (int)response.StatusCode, response.StatusCode); + } - return response; + return response; + } } } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs index 726c01f..2aad922 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Collections.Generic; using System.Collections.Specialized; using System.Security.Cryptography; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; @@ -32,6 +34,17 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// </remarks> internal class ReturnToSignatureBindingElement : IChannelBindingElement { /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + + /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NoneTask = + Task.FromResult<MessageProtections?>(MessageProtections.None); + + /// <summary> /// The name of the callback parameter we'll tack onto the return_to value /// to store our signature on the return_to parameter. /// </summary> @@ -90,6 +103,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -98,7 +112,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { SignedResponseRequest request = message as SignedResponseRequest; if (request != null && request.ReturnTo != null && request.SignReturnTo) { var cryptoKeyPair = this.cryptoKeyStore.GetCurrentKey(SecretUri.AbsoluteUri, OpenIdElement.Configuration.MaxAuthenticationTime); @@ -107,10 +121,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { request.AddReturnToArguments(ReturnToSignatureParameterName, signature); // We return none because we are not signing the entire message (only a part). - return MessageProtections.None; + return NoneTask; } - return null; + return NullTask; } /// <summary> @@ -118,6 +132,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -130,7 +145,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { IndirectSignedResponse response = message as IndirectSignedResponse; if (response != null) { @@ -150,11 +165,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { Logger.Bindings.WarnFormat("The return_to signature failed verification."); } - return MessageProtections.None; + return NoneTask; } } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs index 584b0e9..8f602cf 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SigningBindingElement.cs @@ -11,6 +11,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Globalization; using System.Linq; using System.Net.Security; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Loggers; using DotNetOpenAuth.Messaging; @@ -23,6 +25,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Signs and verifies authentication assertions. /// </summary> internal abstract class SigningBindingElement : IChannelBindingElement { + /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + #region IChannelBindingElement Properties /// <summary> @@ -53,12 +60,13 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. /// </returns> - public virtual MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { - return null; + public virtual Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { + return NullTask; } /// <summary> @@ -66,6 +74,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -74,7 +83,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Thrown when the binding element rules indicate that this message is invalid and should /// NOT be processed. /// </exception> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public async Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var signedMessage = message as ITamperResistantOpenIdMessage; if (signedMessage != null) { Logger.Bindings.DebugFormat("Verifying incoming {0} message signature of: {1}", message.GetType().Name, signedMessage.Signature); @@ -92,7 +101,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { } else { ErrorUtilities.VerifyInternal(this.Channel != null, "Cannot verify private association signature because we don't have a channel."); - protectionsApplied = this.VerifySignatureByUnrecognizedHandle(message, signedMessage, protectionsApplied); + protectionsApplied = await this.VerifySignatureByUnrecognizedHandleAsync(message, signedMessage, protectionsApplied, cancellationToken); } return protectionsApplied; @@ -107,8 +116,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// <param name="message">The message.</param> /// <param name="signedMessage">The signed message.</param> /// <param name="protectionsApplied">The protections applied.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The applied protections.</returns> - protected abstract MessageProtections VerifySignatureByUnrecognizedHandle(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied); + protected abstract Task<MessageProtections> VerifySignatureByUnrecognizedHandleAsync(IProtocolMessage message, ITamperResistantOpenIdMessage signedMessage, MessageProtections protectionsApplied, CancellationToken cancellationToken); #endregion diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SkipSecurityBindingElement.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SkipSecurityBindingElement.cs index d162cf6..ad8d59e 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SkipSecurityBindingElement.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/SkipSecurityBindingElement.cs @@ -10,12 +10,19 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { using System.Diagnostics; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; /// <summary> /// Spoofs security checks on incoming OpenID messages. /// </summary> internal class SkipSecurityBindingElement : IChannelBindingElement { + /// <summary> + /// A reusable pre-completed task that may be returned multiple times to reduce GC pressure. + /// </summary> + private static readonly Task<MessageProtections?> NullTask = Task.FromResult<MessageProtections?>(null); + #region IChannelBindingElement Members /// <summary> @@ -42,6 +49,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Prepares a message for sending based on the rules of this channel binding element. /// </summary> /// <param name="message">The message to prepare for sending.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -50,7 +58,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { Debug.Fail("SkipSecurityBindingElement.ProcessOutgoingMessage should never be called."); return null; } @@ -60,6 +68,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// validates an incoming message based on the rules of this channel binding element. /// </summary> /// <param name="message">The incoming message to process.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The protections (if any) that this binding element applied to the message. /// Null if this binding element did not even apply to this binding element. @@ -72,14 +81,14 @@ namespace DotNetOpenAuth.OpenId.ChannelElements { /// Implementations that provide message protection must honor the /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable. /// </remarks> - public MessageProtections? ProcessIncomingMessage(IProtocolMessage message) { + public Task<MessageProtections?> ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var signedMessage = message as ITamperResistantOpenIdMessage; if (signedMessage != null) { Logger.Bindings.DebugFormat("Skipped security checks of incoming {0} message for preview purposes.", message.GetType().Name); - return this.Protection; + return Task.FromResult<MessageProtections?>(this.Protection); } - return null; + return NullTask; } #endregion diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs index ddd60f3..3f88d41 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Extensions/OpenIdExtensionFactoryAggregator.cs @@ -72,7 +72,7 @@ namespace DotNetOpenAuth.OpenId.Extensions { var factoriesElement = DotNetOpenAuth.Configuration.OpenIdElement.Configuration.ExtensionFactories; var aggregator = new OpenIdExtensionFactoryAggregator(); aggregator.Factories.Add(new StandardOpenIdExtensionFactory()); - aggregator.factories.AddRange(factoriesElement.CreateInstances(false)); + aggregator.factories.AddRange(factoriesElement.CreateInstances(false, null)); return aggregator; } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs index 20b8f1c..1055d15 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs @@ -10,7 +10,11 @@ namespace DotNetOpenAuth.OpenId { using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; + using System.Net.Http; + using System.Runtime.CompilerServices; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.RelyingParty; using Validation; @@ -23,13 +27,38 @@ namespace DotNetOpenAuth.OpenId { /// Performs discovery on the specified identifier. /// </summary> /// <param name="identifier">The identifier to perform discovery on.</param> - /// <param name="requestHandler">The means to place outgoing HTTP requests.</param> - /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty. /// </returns> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "By design")] - [Pure] - IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain); + Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken); + } + + /// <summary> + /// Describes the result of <see cref="IIdentifierDiscoveryService.DiscoverAsync"/>. + /// </summary> + public class IdentifierDiscoveryServiceResult { + /// <summary> + /// Initializes a new instance of the <see cref="IdentifierDiscoveryServiceResult" /> class. + /// </summary> + /// <param name="results">The results.</param> + /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param> + public IdentifierDiscoveryServiceResult(IEnumerable<IdentifierDiscoveryResult> results, bool abortDiscoveryChain = false) { + Requires.NotNull(results, "results"); + + this.Results = results; + this.AbortDiscoveryChain = abortDiscoveryChain; + } + + /// <summary> + /// Gets the results from this individual discovery service. + /// </summary> + public IEnumerable<IdentifierDiscoveryResult> Results { get; private set; } + + /// <summary> + /// Gets a value indicating whether no further discovery services should be called for this identifier. + /// </summary> + public bool AbortDiscoveryChain { get; private set; } } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs b/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs index 419cc84..cf52fef 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.OpenId { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text; using DotNetOpenAuth.Messaging; @@ -21,8 +22,8 @@ namespace DotNetOpenAuth.OpenId { SecuritySettings SecuritySettings { get; } /// <summary> - /// Gets the web request handler. + /// Gets the factory for various dependencies. /// </summary> - IDirectWebRequestHandler WebRequestHandler { get; } + IHostFactories HostFactories { get; } } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs index 1b20d4e..a515033 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs @@ -7,6 +7,9 @@ namespace DotNetOpenAuth.OpenId { using System.Collections.Generic; using System.Linq; + using System.Runtime.CompilerServices; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using Validation; @@ -33,7 +36,7 @@ namespace DotNetOpenAuth.OpenId { Requires.NotNull(host, "host"); this.host = host; - this.discoveryServices.AddRange(OpenIdElement.Configuration.RelyingParty.DiscoveryServices.CreateInstances(true)); + this.discoveryServices.AddRange(OpenIdElement.Configuration.RelyingParty.DiscoveryServices.CreateInstances(true, host.HostFactories)); } /// <summary> @@ -47,16 +50,16 @@ namespace DotNetOpenAuth.OpenId { /// Performs discovery on the specified identifier. /// </summary> /// <param name="identifier">The identifier to discover services for.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A non-null sequence of services discovered for the identifier.</returns> - public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) { + public async Task<IEnumerable<IdentifierDiscoveryResult>> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) { Requires.NotNull(identifier, "identifier"); IEnumerable<IdentifierDiscoveryResult> results = Enumerable.Empty<IdentifierDiscoveryResult>(); foreach (var discoverer in this.DiscoveryServices) { - bool abortDiscoveryChain; - var discoveryResults = discoverer.Discover(identifier, this.host.WebRequestHandler, out abortDiscoveryChain).CacheGeneratedResults(); - results = results.Concat(discoveryResults); - if (abortDiscoveryChain) { + var discoveryResults = await discoverer.DiscoverAsync(identifier, cancellationToken); + results = results.Concat(discoveryResults.Results.CacheGeneratedResults()); + if (discoveryResults.AbortDiscoveryChain) { Logger.OpenId.InfoFormat("Further discovery on '{0}' was stopped by the {1} discovery service.", identifier, discoverer.GetType().Name); break; } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs index 9aac107..cb5b856 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.OpenId.Messages { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using Validation; @@ -21,34 +23,19 @@ namespace DotNetOpenAuth.OpenId.Messages { /// <summary> /// Initializes a new instance of the <see cref="NegativeAssertionResponse"/> class. /// </summary> - /// <param name="request">The request that the relying party sent.</param> - internal NegativeAssertionResponse(CheckIdRequest request) - : this(request, null) { + /// <param name="version">The version.</param> + /// <param name="relyingPartyReturnTo">The relying party return to.</param> + /// <param name="mode">The value of the openid.mode parameter.</param> + internal NegativeAssertionResponse(Version version, Uri relyingPartyReturnTo, string mode) + : base(version, relyingPartyReturnTo, mode) { } /// <summary> /// Initializes a new instance of the <see cref="NegativeAssertionResponse"/> class. /// </summary> - /// <param name="request">The request that the relying party sent.</param> - /// <param name="channel">The channel to use to simulate construction of the user_setup_url, if applicable. May be null, but the user_setup_url will not be constructed.</param> - internal NegativeAssertionResponse(SignedResponseRequest request, Channel channel) + /// <param name="request">The request.</param> + internal NegativeAssertionResponse(SignedResponseRequest request) : base(request, GetMode(request)) { - // If appropriate, and when we're provided with a channel to do it, - // go ahead and construct the user_setup_url - if (this.Version.Major < 2 && request.Immediate && channel != null) { - // All requests are CheckIdRequests in OpenID 1.x, so this cast should be safe. - this.UserSetupUrl = ConstructUserSetupUrl((CheckIdRequest)request, channel); - } - } - - /// <summary> - /// Initializes a new instance of the <see cref="NegativeAssertionResponse"/> class. - /// </summary> - /// <param name="version">The version.</param> - /// <param name="relyingPartyReturnTo">The relying party return to.</param> - /// <param name="mode">The value of the openid.mode parameter.</param> - internal NegativeAssertionResponse(Version version, Uri relyingPartyReturnTo, string mode) - : base(version, relyingPartyReturnTo, mode) { } /// <summary> @@ -107,13 +94,34 @@ namespace DotNetOpenAuth.OpenId.Messages { } /// <summary> + /// Initializes a new instance of the <see cref="NegativeAssertionResponse" /> class. + /// </summary> + /// <param name="request">The request that the relying party sent.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="channel">The channel to use to simulate construction of the user_setup_url, if applicable. May be null, but the user_setup_url will not be constructed.</param> + /// <returns>The negative assertion message that will indicate failure for the user to authenticate or an unwillingness to log into the relying party.</returns> + internal static async Task<NegativeAssertionResponse> CreateAsync(SignedResponseRequest request, CancellationToken cancellationToken, Channel channel = null) { + var result = new NegativeAssertionResponse(request); + + // If appropriate, and when we're provided with a channel to do it, + // go ahead and construct the user_setup_url + if (result.Version.Major < 2 && request.Immediate && channel != null) { + // All requests are CheckIdRequests in OpenID 1.x, so this cast should be safe. + result.UserSetupUrl = await ConstructUserSetupUrlAsync((CheckIdRequest)request, channel, cancellationToken); + } + + return result; + } + + /// <summary> /// Constructs the value for the user_setup_url parameter to be sent back /// in negative assertions in response to OpenID 1.x RP's checkid_immediate requests. /// </summary> /// <param name="immediateRequest">The immediate request.</param> /// <param name="channel">The channel to use to simulate construction of the message.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The value to use for the user_setup_url parameter.</returns> - private static Uri ConstructUserSetupUrl(CheckIdRequest immediateRequest, Channel channel) { + private static async Task<Uri> ConstructUserSetupUrlAsync(CheckIdRequest immediateRequest, Channel channel, CancellationToken cancellationToken) { Requires.NotNull(immediateRequest, "immediateRequest"); Requires.NotNull(channel, "channel"); ErrorUtilities.VerifyInternal(immediateRequest.Immediate, "Only immediate requests should be sent here."); @@ -123,7 +131,8 @@ namespace DotNetOpenAuth.OpenId.Messages { setupRequest.ReturnTo = immediateRequest.ReturnTo; setupRequest.Realm = immediateRequest.Realm; setupRequest.AssociationHandle = immediateRequest.AssociationHandle; - return channel.PrepareResponse(setupRequest).GetDirectUriRequest(channel); + var response = await channel.PrepareResponseAsync(setupRequest, cancellationToken); + return response.GetDirectUriRequest(); } /// <summary> diff --git a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs index e04a633..b797f3a 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs @@ -11,12 +11,19 @@ namespace DotNetOpenAuth.OpenId { using System.Globalization; using System.IO; using System.Linq; + using System.Net; + using System.Net.Cache; + using System.Net.Http; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Web.UI; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Extensions; + using DotNetOpenAuth.OpenId.RelyingParty; + using Org.Mentalis.Security.Cryptography; using Validation; @@ -76,6 +83,24 @@ namespace DotNetOpenAuth.OpenId { } /// <summary> + /// Immediately sends a redirect response to the browser to initiate an authentication request. + /// </summary> + /// <param name="authenticationRequest">The authentication request to send via redirect.</param> + /// <param name="context">The context.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + public static async Task RedirectToProviderAsync(this IAuthenticationRequest authenticationRequest, HttpContextBase context = null, CancellationToken cancellationToken = default(CancellationToken)) { + Requires.NotNull(authenticationRequest, "authenticationRequest"); + Verify.Operation(context != null || HttpContext.Current != null, MessagingStrings.HttpContextRequired); + + context = context ?? new HttpContextWrapper(HttpContext.Current); + var response = await authenticationRequest.GetRedirectingResponseAsync(cancellationToken); + await response.SendAsync(context, cancellationToken); + } + + /// <summary> /// Gets the OpenID protocol instance for the version in a message. /// </summary> /// <param name="message">The message.</param> @@ -181,6 +206,51 @@ namespace DotNetOpenAuth.OpenId { } /// <summary> + /// Creates a new HTTP client for use by OpenID relying parties and providers. + /// </summary> + /// <param name="hostFactories">The host factories.</param> + /// <param name="requireSsl">if set to <c>true</c> [require SSL].</param> + /// <param name="cachePolicy">The cache policy.</param> + /// <returns>An HttpClient instance with appropriate caching policies set for OpenID operations.</returns> + internal static HttpClient CreateHttpClient(this IHostFactories hostFactories, bool requireSsl, RequestCachePolicy cachePolicy = null) { + Requires.NotNull(hostFactories, "hostFactories"); + + var rootHandler = hostFactories.CreateHttpMessageHandler(); + var handler = rootHandler; + bool sslRequiredSet = false, cachePolicySet = false; + do { + var webRequestHandler = handler as WebRequestHandler; + var untrustedHandler = handler as UntrustedWebRequestHandler; + var delegatingHandler = handler as DelegatingHandler; + if (webRequestHandler != null) { + if (cachePolicy != null) { + webRequestHandler.CachePolicy = cachePolicy; + cachePolicySet = true; + } + } else if (untrustedHandler != null) { + untrustedHandler.IsSslRequired = requireSsl; + sslRequiredSet = true; + } + + if (delegatingHandler != null) { + handler = delegatingHandler.InnerHandler; + } else { + break; + } + } + while (true); + + if (cachePolicy != null && !cachePolicySet) { + Logger.OpenId.Warn( + "Unable to set cache policy due to HttpMessageHandler instances not being of type WebRequestHandler."); + } + + ErrorUtilities.VerifyProtocol(!requireSsl || sslRequiredSet, "Unable to set RequireSsl on message handler because no HttpMessageHandler was of type {0}.", typeof(UntrustedWebRequestHandler).FullName); + + return hostFactories.CreateHttpClient(rootHandler); + } + + /// <summary> /// Gets the extension factories from the extension aggregator on an OpenID channel. /// </summary> /// <param name="channel">The channel.</param> diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs index 4a464b9..0615144 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs @@ -6,6 +6,9 @@ namespace DotNetOpenAuth.OpenId.Provider { using System; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; using Validation; @@ -45,7 +48,8 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <summary> /// Attempts to perform relying party discovery of the return URL claimed by the Relying Party. /// </summary> - /// <param name="webRequestHandler">The web request handler.</param> + /// <param name="hostFactories">The host factories.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The details of how successful the relying party discovery was. /// </returns> @@ -53,6 +57,6 @@ namespace DotNetOpenAuth.OpenId.Provider { /// <para>Return URL verification is only attempted if this method is called.</para> /// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para> /// </remarks> - RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(IDirectWebRequestHandler webRequestHandler); + Task<RelyingPartyDiscoveryResult> IsReturnUrlDiscoverableAsync(IHostFactories hostFactories = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs index 57fe66b..d7ec647 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IProviderBehavior.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.OpenId.Provider { using System; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.OpenId.ChannelElements; using Validation; @@ -28,6 +30,7 @@ namespace DotNetOpenAuth.OpenId.Provider { /// Called when a request is received by the Provider. /// </summary> /// <param name="request">The incoming request.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. @@ -37,16 +40,17 @@ namespace DotNetOpenAuth.OpenId.Provider { /// should not change the properties on the instance of <see cref="ProviderSecuritySettings"/> /// itself as that instance may be shared across many requests. /// </remarks> - bool OnIncomingRequest(IRequest request); + Task<bool> OnIncomingRequestAsync(IRequest request, CancellationToken cancellationToken); /// <summary> /// Called when the Provider is preparing to send a response to an authentication request. /// </summary> /// <param name="request">The request that is configured to generate the outgoing response.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// <c>true</c> if this behavior owns this request and wants to stop other behaviors /// from handling it; <c>false</c> to allow other behaviors to process this request. /// </returns> - bool OnOutgoingResponse(IAuthenticationRequest request); + Task<bool> OnOutgoingResponseAsync(IAuthenticationRequest request, CancellationToken cancellationToken); } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs index c1a959e..f6b4129 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs @@ -12,7 +12,10 @@ namespace DotNetOpenAuth.OpenId { using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; + using System.Net.Http; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Xml; using DotNetOpenAuth.Messaging; @@ -415,15 +418,16 @@ namespace DotNetOpenAuth.OpenId { /// Searches for an XRDS document at the realm URL, and if found, searches /// for a description of a relying party endpoints (OpenId login pages). /// </summary> - /// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param> + /// <param name="hostFactories">The host factories.</param> /// <param name="allowRedirects">Whether redirects may be followed when discovering the Realm. /// This may be true when creating an unsolicited assertion, but must be /// false when performing return URL verification per 2.0 spec section 9.2.1.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The details of the endpoints if found; or <c>null</c> if no service document was discovered. /// </returns> - internal virtual IEnumerable<RelyingPartyEndpointDescription> DiscoverReturnToEndpoints(IDirectWebRequestHandler requestHandler, bool allowRedirects) { - XrdsDocument xrds = this.Discover(requestHandler, allowRedirects); + internal virtual async Task<IEnumerable<RelyingPartyEndpointDescription>> DiscoverReturnToEndpointsAsync(IHostFactories hostFactories, bool allowRedirects, CancellationToken cancellationToken) { + XrdsDocument xrds = await this.DiscoverAsync(hostFactories, allowRedirects, cancellationToken); if (xrds != null) { return xrds.FindRelyingPartyReceivingEndpoints(); } @@ -434,16 +438,17 @@ namespace DotNetOpenAuth.OpenId { /// <summary> /// Searches for an XRDS document at the realm URL. /// </summary> - /// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param> + /// <param name="hostFactories">The host factories.</param> /// <param name="allowRedirects">Whether redirects may be followed when discovering the Realm. /// This may be true when creating an unsolicited assertion, but must be /// false when performing return URL verification per 2.0 spec section 9.2.1.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The XRDS document if found; or <c>null</c> if no service document was discovered. /// </returns> - internal virtual XrdsDocument Discover(IDirectWebRequestHandler requestHandler, bool allowRedirects) { + internal virtual async Task<XrdsDocument> DiscoverAsync(IHostFactories hostFactories, bool allowRedirects, CancellationToken cancellationToken) { // Attempt YADIS discovery - DiscoveryResult yadisResult = Yadis.Discover(requestHandler, this.UriWithWildcardChangedToWww, false); + DiscoveryResult yadisResult = await Yadis.DiscoverAsync(hostFactories, this.UriWithWildcardChangedToWww, false, cancellationToken); if (yadisResult != null) { // Detect disallowed redirects, since realm discovery never allows them for security. ErrorUtilities.VerifyProtocol(allowRedirects || yadisResult.NormalizedUri == yadisResult.RequestUri, OpenIdStrings.RealmCausedRedirectUponDiscovery, yadisResult.RequestUri); diff --git a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs index 886029c..3e922d4 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs @@ -8,7 +8,10 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.Messages; @@ -24,12 +27,6 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { AuthenticationRequestMode Mode { get; set; } /// <summary> - /// Gets the HTTP response the relying party should send to the user agent - /// to redirect it to the OpenID Provider to start the OpenID authentication process. - /// </summary> - OutgoingWebResponse RedirectingResponse { get; } - - /// <summary> /// Gets the URL that the user agent will return to after authentication /// completes or fails at the Provider. /// </summary> @@ -173,12 +170,11 @@ namespace DotNetOpenAuth.OpenId.RelyingParty { void AddExtension(IOpenIdMessageExtension extension); /// <summary> - /// Redirects the user agent to the provider for authentication. - /// Execution of the current page terminates after this call. + /// Gets the HTTP response the relying party should send to the user agent + /// to redirect it to the OpenID Provider to start the OpenID authentication process. /// </summary> - /// <remarks> - /// This method requires an ASP.NET HttpContext. - /// </remarks> - void RedirectToProvider(); + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The response message that will cause the client to redirect to the Provider.</returns> + Task<HttpResponseMessage> GetRedirectingResponseAsync(CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs b/src/DotNetOpenAuth.OpenId/OpenId/UntrustedWebRequestHandler.cs index be0182d..94d92e5 100644 --- a/src/DotNetOpenAuth.Core/Messaging/UntrustedWebRequestHandler.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/UntrustedWebRequestHandler.cs @@ -4,7 +4,7 @@ // </copyright> //----------------------------------------------------------------------- -namespace DotNetOpenAuth.Messaging { +namespace DotNetOpenAuth.OpenId { using System; using System.Collections.Generic; using System.Diagnostics; @@ -14,7 +14,10 @@ namespace DotNetOpenAuth.Messaging { using System.IO; using System.Net; using System.Net.Cache; + using System.Net.Http; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using Validation; @@ -33,7 +36,7 @@ namespace DotNetOpenAuth.Messaging { /// If a particular host would be permitted but is in the blacklist, it is not allowed. /// If a particular host would not be permitted but is in the whitelist, it is allowed. /// </remarks> - public class UntrustedWebRequestHandler : IDirectWebRequestHandler { + public class UntrustedWebRequestHandler : DelegatingHandler { /// <summary> /// The set of URI schemes allowed in untrusted web requests. /// </summary> @@ -63,113 +66,156 @@ namespace DotNetOpenAuth.Messaging { /// The maximum redirections to follow in the course of a single request. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private int maximumRedirections = Configuration.MaximumRedirections; + private int maxAutomaticRedirections = Configuration.MaximumRedirections; /// <summary> - /// The maximum number of bytes to read from the response of an untrusted server. + /// A value indicating whether to automatically follow redirects. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private int maximumBytesToRead = Configuration.MaximumBytesToRead; + private bool allowAutoRedirect = true; /// <summary> - /// The handler that will actually send the HTTP request and collect - /// the response once the untrusted server gates have been satisfied. + /// Initializes a new instance of the <see cref="UntrustedWebRequestHandler" /> class. /// </summary> - private IDirectWebRequestHandler chainedWebRequestHandler; - - /// <summary> - /// Initializes a new instance of the <see cref="UntrustedWebRequestHandler"/> class. - /// </summary> - public UntrustedWebRequestHandler() - : this(new StandardWebRequestHandler()) { - } - - /// <summary> - /// Initializes a new instance of the <see cref="UntrustedWebRequestHandler"/> class. - /// </summary> - /// <param name="chainedWebRequestHandler">The chained web request handler.</param> - public UntrustedWebRequestHandler(IDirectWebRequestHandler chainedWebRequestHandler) { - Requires.NotNull(chainedWebRequestHandler, "chainedWebRequestHandler"); + /// <param name="innerHandler"> + /// The inner handler. This handler will be modified to suit the purposes of this wrapping handler, + /// and should not be used independently of this wrapper after construction of this object. + /// </param> + public UntrustedWebRequestHandler(WebRequestHandler innerHandler = null) + : base(innerHandler ?? new WebRequestHandler()) { + // If SSL is required throughout, we cannot allow auto redirects because + // it may include a pass through an unprotected HTTP request. + // We have to follow redirects manually. + // It also allows us to ignore HttpWebResponse.FinalUri since that can be affected by + // the Content-Location header and open security holes. + this.MaxAutomaticRedirections = Configuration.MaximumRedirections; + this.InnerWebRequestHandler.AllowAutoRedirect = false; - this.chainedWebRequestHandler = chainedWebRequestHandler; if (Debugger.IsAttached) { // Since a debugger is attached, requests may be MUCH slower, // so give ourselves huge timeouts. - this.ReadWriteTimeout = TimeSpan.FromHours(1); - this.Timeout = TimeSpan.FromHours(1); + this.InnerWebRequestHandler.ReadWriteTimeout = (int)TimeSpan.FromHours(1).TotalMilliseconds; } else { - this.ReadWriteTimeout = Configuration.ReadWriteTimeout; - this.Timeout = Configuration.Timeout; + this.InnerWebRequestHandler.ReadWriteTimeout = (int)Configuration.ReadWriteTimeout.TotalMilliseconds; } } /// <summary> - /// Gets or sets the default maximum bytes to read in any given HTTP request. + /// Initializes a new instance of the <see cref="UntrustedWebRequestHandler"/> class + /// for use in unit testing. /// </summary> - /// <value>Default is 1MB. Cannot be less than 2KB.</value> - public int MaximumBytesToRead { - get { - return this.maximumBytesToRead; - } - - set { - Requires.Range(value >= 2048, "value"); - this.maximumBytesToRead = value; - } + /// <param name="innerHandler"> + /// The inner handler which is responsible for processing the HTTP response messages. + /// This handler should NOT automatically follow redirects. + /// </param> + internal UntrustedWebRequestHandler(HttpMessageHandler innerHandler) + : base(innerHandler) { } /// <summary> + /// Gets or sets a value indicating whether all requests must use SSL. + /// </summary> + /// <value> + /// <c>true</c> if SSL is required; otherwise, <c>false</c>. + /// </value> + public bool IsSslRequired { get; set; } + + /// <summary> /// Gets or sets the total number of redirections to allow on any one request. /// Default is 10. /// </summary> - public int MaximumRedirections { + public int MaxAutomaticRedirections { get { - return this.maximumRedirections; + return base.InnerHandler is WebRequestHandler ? this.InnerWebRequestHandler.MaxAutomaticRedirections : this.maxAutomaticRedirections; } set { Requires.Range(value >= 0, "value"); - this.maximumRedirections = value; + this.maxAutomaticRedirections = value; + if (base.InnerHandler is WebRequestHandler) { + this.InnerWebRequestHandler.MaxAutomaticRedirections = value; + } } } /// <summary> - /// Gets or sets the time allowed to wait for single read or write operation to complete. - /// Default is 500 milliseconds. + /// Gets or sets a value indicating whether to automatically follow redirects. /// </summary> - public TimeSpan ReadWriteTimeout { get; set; } + public bool AllowAutoRedirect { + get { + return base.InnerHandler is WebRequestHandler ? this.InnerWebRequestHandler.AllowAutoRedirect : this.allowAutoRedirect; + } + + set { + this.allowAutoRedirect = value; + if (base.InnerHandler is WebRequestHandler) { + this.InnerWebRequestHandler.AllowAutoRedirect = value; + } + } + } /// <summary> - /// Gets or sets the time allowed for an entire HTTP request. - /// Default is 5 seconds. + /// Gets or sets the time (in milliseconds) allowed to wait for single read or write operation to complete. + /// Default is 500 milliseconds. /// </summary> - public TimeSpan Timeout { get; set; } + public int ReadWriteTimeout { + get { return this.InnerWebRequestHandler.ReadWriteTimeout; } + set { this.InnerWebRequestHandler.ReadWriteTimeout = value; } + } /// <summary> /// Gets a collection of host name literals that should be allowed even if they don't /// pass standard security checks. /// </summary> - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Whitelist", Justification = "Spelling as intended.")] - public ICollection<string> WhitelistHosts { get { return this.whitelistHosts; } } + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Whitelist", + Justification = "Spelling as intended.")] + public ICollection<string> WhitelistHosts { + get { + return this.whitelistHosts; + } + } /// <summary> /// Gets a collection of host name regular expressions that indicate hosts that should /// be allowed even though they don't pass standard security checks. /// </summary> - [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Whitelist", Justification = "Spelling as intended.")] - public ICollection<Regex> WhitelistHostsRegex { get { return this.whitelistHostsRegex; } } + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Whitelist", + Justification = "Spelling as intended.")] + public ICollection<Regex> WhitelistHostsRegex { + get { + return this.whitelistHostsRegex; + } + } /// <summary> /// Gets a collection of host name literals that should be rejected even if they /// pass standard security checks. /// </summary> - public ICollection<string> BlacklistHosts { get { return this.blacklistHosts; } } + public ICollection<string> BlacklistHosts { + get { + return this.blacklistHosts; + } + } /// <summary> /// Gets a collection of host name regular expressions that indicate hosts that should /// be rejected even if they pass standard security checks. /// </summary> - public ICollection<Regex> BlacklistHostsRegex { get { return this.blacklistHostsRegex; } } + public ICollection<Regex> BlacklistHostsRegex { + get { + return this.blacklistHostsRegex; + } + } + + /// <summary> + /// Gets the inner web request handler. + /// </summary> + /// <value> + /// The inner web request handler. + /// </value> + public WebRequestHandler InnerWebRequestHandler { + get { return (WebRequestHandler)this.InnerHandler; } + } /// <summary> /// Gets the configuration for this class that is specified in the host's .config file. @@ -178,67 +224,61 @@ namespace DotNetOpenAuth.Messaging { get { return DotNetOpenAuthSection.Messaging.UntrustedWebRequest; } } - #region IDirectWebRequestHandler Members - /// <summary> - /// Determines whether this instance can support the specified options. + /// Creates an HTTP client that uses this instance as an HTTP handler. /// </summary> - /// <param name="options">The set of options that might be given in a subsequent web request.</param> - /// <returns> - /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>. - /// </returns> - [Pure] - public bool CanSupport(DirectWebRequestOptions options) { - // We support whatever our chained handler supports, plus RequireSsl. - return this.chainedWebRequestHandler.CanSupport(options & ~DirectWebRequestOptions.RequireSsl); + /// <returns>The initialized instance.</returns> + public HttpClient CreateClient() { + var client = new HttpClient(this); + client.MaxResponseContentBufferSize = Configuration.MaximumBytesToRead; + + if (Debugger.IsAttached) { + // Since a debugger is attached, requests may be MUCH slower, + // so give ourselves huge timeouts. + client.Timeout = TimeSpan.FromHours(1); + } else { + client.Timeout = Configuration.Timeout; + } + + return client; } /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. + /// Determines whether an exception was thrown because of the remote HTTP server returning HTTP 417 Expectation Failed. /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <param name="options">The options to apply to this web request.</param> + /// <param name="ex">The caught exception.</param> /// <returns> - /// The writer the caller should write out the entity data to. + /// <c>true</c> if the failure was originally caused by a 417 Exceptation Failed error; otherwise, <c>false</c>. /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/> - /// and any other appropriate properties <i>before</i> calling this method.</para> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch.</para> - /// </remarks> - public Stream GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) { - this.EnsureAllowableRequestUri(request.RequestUri, (options & DirectWebRequestOptions.RequireSsl) != 0); - - this.PrepareRequest(request, true); - - // Submit the request and get the request stream back. - return this.chainedWebRequestHandler.GetRequestStream(request, options & ~DirectWebRequestOptions.RequireSsl); + internal static bool IsExceptionFrom417ExpectationFailed(Exception ex) { + while (ex != null) { + WebException webEx = ex as WebException; + if (webEx != null) { + HttpWebResponse response = webEx.Response as HttpWebResponse; + if (response != null) { + if (response.StatusCode == HttpStatusCode.ExpectationFailed) { + return true; + } + } + } + + ex = ex.InnerException; + } + + return false; } /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. + /// Send an HTTP request as an asynchronous operation. /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <param name="options">The options to apply to this web request.</param> + /// <param name="request">The HTTP request message to send.</param> + /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <returns> - /// An instance of <see cref="CachedDirectWebResponse"/> describing the response. + /// Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation. /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Uri(Uri, string) accepts second arguments that Uri(Uri, new Uri(string)) does not that we must support.")] - public IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options) { - // This request MAY have already been prepared by GetRequestStream, but - // we have no guarantee, so do it just to be safe. - this.PrepareRequest(request, false); + protected override async Task<HttpResponseMessage> SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) { + this.EnsureAllowableRequestUri(request.RequestUri); // Since we may require SSL for every redirect, we handle each redirect manually // in order to detect and fail if any redirect sends us to an HTTP url. @@ -246,68 +286,47 @@ namespace DotNetOpenAuth.Messaging { // but our mock request infrastructure can't do redirects on its own either. Uri originalRequestUri = request.RequestUri; int i; - for (i = 0; i < this.MaximumRedirections; i++) { - this.EnsureAllowableRequestUri(request.RequestUri, (options & DirectWebRequestOptions.RequireSsl) != 0); - CachedDirectWebResponse response = this.chainedWebRequestHandler.GetResponse(request, options & ~DirectWebRequestOptions.RequireSsl).GetSnapshot(this.MaximumBytesToRead); - if (response.Status == HttpStatusCode.MovedPermanently || - response.Status == HttpStatusCode.Redirect || - response.Status == HttpStatusCode.RedirectMethod || - response.Status == HttpStatusCode.RedirectKeepVerb) { - // We have no copy of the post entity stream to repeat on our manually - // cloned HttpWebRequest, so we have to bail. - ErrorUtilities.VerifyProtocol(request.Method != "POST", MessagingStrings.UntrustedRedirectsOnPOSTNotSupported); - Uri redirectUri = new Uri(response.FinalUri, response.Headers[HttpResponseHeader.Location]); - request = request.Clone(redirectUri); - } else { - if (response.FinalUri != request.RequestUri) { - // Since we don't automatically follow redirects, there's only one scenario where this - // can happen: when the server sends a (non-redirecting) Content-Location header in the response. - // It's imperative that we do not trust that header though, so coerce the FinalUri to be - // what we just requested. - Logger.Http.WarnFormat("The response from {0} included an HTTP header indicating it's the same as {1}, but it's not a redirect so we won't trust that.", request.RequestUri, response.FinalUri); - response.FinalUri = request.RequestUri; + for (i = 0; i < this.MaxAutomaticRedirections; i++) { + this.EnsureAllowableRequestUri(request.RequestUri); + var response = await base.SendAsync(request, cancellationToken); + if (this.AllowAutoRedirect) { + if (response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Redirect + || response.StatusCode == HttpStatusCode.RedirectMethod + || response.StatusCode == HttpStatusCode.RedirectKeepVerb) { + // We have no copy of the post entity stream to repeat on our manually + // cloned HttpWebRequest, so we have to bail. + ErrorUtilities.VerifyProtocol( + request.Method != HttpMethod.Post, MessagingStrings.UntrustedRedirectsOnPOSTNotSupported); + Uri redirectUri = new Uri(request.RequestUri, response.Headers.Location); + request = request.Clone(); + request.RequestUri = redirectUri; + continue; } + } - return response; + if (response.StatusCode == HttpStatusCode.ExpectationFailed) { + // Some OpenID servers doesn't understand the Expect header and send 417 error back. + // If this server just failed from that, alter the ServicePoint for this server + // so that we don't send that header again next time (whenever that is). + // "Expect: 100-Continue" HTTP header. (see Google Code Issue 72) + // We don't want to blindly set all ServicePoints to not use the Expect header + // as that would be a security hole allowing any visitor to a web site change + // the web site's global behavior when calling that host. + // TODO: verify that this still works in DNOA 5.0 + var servicePoint = ServicePointManager.FindServicePoint(request.RequestUri); + Logger.Http.InfoFormat( + "HTTP POST to {0} resulted in 417 Expectation Failed. Changing ServicePoint to not use Expect: Continue next time.", + request.RequestUri); + servicePoint.Expect100Continue = false; } + + return response; } throw ErrorUtilities.ThrowProtocol(MessagingStrings.TooManyRedirects, originalRequestUri); } /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <returns> - /// The writer the caller should write out the entity data to. - /// </returns> - Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request) { - return this.GetRequestStream(request, DirectWebRequestOptions.None); - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <returns> - /// An instance of <see cref="IncomingWebResponse"/> describing the response. - /// </returns> - /// <exception cref="ProtocolException">Thrown for any network error.</exception> - /// <remarks> - /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a - /// <see cref="ProtocolException"/> to abstract away the transport and provide - /// a single exception type for hosts to catch. The <see cref="WebException.Response"/> - /// value, if set, should be Closed before throwing.</para> - /// </remarks> - IncomingWebResponse IDirectWebRequestHandler.GetResponse(HttpWebRequest request) { - return this.GetResponse(request, DirectWebRequestOptions.None); - } - - #endregion - - /// <summary> /// Determines whether an IP address is the IPv6 equivalent of "localhost/127.0.0.1". /// </summary> /// <param name="ip">The ip address to check.</param> @@ -380,11 +399,14 @@ namespace DotNetOpenAuth.Messaging { /// Verify that the request qualifies under our security policies /// </summary> /// <param name="requestUri">The request URI.</param> - /// <param name="requireSsl">If set to <c>true</c>, only web requests that can be made entirely over SSL will succeed.</param> /// <exception cref="ProtocolException">Thrown when the URI is disallowed for security reasons.</exception> - private void EnsureAllowableRequestUri(Uri requestUri, bool requireSsl) { - ErrorUtilities.VerifyProtocol(this.IsUriAllowable(requestUri), MessagingStrings.UnsafeWebRequestDetected, requestUri); - ErrorUtilities.VerifyProtocol(!requireSsl || string.Equals(requestUri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase), MessagingStrings.InsecureWebRequestWithSslRequired, requestUri); + private void EnsureAllowableRequestUri(Uri requestUri) { + ErrorUtilities.VerifyProtocol( + this.IsUriAllowable(requestUri), MessagingStrings.UnsafeWebRequestDetected, requestUri); + ErrorUtilities.VerifyProtocol( + !this.IsSslRequired || string.Equals(requestUri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase), + MessagingStrings.InsecureWebRequestWithSslRequired, + requestUri); } /// <summary> @@ -449,29 +471,5 @@ namespace DotNetOpenAuth.Messaging { } return true; } - - /// <summary> - /// Prepares the request by setting timeout and redirect policies. - /// </summary> - /// <param name="request">The request to prepare.</param> - /// <param name="preparingPost"><c>true</c> if this is a POST request whose headers have not yet been sent out; <c>false</c> otherwise.</param> - private void PrepareRequest(HttpWebRequest request, bool preparingPost) { - Requires.NotNull(request, "request"); - - // Be careful to not try to change the HTTP headers that have already gone out. - if (preparingPost || request.Method == "GET") { - // Set/override a few properties of the request to apply our policies for untrusted requests. - request.ReadWriteTimeout = (int)this.ReadWriteTimeout.TotalMilliseconds; - request.Timeout = (int)this.Timeout.TotalMilliseconds; - request.KeepAlive = false; - } - - // If SSL is required throughout, we cannot allow auto redirects because - // it may include a pass through an unprotected HTTP request. - // We have to follow redirects manually. - // It also allows us to ignore HttpWebResponse.FinalUri since that can be affected by - // the Content-Location header and open security holes. - request.AllowAutoRedirect = false; - } } } diff --git a/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs b/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs index c262ac9..7cb2a9a 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs @@ -8,47 +8,63 @@ namespace DotNetOpenAuth.OpenId { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; + using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using System.Web.UI.HtmlControls; using System.Xml; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Xrds; using DotNetOpenAuth.Yadis; + using Validation; /// <summary> /// The discovery service for URI identifiers. /// </summary> - public class UriDiscoveryService : IIdentifierDiscoveryService { + public class UriDiscoveryService : IIdentifierDiscoveryService, IRequireHostFactories { /// <summary> /// Initializes a new instance of the <see cref="UriDiscoveryService"/> class. /// </summary> public UriDiscoveryService() { } - #region IDiscoveryService Members + /// <summary> + /// Gets or sets the host factories used by this instance. + /// </summary> + /// <value> + /// The host factories. + /// </value> + public IHostFactories HostFactories { get; set; } + + #region IIdentifierDiscoveryService Members /// <summary> /// Performs discovery on the specified identifier. /// </summary> /// <param name="identifier">The identifier to perform discovery on.</param> - /// <param name="requestHandler">The means to place outgoing HTTP requests.</param> - /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty. /// </returns> - public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) { - abortDiscoveryChain = false; + public async Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) { + Requires.NotNull(identifier, "identifier"); + Verify.Operation(this.HostFactories != null, Strings.HostFactoriesRequired); + cancellationToken.ThrowIfCancellationRequested(); + var uriIdentifier = identifier as UriIdentifier; if (uriIdentifier == null) { - return Enumerable.Empty<IdentifierDiscoveryResult>(); + return new IdentifierDiscoveryServiceResult(Enumerable.Empty<IdentifierDiscoveryResult>()); } var endpoints = new List<IdentifierDiscoveryResult>(); // Attempt YADIS discovery - DiscoveryResult yadisResult = Yadis.Discover(requestHandler, uriIdentifier, identifier.IsDiscoverySecureEndToEnd); + DiscoveryResult yadisResult = await Yadis.DiscoverAsync(this.HostFactories, uriIdentifier, identifier.IsDiscoverySecureEndToEnd, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); if (yadisResult != null) { if (yadisResult.IsXrds) { try { @@ -67,7 +83,7 @@ namespace DotNetOpenAuth.OpenId { // Failing YADIS discovery of an XRDS document, we try HTML discovery. if (endpoints.Count == 0) { - yadisResult.TryRevertToHtmlResponse(); + await yadisResult.TryRevertToHtmlResponseAsync(); var htmlEndpoints = new List<IdentifierDiscoveryResult>(DiscoverFromHtml(yadisResult.NormalizedUri, uriIdentifier, yadisResult.ResponseText)); if (htmlEndpoints.Any()) { Logger.Yadis.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count); @@ -83,7 +99,8 @@ namespace DotNetOpenAuth.OpenId { Logger.Yadis.Debug("Skipping HTML discovery because XRDS contained service endpoints."); } } - return endpoints; + + return new IdentifierDiscoveryServiceResult(endpoints); } #endregion diff --git a/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs index a3e8345..bea8752 100644 --- a/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs +++ b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs @@ -10,7 +10,11 @@ namespace DotNetOpenAuth.OpenId { using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; + using System.Net.Http; + using System.Runtime.CompilerServices; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Xml; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; @@ -23,7 +27,7 @@ namespace DotNetOpenAuth.OpenId { /// The discovery service for XRI identifiers that uses an XRI proxy resolver for discovery. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xri", Justification = "Acronym")] - public class XriDiscoveryProxyService : IIdentifierDiscoveryService { + public class XriDiscoveryProxyService : IIdentifierDiscoveryService, IRequireHostFactories { /// <summary> /// The magic URL that will provide us an XRDS document for a given XRI identifier. /// </summary> @@ -42,25 +46,33 @@ namespace DotNetOpenAuth.OpenId { public XriDiscoveryProxyService() { } + /// <summary> + /// Gets or sets the host factories used by this instance. + /// </summary> + public IHostFactories HostFactories { get; set; } + #region IDiscoveryService Members /// <summary> /// Performs discovery on the specified identifier. /// </summary> /// <param name="identifier">The identifier to perform discovery on.</param> - /// <param name="requestHandler">The means to place outgoing HTTP requests.</param> - /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty. /// </returns> - public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) { - abortDiscoveryChain = false; + public async Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) { + Requires.NotNull(identifier, "identifier"); + Verify.Operation(this.HostFactories != null, Strings.HostFactoriesRequired); + var xriIdentifier = identifier as XriIdentifier; if (xriIdentifier == null) { - return Enumerable.Empty<IdentifierDiscoveryResult>(); + return new IdentifierDiscoveryServiceResult(Enumerable.Empty<IdentifierDiscoveryResult>()); } - return DownloadXrds(xriIdentifier, requestHandler).XrdElements.CreateServiceEndpoints(xriIdentifier); + var xrds = await DownloadXrdsAsync(xriIdentifier, this.HostFactories, cancellationToken); + var endpoints = xrds.XrdElements.CreateServiceEndpoints(xriIdentifier); + return new IdentifierDiscoveryServiceResult(endpoints); } #endregion @@ -69,16 +81,26 @@ namespace DotNetOpenAuth.OpenId { /// Downloads the XRDS document for this XRI. /// </summary> /// <param name="identifier">The identifier.</param> - /// <param name="requestHandler">The request handler.</param> - /// <returns>The XRDS document.</returns> - private static XrdsDocument DownloadXrds(XriIdentifier identifier, IDirectWebRequestHandler requestHandler) { + /// <param name="hostFactories">The host factories.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The XRDS document. + /// </returns> + private static async Task<XrdsDocument> DownloadXrdsAsync(XriIdentifier identifier, IHostFactories hostFactories, CancellationToken cancellationToken) { Requires.NotNull(identifier, "identifier"); - Requires.NotNull(requestHandler, "requestHandler"); + Requires.NotNull(hostFactories, "hostFactories"); + XrdsDocument doc; - using (var xrdsResponse = Yadis.Request(requestHandler, GetXrdsUrl(identifier), identifier.IsDiscoverySecureEndToEnd)) { + using (var xrdsResponse = await Yadis.RequestAsync(GetXrdsUrl(identifier), identifier.IsDiscoverySecureEndToEnd, hostFactories, cancellationToken)) { + xrdsResponse.EnsureSuccessStatusCode(); var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings(); - doc = new XrdsDocument(XmlReader.Create(xrdsResponse.ResponseStream, readerSettings)); + ErrorUtilities.VerifyProtocol(xrdsResponse.Content != null, "XRDS request \"{0}\" returned no response.", GetXrdsUrl(identifier)); + await xrdsResponse.Content.LoadIntoBufferAsync(); + using (var xrdsStream = await xrdsResponse.Content.ReadAsStreamAsync()) { + doc = new XrdsDocument(XmlReader.Create(xrdsStream, readerSettings)); + } } + ErrorUtilities.VerifyProtocol(doc.IsXrdResolutionSuccessful, OpenIdStrings.XriResolutionFailed); return doc; } diff --git a/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs b/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs index 06c6fc7..8266ff0 100644 --- a/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs +++ b/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs @@ -7,10 +7,15 @@ namespace DotNetOpenAuth.Yadis { using System; using System.IO; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Net.Mime; + using System.Threading.Tasks; using System.Web.UI.HtmlControls; using System.Xml; using DotNetOpenAuth.Messaging; + using Validation; /// <summary> /// Contains the result of YADIS discovery. @@ -20,30 +25,12 @@ namespace DotNetOpenAuth.Yadis { /// The original web response, backed up here if the final web response is the preferred response to use /// in case it turns out to not work out. /// </summary> - private CachedDirectWebResponse htmlFallback; + private HttpResponseMessage htmlFallback; /// <summary> - /// Initializes a new instance of the <see cref="DiscoveryResult"/> class. + /// Prevents a default instance of the <see cref="DiscoveryResult" /> class from being created. /// </summary> - /// <param name="requestUri">The user-supplied identifier.</param> - /// <param name="initialResponse">The initial response.</param> - /// <param name="finalResponse">The final response.</param> - public DiscoveryResult(Uri requestUri, CachedDirectWebResponse initialResponse, CachedDirectWebResponse finalResponse) { - this.RequestUri = requestUri; - this.NormalizedUri = initialResponse.FinalUri; - if (finalResponse == null || finalResponse.Status != System.Net.HttpStatusCode.OK) { - this.ApplyHtmlResponse(initialResponse); - } else { - this.ContentType = finalResponse.ContentType; - this.ResponseText = finalResponse.GetResponseString(); - this.IsXrds = true; - if (initialResponse != finalResponse) { - this.YadisLocation = finalResponse.RequestUri; - } - - // Back up the initial HTML response in case the XRDS is not useful. - this.htmlFallback = initialResponse; - } + private DiscoveryResult() { } /// <summary> @@ -68,7 +55,7 @@ namespace DotNetOpenAuth.Yadis { /// <summary> /// Gets the Content-Type associated with the <see cref="ResponseText"/>. /// </summary> - public ContentType ContentType { get; private set; } + public MediaTypeHeaderValue ContentType { get; private set; } /// <summary> /// Gets the text in the final response. @@ -84,11 +71,42 @@ namespace DotNetOpenAuth.Yadis { public bool IsXrds { get; private set; } /// <summary> + /// Initializes a new instance of the <see cref="DiscoveryResult"/> class. + /// </summary> + /// <param name="requestUri">The request URI.</param> + /// <param name="initialResponse">The initial response.</param> + /// <param name="finalResponse">The final response.</param> + /// <returns>The newly initialized instance.</returns> + internal static async Task<DiscoveryResult> CreateAsync(Uri requestUri, HttpResponseMessage initialResponse, HttpResponseMessage finalResponse) { + var result = new DiscoveryResult(); + result.RequestUri = requestUri; + result.NormalizedUri = initialResponse.RequestMessage.RequestUri; + if (finalResponse == null || finalResponse.StatusCode != HttpStatusCode.OK) { + await result.ApplyHtmlResponseAsync(initialResponse); + } else { + result.ContentType = finalResponse.Content.Headers.ContentType; + result.ResponseText = await finalResponse.Content.ReadAsStringAsync(); + result.IsXrds = true; + if (initialResponse != finalResponse) { + result.YadisLocation = finalResponse.RequestMessage.RequestUri; + } + + // Back up the initial HTML response in case the XRDS is not useful. + result.htmlFallback = initialResponse; + } + + return result; + } + + /// <summary> /// Reverts to the HTML response after the XRDS response didn't work out. /// </summary> - internal void TryRevertToHtmlResponse() { + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + internal async Task TryRevertToHtmlResponseAsync() { if (this.htmlFallback != null) { - this.ApplyHtmlResponse(this.htmlFallback); + await this.ApplyHtmlResponseAsync(this.htmlFallback); this.htmlFallback = null; } } @@ -96,10 +114,15 @@ namespace DotNetOpenAuth.Yadis { /// <summary> /// Applies the HTML response to the object. /// </summary> - /// <param name="initialResponse">The initial response.</param> - private void ApplyHtmlResponse(CachedDirectWebResponse initialResponse) { - this.ContentType = initialResponse.ContentType; - this.ResponseText = initialResponse.GetResponseString(); + /// <param name="response">The initial response.</param> + /// <returns> + /// A task that completes with the asynchronous operation. + /// </returns> + private async Task ApplyHtmlResponseAsync(HttpResponseMessage response) { + Requires.NotNull(response, "response"); + + this.ContentType = response.Content.Headers.ContentType; + this.ResponseText = await response.Content.ReadAsStringAsync(); this.IsXrds = this.ContentType != null && this.ContentType.MediaType == ContentTypes.Xrds; } } diff --git a/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs index 4a06ea7..77d4926 100644 --- a/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs +++ b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs @@ -6,9 +6,15 @@ namespace DotNetOpenAuth.Yadis { using System; + using System.Collections.Generic; using System.IO; + using System.Linq; using System.Net; using System.Net.Cache; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading; + using System.Threading.Tasks; using System.Web.UI.HtmlControls; using System.Xml; using DotNetOpenAuth.Configuration; @@ -44,39 +50,51 @@ namespace DotNetOpenAuth.Yadis { /// <summary> /// Performs YADIS discovery on some identifier. /// </summary> - /// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param> + /// <param name="hostFactories">The host factories.</param> /// <param name="uri">The URI to perform discovery on.</param> /// <param name="requireSsl">Whether discovery should fail if any step of it is not encrypted.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The result of discovery on the given URL. /// Null may be returned if an error occurs, - /// or if <paramref name="requireSsl"/> is true but part of discovery + /// or if <paramref name="requireSsl" /> is true but part of discovery /// is not protected by SSL. /// </returns> - public static DiscoveryResult Discover(IDirectWebRequestHandler requestHandler, UriIdentifier uri, bool requireSsl) { - CachedDirectWebResponse response; + public static async Task<DiscoveryResult> DiscoverAsync(IHostFactories hostFactories, UriIdentifier uri, bool requireSsl, CancellationToken cancellationToken) { + Requires.NotNull(hostFactories, "hostFactories"); + Requires.NotNull(uri, "uri"); + + HttpResponseMessage response; try { if (requireSsl && !string.Equals(uri.Uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { Logger.Yadis.WarnFormat("Discovery on insecure identifier '{0}' aborted.", uri); return null; } - response = Request(requestHandler, uri, requireSsl, ContentTypes.Html, ContentTypes.XHtml, ContentTypes.Xrds).GetSnapshot(MaximumResultToScan); - if (response.Status != System.Net.HttpStatusCode.OK) { - Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response.Status, response.Status, uri); + + response = await RequestAsync(uri, requireSsl, hostFactories, cancellationToken, ContentTypes.Html, ContentTypes.XHtml, ContentTypes.Xrds); + if (response.StatusCode != System.Net.HttpStatusCode.OK) { + Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response.StatusCode, response.StatusCode, uri); return null; } + + await response.Content.LoadIntoBufferAsync(); } catch (ArgumentException ex) { // Unsafe URLs generate this Logger.Yadis.WarnFormat("Unsafe OpenId URL detected ({0}). Request aborted. {1}", uri, ex); return null; } - CachedDirectWebResponse response2 = null; - if (IsXrdsDocument(response)) { + HttpResponseMessage response2 = null; + if (await IsXrdsDocumentAsync(response)) { Logger.Yadis.Debug("An XRDS response was received from GET at user-supplied identifier."); Reporting.RecordEventOccurrence("Yadis", "XRDS in initial response"); response2 = response; } else { - string uriString = response.Headers.Get(HeaderName); + IEnumerable<string> uriStrings; + string uriString = null; + if (response.Headers.TryGetValues(HeaderName, out uriStrings)) { + uriString = uriStrings.FirstOrDefault(); + } + Uri url = null; if (uriString != null) { if (Uri.TryCreate(uriString, UriKind.Absolute, out url)) { @@ -84,8 +102,10 @@ namespace DotNetOpenAuth.Yadis { Reporting.RecordEventOccurrence("Yadis", "XRDS referenced in HTTP header"); } } - if (url == null && response.ContentType != null && (response.ContentType.MediaType == ContentTypes.Html || response.ContentType.MediaType == ContentTypes.XHtml)) { - url = FindYadisDocumentLocationInHtmlMetaTags(response.GetResponseString()); + + var contentType = response.Content.Headers.ContentType; + if (url == null && contentType != null && (contentType.MediaType == ContentTypes.Html || contentType.MediaType == ContentTypes.XHtml)) { + url = FindYadisDocumentLocationInHtmlMetaTags(await response.Content.ReadAsStringAsync()); if (url != null) { Logger.Yadis.DebugFormat("{0} found in HTML Http-Equiv tag. Preparing to pull XRDS from {1}", HeaderName, url); Reporting.RecordEventOccurrence("Yadis", "XRDS referenced in HTML"); @@ -93,16 +113,17 @@ namespace DotNetOpenAuth.Yadis { } if (url != null) { if (!requireSsl || string.Equals(url.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { - response2 = Request(requestHandler, url, requireSsl, ContentTypes.Xrds).GetSnapshot(MaximumResultToScan); - if (response2.Status != HttpStatusCode.OK) { - Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response2.Status, response2.Status, uri); + response2 = await RequestAsync(url, requireSsl, hostFactories, cancellationToken, ContentTypes.Xrds); + if (response2.StatusCode != HttpStatusCode.OK) { + Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response2.StatusCode, response2.StatusCode, uri); } } else { Logger.Yadis.WarnFormat("XRDS document at insecure location '{0}'. Aborting YADIS discovery.", url); } } } - return new DiscoveryResult(uri, response, response2); + + return await DiscoveryResult.CreateAsync(uri, response, response2); } /// <summary> @@ -129,43 +150,45 @@ namespace DotNetOpenAuth.Yadis { /// <summary> /// Sends a YADIS HTTP request as part of identifier discovery. /// </summary> - /// <param name="requestHandler">The request handler to use to actually submit the request.</param> /// <param name="uri">The URI to GET.</param> /// <param name="requireSsl">Whether only HTTPS URLs should ever be retrieved.</param> + /// <param name="hostFactories">The host factories.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <param name="acceptTypes">The value of the Accept HTTP header to include in the request.</param> - /// <returns>The HTTP response retrieved from the request.</returns> - internal static IncomingWebResponse Request(IDirectWebRequestHandler requestHandler, Uri uri, bool requireSsl, params string[] acceptTypes) { - Requires.NotNull(requestHandler, "requestHandler"); + /// <returns> + /// The HTTP response retrieved from the request. + /// </returns> + internal static async Task<HttpResponseMessage> RequestAsync(Uri uri, bool requireSsl, IHostFactories hostFactories, CancellationToken cancellationToken, params string[] acceptTypes) { Requires.NotNull(uri, "uri"); + Requires.NotNull(hostFactories, "hostFactories"); - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); - request.CachePolicy = IdentifierDiscoveryCachePolicy; - if (acceptTypes != null) { - request.Accept = string.Join(",", acceptTypes); - } - - DirectWebRequestOptions options = DirectWebRequestOptions.None; - if (requireSsl) { - options |= DirectWebRequestOptions.RequireSsl; - } + using (var httpClient = hostFactories.CreateHttpClient(requireSsl, IdentifierDiscoveryCachePolicy)) { + var request = new HttpRequestMessage(HttpMethod.Get, uri); + if (acceptTypes != null) { + request.Headers.Accept.AddRange(acceptTypes.Select(at => new MediaTypeWithQualityHeaderValue(at))); + } - try { - return requestHandler.GetResponse(request, options); - } catch (ProtocolException ex) { - var webException = ex.InnerException as WebException; - if (webException != null) { - var response = webException.Response as HttpWebResponse; - if (response != null && response.IsFromCache) { + HttpResponseMessage response = null; + try { + response = await httpClient.SendAsync(request, cancellationToken); + // http://stackoverflow.com/questions/14103154/how-to-determine-if-an-httpresponsemessage-was-fulfilled-from-cache-using-httpcl + if (!response.IsSuccessStatusCode && response.Headers.Age.HasValue && response.Headers.Age.Value > TimeSpan.Zero) { // We don't want to report error responses from the cache, since the server may have fixed // whatever was causing the problem. So try again with cache disabled. - Logger.Messaging.Error("An HTTP error response was obtained from the cache. Retrying with cache disabled.", ex); + Logger.Messaging.ErrorFormat("An HTTP {0} response was obtained from the cache. Retrying with cache disabled.", response.StatusCode); + response.Dispose(); // discard the old one + var nonCachingRequest = request.Clone(); - nonCachingRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Reload); - return requestHandler.GetResponse(nonCachingRequest, options); + using (var nonCachingHttpClient = hostFactories.CreateHttpClient(requireSsl, new RequestCachePolicy(RequestCacheLevel.Reload))) { + response = await nonCachingHttpClient.SendAsync(nonCachingRequest, cancellationToken); + } } - } - throw; + return response; + } catch { + response.DisposeIfNotNull(); + throw; + } } } @@ -176,25 +199,26 @@ namespace DotNetOpenAuth.Yadis { /// <returns> /// <c>true</c> if the response constains an XRDS document; otherwise, <c>false</c>. /// </returns> - private static bool IsXrdsDocument(CachedDirectWebResponse response) { - if (response.ContentType == null) { + private static async Task<bool> IsXrdsDocumentAsync(HttpResponseMessage response) { + if (response.Content.Headers.ContentType == null) { return false; } - if (response.ContentType.MediaType == ContentTypes.Xrds) { + if (response.Content.Headers.ContentType.MediaType == ContentTypes.Xrds) { return true; } - if (response.ContentType.MediaType == ContentTypes.Xml) { + if (response.Content.Headers.ContentType.MediaType == ContentTypes.Xml) { // This COULD be an XRDS document with an imprecise content-type. - response.ResponseStream.Seek(0, SeekOrigin.Begin); - var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings(); - XmlReader reader = XmlReader.Create(response.ResponseStream, readerSettings); - while (reader.Read() && reader.NodeType != XmlNodeType.Element) { - // intentionally blank - } - if (reader.NamespaceURI == XrdsNode.XrdsNamespace && reader.Name == "XRDS") { - return true; + using (var responseStream = await response.Content.ReadAsStreamAsync()) { + var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings(); + XmlReader reader = XmlReader.Create(responseStream, readerSettings); + while (await reader.ReadAsync() && reader.NodeType != XmlNodeType.Element) { + // intentionally blank + } + if (reader.NamespaceURI == XrdsNode.XrdsNamespace && reader.Name == "XRDS") { + return true; + } } } diff --git a/src/DotNetOpenAuth.OpenId/packages.config b/src/DotNetOpenAuth.OpenId/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OpenId/packages.config +++ b/src/DotNetOpenAuth.OpenId/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj b/src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj index ed05c2d..8c71fb5 100644 --- a/src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj +++ b/src/DotNetOpenAuth.OpenIdInfoCard.UI/DotNetOpenAuth.OpenIdInfoCard.UI.csproj @@ -64,9 +64,11 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenIdInfoCard.UI/packages.config b/src/DotNetOpenAuth.OpenIdInfoCard.UI/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OpenIdInfoCard.UI/packages.config +++ b/src/DotNetOpenAuth.OpenIdInfoCard.UI/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.OpenIdOAuth/DotNetOpenAuth.OpenIdOAuth.csproj b/src/DotNetOpenAuth.OpenIdOAuth/DotNetOpenAuth.OpenIdOAuth.csproj index 0670297..6f4c60d 100644 --- a/src/DotNetOpenAuth.OpenIdOAuth/DotNetOpenAuth.OpenIdOAuth.csproj +++ b/src/DotNetOpenAuth.OpenIdOAuth/DotNetOpenAuth.OpenIdOAuth.csproj @@ -54,9 +54,11 @@ </ProjectReference> </ItemGroup> <ItemGroup> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> diff --git a/src/DotNetOpenAuth.OpenIdOAuth/OAuth/ServiceProviderOpenIdProvider.cs b/src/DotNetOpenAuth.OpenIdOAuth/OAuth/ServiceProviderOpenIdProvider.cs index f827857..1c0c5fb 100644 --- a/src/DotNetOpenAuth.OpenIdOAuth/OAuth/ServiceProviderOpenIdProvider.cs +++ b/src/DotNetOpenAuth.OpenIdOAuth/OAuth/ServiceProviderOpenIdProvider.cs @@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OAuth { /// </summary> /// <param name="serviceDescription">The endpoints and behavior on the Service Provider.</param> /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> - public ServiceProviderOpenIdProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager) + public ServiceProviderOpenIdProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager) : base(serviceDescription, tokenManager) { } @@ -51,7 +51,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="serviceDescription">The service description.</param> /// <param name="tokenManager">The token manager.</param> /// <param name="messageTypeProvider">The message type provider.</param> - public ServiceProviderOpenIdProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, OAuthServiceProviderMessageFactory messageTypeProvider) + public ServiceProviderOpenIdProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager, OAuthServiceProviderMessageFactory messageTypeProvider) : base(serviceDescription, tokenManager, messageTypeProvider) { } @@ -61,7 +61,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="serviceDescription">The service description.</param> /// <param name="tokenManager">The token manager.</param> /// <param name="nonceStore">The nonce store.</param> - public ServiceProviderOpenIdProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore) + public ServiceProviderOpenIdProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore) : base(serviceDescription, tokenManager, nonceStore) { } @@ -72,7 +72,7 @@ namespace DotNetOpenAuth.OAuth { /// <param name="tokenManager">The token manager.</param> /// <param name="nonceStore">The nonce store.</param> /// <param name="messageTypeProvider">The message type provider.</param> - public ServiceProviderOpenIdProvider(ServiceProviderDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore, OAuthServiceProviderMessageFactory messageTypeProvider) + public ServiceProviderOpenIdProvider(ServiceProviderHostDescription serviceDescription, IServiceProviderTokenManager tokenManager, INonceStore nonceStore, OAuthServiceProviderMessageFactory messageTypeProvider) : base(serviceDescription, tokenManager, nonceStore, messageTypeProvider) { } diff --git a/src/DotNetOpenAuth.OpenIdOAuth/OAuth/WebConsumerOpenIdRelyingParty.cs b/src/DotNetOpenAuth.OpenIdOAuth/OAuth/WebConsumerOpenIdRelyingParty.cs index 7c77e4f..dce51c2 100644 --- a/src/DotNetOpenAuth.OpenIdOAuth/OAuth/WebConsumerOpenIdRelyingParty.cs +++ b/src/DotNetOpenAuth.OpenIdOAuth/OAuth/WebConsumerOpenIdRelyingParty.cs @@ -8,7 +8,11 @@ namespace DotNetOpenAuth.OAuth { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; + using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; @@ -24,14 +28,13 @@ namespace DotNetOpenAuth.OAuth { /// The methods on this class are thread-safe. Provided the properties are set and not changed /// afterward, a single instance of this class may be used by an entire web application safely. /// </remarks> - public class WebConsumerOpenIdRelyingParty : WebConsumer { + public class WebConsumerOpenIdRelyingParty : Consumer { /// <summary> /// Initializes a new instance of the <see cref="WebConsumerOpenIdRelyingParty"/> class. /// </summary> /// <param name="serviceDescription">The endpoints and behavior of the Service Provider.</param> /// <param name="tokenManager">The host's method of storing and recalling tokens and secrets.</param> - public WebConsumerOpenIdRelyingParty(ServiceProviderDescription serviceDescription, IConsumerTokenManager tokenManager) - : base(serviceDescription, tokenManager) { + public WebConsumerOpenIdRelyingParty() { } /// <summary> @@ -54,18 +57,16 @@ namespace DotNetOpenAuth.OAuth { /// Processes an incoming authorization-granted message from an SP and obtains an access token. /// </summary> /// <param name="openIdAuthenticationResponse">The OpenID authentication response that may be carrying an authorized request token.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The access token, or null if OAuth authorization was denied by the user or service provider. /// </returns> /// <remarks> - /// The access token, if granted, is automatically stored in the <see cref="ConsumerBase.TokenManager"/>. - /// The token manager instance must implement <see cref="IOpenIdOAuthTokenManager"/>. + /// The access token, if granted, is automatically stored in the <see cref="ConsumerBase.TokenManager" />. + /// The token manager instance must implement <see cref="IOpenIdOAuthTokenManager" />. /// </remarks> - public AuthorizedTokenResponse ProcessUserAuthorization(IAuthenticationResponse openIdAuthenticationResponse) { + public async Task<AccessTokenResponse> ProcessUserAuthorizationAsync(IAuthenticationResponse openIdAuthenticationResponse, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(openIdAuthenticationResponse, "openIdAuthenticationResponse"); - RequiresEx.ValidState(this.TokenManager is IOpenIdOAuthTokenManager); - var openidTokenManager = this.TokenManager as IOpenIdOAuthTokenManager; - ErrorUtilities.VerifyOperation(openidTokenManager != null, OAuthStrings.OpenIdOAuthExtensionRequiresSpecialTokenManagerInterface, typeof(IOpenIdOAuthTokenManager).FullName); // The OAuth extension is only expected in positive assertion responses. if (openIdAuthenticationResponse.Status != AuthenticationStatus.Authenticated) { @@ -78,21 +79,24 @@ namespace DotNetOpenAuth.OAuth { return null; } - // Prepare a message to exchange the request token for an access token. - // We are careful to use a v1.0 message version so that the oauth_verifier is not required. - var requestAccess = new AuthorizedTokenRequest(this.ServiceProvider.AccessTokenEndpoint, Protocol.V10.Version) { - RequestToken = positiveAuthorization.RequestToken, - ConsumerKey = this.ConsumerKey, - }; + using (var client = this.CreateHttpClient(new AccessToken(positiveAuthorization.RequestToken, string.Empty))) { + var request = new HttpRequestMessage(this.ServiceProvider.TokenRequestEndpointMethod, this.ServiceProvider.TokenRequestEndpoint); + using (var response = await client.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); - // Retrieve the access token and store it in the token manager. - openidTokenManager.StoreOpenIdAuthorizedRequestToken(this.ConsumerKey, positiveAuthorization); - var grantAccess = this.Channel.Request<AuthorizedTokenResponse>(requestAccess); - this.TokenManager.ExpireRequestTokenAndStoreNewAccessToken(this.ConsumerKey, positiveAuthorization.RequestToken, grantAccess.AccessToken, grantAccess.TokenSecret); + // Parse the response and ensure that it meets the requirements of the OAuth 1.0 spec. + string content = await response.Content.ReadAsStringAsync(); + var responseData = HttpUtility.ParseQueryString(content); + string accessToken = responseData[Protocol.TokenParameter]; + string tokenSecret = responseData[Protocol.TokenSecretParameter]; + ErrorUtilities.VerifyProtocol(!string.IsNullOrEmpty(accessToken), MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenParameter); + ErrorUtilities.VerifyProtocol(tokenSecret != null, MessagingStrings.RequiredParametersMissing, typeof(AuthorizedTokenResponse).Name, Protocol.TokenSecretParameter); - // Provide the caller with the access token so it may be associated with the user - // that is logging in. - return grantAccess; + responseData.Remove(Protocol.TokenParameter); + responseData.Remove(Protocol.TokenSecretParameter); + return new AccessTokenResponse(accessToken, tokenSecret, responseData); + } + } } } } diff --git a/src/DotNetOpenAuth.OpenIdOAuth/packages.config b/src/DotNetOpenAuth.OpenIdOAuth/packages.config index 58890d8..d32d62f 100644 --- a/src/DotNetOpenAuth.OpenIdOAuth/packages.config +++ b/src/DotNetOpenAuth.OpenIdOAuth/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Test/AutoRedirectHandler.cs b/src/DotNetOpenAuth.Test/AutoRedirectHandler.cs new file mode 100644 index 0000000..3f67259 --- /dev/null +++ b/src/DotNetOpenAuth.Test/AutoRedirectHandler.cs @@ -0,0 +1,33 @@ +namespace DotNetOpenAuth.Test { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Text; + using System.Threading.Tasks; + + using DotNetOpenAuth.Messaging; + + internal class AutoRedirectHandler : DelegatingHandler { + internal AutoRedirectHandler(HttpMessageHandler innerHandler) + : base(innerHandler) { + } + + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { + HttpResponseMessage response = null; + do { + if (response != null) { + var modifiedRequest = MessagingUtilities.Clone(request); + modifiedRequest.RequestUri = new Uri(request.RequestUri, response.Headers.Location); + request = modifiedRequest; + } + + response = await base.SendAsync(request, cancellationToken); + } + while (response.StatusCode == HttpStatusCode.Redirect); + + return response; + } + } +} diff --git a/src/DotNetOpenAuth.Test/CookieContainerExtensions.cs b/src/DotNetOpenAuth.Test/CookieContainerExtensions.cs new file mode 100644 index 0000000..5a09d13 --- /dev/null +++ b/src/DotNetOpenAuth.Test/CookieContainerExtensions.cs @@ -0,0 +1,38 @@ +//----------------------------------------------------------------------- +// <copyright file="CookieContainerExtensions.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + + using Validation; + + internal static class CookieContainerExtensions { + internal static void SetCookies(this CookieContainer container, HttpResponseMessage response, Uri requestUri = null) { + Requires.NotNull(container, "container"); + Requires.NotNull(response, "response"); + + IEnumerable<string> cookieHeaders; + if (response.Headers.TryGetValues("Set-Cookie", out cookieHeaders)) { + foreach (string cookie in cookieHeaders) { + container.SetCookies(requestUri ?? response.RequestMessage.RequestUri, cookie); + } + } + } + + internal static void ApplyCookies(this CookieContainer container, HttpRequestMessage request) { + Requires.NotNull(container, "container"); + Requires.NotNull(request, "request"); + + string cookieHeader = container.GetCookieHeader(request.RequestUri); + if (!string.IsNullOrEmpty(cookieHeader)) { + request.Headers.TryAddWithoutValidation("Cookie", cookieHeader); + } + } + } +}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Test/CookieDelegatingHandler.cs b/src/DotNetOpenAuth.Test/CookieDelegatingHandler.cs new file mode 100644 index 0000000..1b25dc0 --- /dev/null +++ b/src/DotNetOpenAuth.Test/CookieDelegatingHandler.cs @@ -0,0 +1,31 @@ +//----------------------------------------------------------------------- +// <copyright file="CookieDelegatingHandler.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + internal class CookieDelegatingHandler : DelegatingHandler { + internal CookieDelegatingHandler(HttpMessageHandler innerHandler, CookieContainer cookieContainer = null) + : base(innerHandler) { + this.Container = cookieContainer ?? new CookieContainer(); + } + + public CookieContainer Container { get; set; } + + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + this.Container.ApplyCookies(request); + var response = await base.SendAsync(request, cancellationToken); + this.Container.SetCookies(response); + return response; + } + } +} diff --git a/src/DotNetOpenAuth.Test/CoordinatorBase.cs b/src/DotNetOpenAuth.Test/CoordinatorBase.cs deleted file mode 100644 index d1c6f85..0000000 --- a/src/DotNetOpenAuth.Test/CoordinatorBase.cs +++ /dev/null @@ -1,91 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatorBase.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test { - using System; - using System.Threading; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OpenId.RelyingParty; - using DotNetOpenAuth.Test.Mocks; - using NUnit.Framework; - using Validation; - - internal abstract class CoordinatorBase<T1, T2> { - private Action<T1> party1Action; - private Action<T2> party2Action; - - protected CoordinatorBase(Action<T1> party1Action, Action<T2> party2Action) { - Requires.NotNull(party1Action, "party1Action"); - Requires.NotNull(party2Action, "party2Action"); - - this.party1Action = party1Action; - this.party2Action = party2Action; - } - - protected internal Action<IProtocolMessage> IncomingMessageFilter { get; set; } - - protected internal Action<IProtocolMessage> OutgoingMessageFilter { get; set; } - - internal abstract void Run(); - - protected void RunCore(T1 party1Object, T2 party2Object) { - Thread party1Thread = null, party2Thread = null; - Exception failingException = null; - - // Each thread we create needs a surrounding exception catcher so that we can - // terminate the other thread and inform the test host that the test failed. - Action<Action> safeWrapper = (action) => { - try { - TestBase.SetMockHttpContext(); - action(); - } catch (Exception ex) { - // We may be the second thread in an ThreadAbortException, so check the "flag" - lock (this) { - if (failingException == null || (failingException is ThreadAbortException && !(ex is ThreadAbortException))) { - failingException = ex; - if (Thread.CurrentThread == party1Thread) { - party2Thread.Abort(); - } else { - party1Thread.Abort(); - } - } - } - } - }; - - // Run the threads, and wait for them to complete. - // If this main thread is aborted (test run aborted), go ahead and abort the other two threads. - party1Thread = new Thread(() => { safeWrapper(() => { this.party1Action(party1Object); }); }); - party2Thread = new Thread(() => { safeWrapper(() => { this.party2Action(party2Object); }); }); - party1Thread.Name = "P1"; - party2Thread.Name = "P2"; - try { - party1Thread.Start(); - party2Thread.Start(); - party1Thread.Join(); - party2Thread.Join(); - } catch (ThreadAbortException) { - party1Thread.Abort(); - party2Thread.Abort(); - throw; - } catch (ThreadStartException ex) { - if (ex.InnerException is ThreadAbortException) { - // if party1Thread threw an exception - // (which may even have been intentional for the test) - // before party2Thread even started, then this exception - // can be thrown, and should be ignored. - } else { - throw; - } - } - - // Use the failing reason of a failing sub-thread as our reason, if anything failed. - if (failingException != null) { - throw new AssertionException("Coordinator thread threw unhandled exception: " + failingException, failingException); - } - } - } -} diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj index 0e13449..ab90935 100644 --- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj +++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj @@ -84,6 +84,7 @@ <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization"> <RequiredTargetFramework>3.0</RequiredTargetFramework> @@ -97,14 +98,14 @@ <Reference Include="System.Xml.Linq"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> - <Reference Include="Validation"> - <HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> - <Private>True</Private> + <Reference Include="Validation, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\packages\Validation.2.0.2.13022\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath> </Reference> </ItemGroup> <ItemGroup> + <Compile Include="AutoRedirectHandler.cs" /> <Compile Include="Configuration\SectionTests.cs" /> - <Compile Include="CoordinatorBase.cs" /> <Compile Include="Hosting\AspNetHost.cs" /> <Compile Include="Hosting\HostingTests.cs" /> <Compile Include="Hosting\HttpHost.cs" /> @@ -114,8 +115,6 @@ <Compile Include="Messaging\EnumerableCacheTests.cs" /> <Compile Include="Messaging\ErrorUtilitiesTests.cs" /> <Compile Include="Messaging\MessageSerializerTests.cs" /> - <Compile Include="Messaging\MultipartPostPartTests.cs" /> - <Compile Include="Messaging\OutgoingWebResponseTests.cs" /> <Compile Include="Messaging\Reflection\MessageDescriptionTests.cs" /> <Compile Include="Messaging\Reflection\MessageDictionaryTests.cs" /> <Compile Include="Messaging\MessagingTestBase.cs" /> @@ -127,19 +126,14 @@ <Compile Include="Messaging\Reflection\MessagePartTests.cs" /> <Compile Include="Messaging\Reflection\ValueMappingTests.cs" /> <Compile Include="Messaging\StandardMessageFactoryTests.cs" /> + <Compile Include="MockingHostFactories.cs" /> <Compile Include="Mocks\AssociateUnencryptedRequestNoSslCheck.cs" /> - <Compile Include="Mocks\CoordinatingChannel.cs" /> - <Compile Include="Mocks\CoordinatingHttpRequestInfo.cs" /> - <Compile Include="Mocks\CoordinatingOAuth2AuthServerChannel.cs" /> - <Compile Include="Mocks\CoordinatingOAuth2ClientChannel.cs" /> - <Compile Include="Mocks\CoordinatingOutgoingWebResponse.cs" /> - <Compile Include="Mocks\CoordinatingOAuthConsumerChannel.cs" /> + <Compile Include="CookieContainerExtensions.cs" /> + <Compile Include="CookieDelegatingHandler.cs" /> <Compile Include="Mocks\IBaseMessageExplicitMembers.cs" /> <Compile Include="Mocks\InMemoryTokenManager.cs" /> <Compile Include="Mocks\MockHttpMessageHandler.cs" /> <Compile Include="Mocks\MockHttpRequest.cs" /> - <Compile Include="Mocks\MockIdentifier.cs" /> - <Compile Include="Mocks\MockIdentifierDiscoveryService.cs" /> <Compile Include="Mocks\MockOpenIdExtension.cs" /> <Compile Include="Mocks\MockRealm.cs" /> <Compile Include="Mocks\MockTransformationBindingElement.cs" /> @@ -154,7 +148,6 @@ <Compile Include="Mocks\TestExpiringMessage.cs" /> <Compile Include="Mocks\TestSignedDirectedMessage.cs" /> <Compile Include="Mocks\MockSigningBindingElement.cs" /> - <Compile Include="Mocks\TestWebRequestHandler.cs" /> <Compile Include="Mocks\TestChannel.cs" /> <Compile Include="Mocks\TestMessage.cs" /> <Compile Include="Mocks\TestMessageFactory.cs" /> @@ -162,7 +155,6 @@ <Compile Include="OAuth2\MessageFactoryTests.cs" /> <Compile Include="OAuth2\ResourceServerTests.cs" /> <Compile Include="OAuth2\UserAgentClientAuthorizeTests.cs" /> - <Compile Include="OAuth2\OAuth2Coordinator.cs" /> <Compile Include="OAuth2\OAuth2TestBase.cs" /> <Compile Include="OAuth2\WebServerClientAuthorizeTests.cs" /> <Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElementTests.cs" /> @@ -217,7 +209,6 @@ <Compile Include="OpenId\Messages\PositiveAssertionResponseTests.cs" /> <Compile Include="OpenId\Messages\SignedResponseRequestTests.cs" /> <Compile Include="OpenId\NonIdentityTests.cs" /> - <Compile Include="OpenId\OpenIdCoordinator.cs" /> <Compile Include="OpenId\AssociationHandshakeTests.cs" /> <Compile Include="OpenId\OpenIdTestBase.cs" /> <Compile Include="OpenId\OpenIdUtilitiesTests.cs" /> @@ -244,10 +235,7 @@ <Compile Include="Performance\HighPerformance.cs" /> <Compile Include="Performance\PerformanceTestUtilities.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Messaging\ResponseTests.cs" /> <Compile Include="OAuth\AppendixScenarios.cs" /> - <Compile Include="Mocks\CoordinatingOAuthServiceProviderChannel.cs" /> - <Compile Include="OAuth\OAuthCoordinator.cs" /> <Compile Include="TestBase.cs" /> <Compile Include="TestUtilities.cs" /> <Compile Include="UriUtilTests.cs" /> @@ -338,6 +326,10 @@ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project> <Name>DotNetOpenAuth.Core</Name> </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OAuth.Common\DotNetOpenAuth.OAuth.Common.csproj"> + <Project>{115217c5-22cd-415c-a292-0dd0238cdd89}</Project> + <Name>DotNetOpenAuth.OAuth.Common</Name> + </ProjectReference> <ProjectReference Include="..\DotNetOpenAuth.OAuth.Consumer\DotNetOpenAuth.OAuth.Consumer.csproj"> <Project>{B202E40D-4663-4A2B-ACDA-865F88FF7CAA}</Project> <Name>DotNetOpenAuth.OAuth.Consumer</Name> @@ -394,6 +386,14 @@ <Project>{75E13AAE-7D51-4421-ABFD-3F3DC91F576E}</Project> <Name>DotNetOpenAuth.OpenId.UI</Name> </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OpenIdInfoCard.UI\DotNetOpenAuth.OpenIdInfoCard.UI.csproj"> + <Project>{3a8347e8-59a5-4092-8842-95c75d7d2f36}</Project> + <Name>DotNetOpenAuth.OpenIdInfoCard.UI</Name> + </ProjectReference> + <ProjectReference Include="..\DotNetOpenAuth.OpenIdOAuth\DotNetOpenAuth.OpenIdOAuth.csproj"> + <Project>{4bfaa336-5df3-4f27-82d3-06d13240e8ab}</Project> + <Name>DotNetOpenAuth.OpenIdOAuth</Name> + </ProjectReference> <ProjectReference Include="..\DotNetOpenAuth.OpenId\DotNetOpenAuth.OpenId.csproj"> <Project>{3896A32A-E876-4C23-B9B8-78E17D134CD3}</Project> <Name>DotNetOpenAuth.OpenId</Name> diff --git a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs index 6aa9461..a8eb7c1 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardExpirationBindingElementTests.cs @@ -6,7 +6,7 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { using System; - + using System.Threading.Tasks; using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; @@ -16,38 +16,38 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { [TestFixture] public class StandardExpirationBindingElementTests : MessagingTestBase { [Test] - public void SendSetsTimestamp() { + public async Task SendSetsTimestamp() { TestExpiringMessage message = new TestExpiringMessage(MessageTransport.Indirect); message.Recipient = new Uri("http://localtest"); ((IExpiringProtocolMessage)message).UtcCreationDate = DateTime.Parse("1/1/1990"); Channel channel = CreateChannel(MessageProtections.Expiration); - channel.PrepareResponse(message); + await channel.PrepareResponseAsync(message); Assert.IsTrue(DateTime.UtcNow - ((IExpiringProtocolMessage)message).UtcCreationDate < TimeSpan.FromSeconds(3), "The timestamp on the message was not set on send."); } [Test] - public void VerifyGoodTimestampIsAccepted() { + public async Task VerifyGoodTimestampIsAccepted() { this.Channel = CreateChannel(MessageProtections.Expiration); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow, false); } [Test] - public void VerifyFutureTimestampWithinClockSkewIsAccepted() { + public async Task VerifyFutureTimestampWithinClockSkewIsAccepted() { this.Channel = CreateChannel(MessageProtections.Expiration); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow + DotNetOpenAuthSection.Messaging.MaximumClockSkew - TimeSpan.FromSeconds(1), false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow + DotNetOpenAuthSection.Messaging.MaximumClockSkew - TimeSpan.FromSeconds(1), false); } [Test, ExpectedException(typeof(ExpiredMessageException))] - public void VerifyOldTimestampIsRejected() { + public async Task VerifyOldTimestampIsRejected() { this.Channel = CreateChannel(MessageProtections.Expiration); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow - StandardExpirationBindingElement.MaximumMessageAge - TimeSpan.FromSeconds(1), false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow - StandardExpirationBindingElement.MaximumMessageAge - TimeSpan.FromSeconds(1), false); } [Test, ExpectedException(typeof(ProtocolException))] - public void VerifyFutureTimestampIsRejected() { + public async Task VerifyFutureTimestampIsRejected() { this.Channel = CreateChannel(MessageProtections.Expiration); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow + DotNetOpenAuthSection.Messaging.MaximumClockSkew + TimeSpan.FromSeconds(2), false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow + DotNetOpenAuthSection.Messaging.MaximumClockSkew + TimeSpan.FromSeconds(2), false); } } } diff --git a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs index 9a46e42..04c63ef 100644 --- a/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/Bindings/StandardReplayProtectionBindingElementTests.cs @@ -9,6 +9,8 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId; @@ -40,14 +42,14 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { /// Verifies that the generated nonce includes random characters. /// </summary> [Test] - public void RandomCharactersTest() { - Assert.IsNotNull(this.nonceElement.ProcessOutgoingMessage(this.message)); + public async Task RandomCharactersTest() { + Assert.IsNotNull(await this.nonceElement.ProcessOutgoingMessageAsync(this.message, CancellationToken.None)); Assert.IsNotNull(this.message.Nonce, "No nonce was set on the message."); Assert.AreNotEqual(0, this.message.Nonce.Length, "The generated nonce was empty."); string firstNonce = this.message.Nonce; // Apply another nonce and verify that they are different than the first ones. - Assert.IsNotNull(this.nonceElement.ProcessOutgoingMessage(this.message)); + Assert.IsNotNull(await this.nonceElement.ProcessOutgoingMessageAsync(this.message, CancellationToken.None)); Assert.IsNotNull(this.message.Nonce, "No nonce was set on the message."); Assert.AreNotEqual(0, this.message.Nonce.Length, "The generated nonce was empty."); Assert.AreNotEqual(firstNonce, this.message.Nonce, "The two generated nonces are identical."); @@ -57,41 +59,41 @@ namespace DotNetOpenAuth.Test.Messaging.Bindings { /// Verifies that a message is received correctly. /// </summary> [Test] - public void ValidMessageReceivedTest() { + public async Task ValidMessageReceivedTest() { this.message.Nonce = "a"; - Assert.IsNotNull(this.nonceElement.ProcessIncomingMessage(this.message)); + Assert.IsNotNull(await this.nonceElement.ProcessIncomingMessageAsync(this.message, CancellationToken.None)); } /// <summary> /// Verifies that a message that doesn't have a string of random characters is received correctly. /// </summary> [Test] - public void ValidMessageNoNonceReceivedTest() { + public async Task ValidMessageNoNonceReceivedTest() { this.message.Nonce = string.Empty; this.nonceElement.AllowZeroLengthNonce = true; - Assert.IsNotNull(this.nonceElement.ProcessIncomingMessage(this.message)); + Assert.IsNotNull(await this.nonceElement.ProcessIncomingMessageAsync(this.message, CancellationToken.None)); } /// <summary> /// Verifies that a message that doesn't have a string of random characters is received correctly. /// </summary> [Test, ExpectedException(typeof(ProtocolException))] - public void InvalidMessageNoNonceReceivedTest() { + public async Task InvalidMessageNoNonceReceivedTest() { this.message.Nonce = string.Empty; this.nonceElement.AllowZeroLengthNonce = false; - Assert.IsNotNull(this.nonceElement.ProcessIncomingMessage(this.message)); + Assert.IsNotNull(await this.nonceElement.ProcessIncomingMessageAsync(this.message, CancellationToken.None)); } /// <summary> /// Verifies that a replayed message is rejected. /// </summary> [Test, ExpectedException(typeof(ReplayedMessageException))] - public void ReplayDetectionTest() { + public async Task ReplayDetectionTest() { this.message.Nonce = "a"; - Assert.IsNotNull(this.nonceElement.ProcessIncomingMessage(this.message)); + Assert.IsNotNull(await this.nonceElement.ProcessIncomingMessageAsync(this.message, CancellationToken.None)); // Now receive the same message again. This should throw because it's a message replay. - this.nonceElement.ProcessIncomingMessage(this.message); + await this.nonceElement.ProcessIncomingMessageAsync(this.message, CancellationToken.None); } } } diff --git a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs index 5646a7e..9050fad 100644 --- a/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/ChannelTests.cs @@ -9,29 +9,41 @@ namespace DotNetOpenAuth.Test.Messaging { using System.Collections.Generic; using System.IO; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; + using DotNetOpenAuth.OpenId; using DotNetOpenAuth.Test.Mocks; using NUnit.Framework; [TestFixture] public class ChannelTests : MessagingTestBase { [Test, ExpectedException(typeof(ArgumentNullException))] - public void CtorNull() { - // This bad channel is deliberately constructed to pass null to - // its protected base class' constructor. - new TestBadChannel(true); + public void CtorNullFirstParameter() { + new TestBadChannel(null, new IChannelBindingElement[0], new DefaultOpenIdHostFactories()); + } + + [Test, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullSecondParameter() { + new TestBadChannel(new TestMessageFactory(), null, new DefaultOpenIdHostFactories()); + } + + [Test, ExpectedException(typeof(ArgumentNullException))] + public void CtorNullThirdParameter() { + new TestBadChannel(new TestMessageFactory(), new IChannelBindingElement[0], null); } [Test] - public void ReadFromRequestQueryString() { - this.ParameterizedReceiveTest("GET"); + public async Task ReadFromRequestQueryString() { + await this.ParameterizedReceiveTestAsync(HttpMethod.Get); } [Test] - public void ReadFromRequestForm() { - this.ParameterizedReceiveTest("POST"); + public async Task ReadFromRequestForm() { + await this.ParameterizedReceiveTestAsync(HttpMethod.Post); } /// <summary> @@ -39,78 +51,78 @@ namespace DotNetOpenAuth.Test.Messaging { /// will reject messages that come with an unexpected HTTP verb. /// </summary> [Test, ExpectedException(typeof(ProtocolException))] - public void ReadFromRequestDisallowedHttpMethod() { + public async Task ReadFromRequestDisallowedHttpMethod() { var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings); fields["GetOnly"] = "true"; - this.Channel.ReadFromRequest(CreateHttpRequestInfo("POST", fields)); + await this.Channel.ReadFromRequestAsync(CreateHttpRequestInfo(HttpMethod.Post, fields), CancellationToken.None); } [Test, ExpectedException(typeof(ArgumentNullException))] - public void SendNull() { - this.Channel.PrepareResponse(null); + public async Task SendNull() { + await this.Channel.PrepareResponseAsync(null); } [Test, ExpectedException(typeof(ArgumentException))] - public void SendIndirectedUndirectedMessage() { + public async Task SendIndirectedUndirectedMessage() { IProtocolMessage message = new TestDirectedMessage(MessageTransport.Indirect); - this.Channel.PrepareResponse(message); + await this.Channel.PrepareResponseAsync(message); } [Test, ExpectedException(typeof(ArgumentException))] - public void SendDirectedNoRecipientMessage() { + public async Task SendDirectedNoRecipientMessage() { IProtocolMessage message = new TestDirectedMessage(MessageTransport.Indirect); - this.Channel.PrepareResponse(message); + await this.Channel.PrepareResponseAsync(message); } [Test, ExpectedException(typeof(ArgumentException))] - public void SendInvalidMessageTransport() { + public async Task SendInvalidMessageTransport() { IProtocolMessage message = new TestDirectedMessage((MessageTransport)100); - this.Channel.PrepareResponse(message); + await this.Channel.PrepareResponseAsync(message); } [Test] - public void SendIndirectMessage301Get() { + public async Task SendIndirectMessage301Get() { TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Indirect); GetStandardTestMessage(FieldFill.CompleteBeforeBindings, message); message.Recipient = new Uri("http://provider/path"); var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings); - OutgoingWebResponse response = this.Channel.PrepareResponse(message); - Assert.AreEqual(HttpStatusCode.Redirect, response.Status); - Assert.AreEqual("text/html; charset=utf-8", response.Headers[HttpResponseHeader.ContentType]); - Assert.IsTrue(response.Body != null && response.Body.Length > 0); // a non-empty body helps get passed filters like WebSense - StringAssert.StartsWith("http://provider/path", response.Headers[HttpResponseHeader.Location]); + var response = await this.Channel.PrepareResponseAsync(message); + Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode); + Assert.AreEqual("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString()); + Assert.IsTrue(response.Content != null && response.Content.Headers.ContentLength > 0); // a non-empty body helps get passed filters like WebSense + StringAssert.StartsWith("http://provider/path", response.Headers.Location.AbsoluteUri); foreach (var pair in expected) { string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key); string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value); string substring = string.Format("{0}={1}", key, value); - StringAssert.Contains(substring, response.Headers[HttpResponseHeader.Location]); + StringAssert.Contains(substring, response.Headers.Location.AbsoluteUri); } } [Test, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessage301GetNullMessage() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); badChannel.Create301RedirectResponse(null, new Dictionary<string, string>()); } [Test, ExpectedException(typeof(ArgumentException))] public void SendIndirectMessage301GetEmptyRecipient() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); var message = new TestDirectedMessage(MessageTransport.Indirect); badChannel.Create301RedirectResponse(message, new Dictionary<string, string>()); } [Test, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessage301GetNullFields() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); var message = new TestDirectedMessage(MessageTransport.Indirect); message.Recipient = new Uri("http://someserver"); badChannel.Create301RedirectResponse(message, null); } [Test] - public void SendIndirectMessageFormPost() { + public async Task SendIndirectMessageFormPost() { // We craft a very large message to force fallback to form POST. // We'll also stick some HTML reserved characters in the string value // to test proper character escaping. @@ -120,10 +132,10 @@ namespace DotNetOpenAuth.Test.Messaging { Location = new Uri("http://host/path"), Recipient = new Uri("http://provider/path"), }; - OutgoingWebResponse response = this.Channel.PrepareResponse(message); - Assert.AreEqual(HttpStatusCode.OK, response.Status, "A form redirect should be an HTTP successful response."); - Assert.IsNull(response.Headers[HttpResponseHeader.Location], "There should not be a redirection header in the response."); - string body = response.Body; + var response = await this.Channel.PrepareResponseAsync(message); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "A form redirect should be an HTTP successful response."); + Assert.IsNull(response.Headers.Location, "There should not be a redirection header in the response."); + string body = await response.Content.ReadAsStringAsync(); StringAssert.Contains("<form ", body); StringAssert.Contains("action=\"http://provider/path\"", body); StringAssert.Contains("method=\"post\"", body); @@ -135,20 +147,20 @@ namespace DotNetOpenAuth.Test.Messaging { [Test, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessageFormPostNullMessage() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); badChannel.CreateFormPostResponse(null, new Dictionary<string, string>()); } [Test, ExpectedException(typeof(ArgumentException))] public void SendIndirectMessageFormPostEmptyRecipient() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); var message = new TestDirectedMessage(MessageTransport.Indirect); badChannel.CreateFormPostResponse(message, new Dictionary<string, string>()); } [Test, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessageFormPostNullFields() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); var message = new TestDirectedMessage(MessageTransport.Indirect); message.Recipient = new Uri("http://someserver"); badChannel.CreateFormPostResponse(message, null); @@ -162,101 +174,103 @@ namespace DotNetOpenAuth.Test.Messaging { /// we just check that the right method was called. /// </remarks> [Test, ExpectedException(typeof(NotImplementedException))] - public void SendDirectMessageResponse() { + public async Task SendDirectMessageResponse() { IProtocolMessage message = new TestDirectedMessage { Age = 15, Name = "Andrew", Location = new Uri("http://host/path"), }; - this.Channel.PrepareResponse(message); + await this.Channel.PrepareResponseAsync(message); } [Test, ExpectedException(typeof(ArgumentNullException))] public void SendIndirectMessageNull() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); badChannel.PrepareIndirectResponse(null); } [Test, ExpectedException(typeof(ArgumentNullException))] public void ReceiveNull() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); badChannel.Receive(null, null); } [Test] public void ReceiveUnrecognizedMessage() { - TestBadChannel badChannel = new TestBadChannel(false); + TestBadChannel badChannel = new TestBadChannel(); Assert.IsNull(badChannel.Receive(new Dictionary<string, string>(), null)); } [Test] - public void ReadFromRequestWithContext() { + public async Task ReadFromRequestWithContext() { var fields = GetStandardTestFields(FieldFill.AllRequired); TestMessage expectedMessage = GetStandardTestMessage(FieldFill.AllRequired); HttpRequest request = new HttpRequest("somefile", "http://someurl", MessagingUtilities.CreateQueryString(fields)); HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter())); - IProtocolMessage message = this.Channel.ReadFromRequest(); + var requestBase = this.Channel.GetRequestFromContext(); + IProtocolMessage message = await this.Channel.ReadFromRequestAsync(requestBase.AsHttpRequestMessage(), CancellationToken.None); Assert.IsNotNull(message); Assert.IsInstanceOf<TestMessage>(message); Assert.AreEqual(expectedMessage.Age, ((TestMessage)message).Age); } [Test, ExpectedException(typeof(InvalidOperationException))] - public void ReadFromRequestNoContext() { + public void GetRequestFromContextNoContext() { HttpContext.Current = null; - TestBadChannel badChannel = new TestBadChannel(false); - badChannel.ReadFromRequest(); + TestBadChannel badChannel = new TestBadChannel(); + badChannel.GetRequestFromContext(); } [Test, ExpectedException(typeof(ArgumentNullException))] - public void ReadFromRequestNull() { - TestBadChannel badChannel = new TestBadChannel(false); - badChannel.ReadFromRequest(null); + public async Task ReadFromRequestNull() { + TestBadChannel badChannel = new TestBadChannel(); + await badChannel.ReadFromRequestAsync(null, CancellationToken.None); } [Test] - public void SendReplayProtectedMessageSetsNonce() { + public async Task SendReplayProtectedMessageSetsNonce() { TestReplayProtectedMessage message = new TestReplayProtectedMessage(MessageTransport.Indirect); message.Recipient = new Uri("http://localtest"); this.Channel = CreateChannel(MessageProtections.ReplayProtection); - this.Channel.PrepareResponse(message); + await this.Channel.PrepareResponseAsync(message); Assert.IsNotNull(((IReplayProtectedProtocolMessage)message).Nonce); } [Test, ExpectedException(typeof(InvalidSignatureException))] - public void ReceivedInvalidSignature() { + public async Task ReceivedInvalidSignature() { this.Channel = CreateChannel(MessageProtections.TamperProtection); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, true); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow, true); } [Test] - public void ReceivedReplayProtectedMessageJustOnce() { + public async Task ReceivedReplayProtectedMessageJustOnce() { this.Channel = CreateChannel(MessageProtections.ReplayProtection); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow, false); } [Test, ExpectedException(typeof(ReplayedMessageException))] - public void ReceivedReplayProtectedMessageTwice() { + public async Task ReceivedReplayProtectedMessageTwice() { this.Channel = CreateChannel(MessageProtections.ReplayProtection); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); - this.ParameterizedReceiveProtectedTest(DateTime.UtcNow, false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow, false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.UtcNow, false); } [Test, ExpectedException(typeof(ProtocolException))] public void MessageExpirationWithoutTamperResistance() { new TestChannel( new TestMessageFactory(), - new StandardExpirationBindingElement()); + new IChannelBindingElement[] { new StandardExpirationBindingElement() }, + new DefaultOpenIdHostFactories()); } [Test, ExpectedException(typeof(ProtocolException))] - public void TooManyBindingElementsProvidingSameProtection() { + public async Task TooManyBindingElementsProvidingSameProtection() { Channel channel = new TestChannel( new TestMessageFactory(), - new MockSigningBindingElement(), - new MockSigningBindingElement()); - channel.ProcessOutgoingMessageTestHook(new TestSignedDirectedMessage()); + new IChannelBindingElement[] { new MockSigningBindingElement(), new MockSigningBindingElement() }, + new DefaultOpenIdHostFactories()); + await channel.ProcessOutgoingMessageTestHookAsync(new TestSignedDirectedMessage()); } [Test] @@ -269,11 +283,8 @@ namespace DotNetOpenAuth.Test.Messaging { Channel channel = new TestChannel( new TestMessageFactory(), - sign, - replay, - expire, - transformB, - transformA); + new[] { sign, replay, expire, transformB, transformA }, + new DefaultOpenIdHostFactories()); Assert.AreEqual(5, channel.BindingElements.Count); Assert.AreSame(transformB, channel.BindingElements[0]); @@ -284,22 +295,22 @@ namespace DotNetOpenAuth.Test.Messaging { } [Test, ExpectedException(typeof(UnprotectedMessageException))] - public void InsufficientlyProtectedMessageSent() { + public async Task InsufficientlyProtectedMessageSent() { var message = new TestSignedDirectedMessage(MessageTransport.Direct); message.Recipient = new Uri("http://localtest"); - this.Channel.PrepareResponse(message); + await this.Channel.PrepareResponseAsync(message); } [Test, ExpectedException(typeof(UnprotectedMessageException))] - public void InsufficientlyProtectedMessageReceived() { + public async Task InsufficientlyProtectedMessageReceived() { this.Channel = CreateChannel(MessageProtections.None, MessageProtections.TamperProtection); - this.ParameterizedReceiveProtectedTest(DateTime.Now, false); + await this.ParameterizedReceiveProtectedTestAsync(DateTime.Now, false); } [Test, ExpectedException(typeof(ProtocolException))] - public void IncomingMessageMissingRequiredParameters() { + public async Task IncomingMessageMissingRequiredParameters() { var fields = GetStandardTestFields(FieldFill.IdentifiableButNotAllRequired); - this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields)); + await this.Channel.ReadFromRequestAsync(CreateHttpRequestInfo(HttpMethod.Get, fields), CancellationToken.None); } } } diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs index b7c0980..7903e89 100644 --- a/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessagingTestBase.cs @@ -10,6 +10,9 @@ namespace DotNetOpenAuth.Test { using System.Collections.Specialized; using System.IO; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using System.Xml; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; @@ -52,30 +55,29 @@ namespace DotNetOpenAuth.Test { public override void SetUp() { base.SetUp(); - this.Channel = new TestChannel(); + this.Channel = new TestChannel(this.HostFactories); } - internal static HttpRequestInfo CreateHttpRequestInfo(string method, IDictionary<string, string> fields) { + internal static HttpRequestMessage CreateHttpRequestInfo(HttpMethod method, IDictionary<string, string> fields) { + var result = new HttpRequestMessage() { Method = method }; var requestUri = new UriBuilder(DefaultUrlForHttpRequestInfo); - var headers = new NameValueCollection(); - NameValueCollection form = null; - if (method == "POST") { - form = fields.ToNameValueCollection(); - headers.Add(HttpRequestHeaders.ContentType, Channel.HttpFormUrlEncoded); - } else if (method == "GET") { - requestUri.Query = MessagingUtilities.CreateQueryString(fields); + if (method == HttpMethod.Post) { + result.Content = new FormUrlEncodedContent(fields); + } else if (method == HttpMethod.Get) { + requestUri.AppendQueryArgs(fields); } else { throw new ArgumentOutOfRangeException("method", method, "Expected POST or GET"); } - return new HttpRequestInfo(method, requestUri.Uri, form: form, headers: headers); + result.RequestUri = requestUri.Uri; + return result; } - internal static Channel CreateChannel(MessageProtections capabilityAndRecognition) { - return CreateChannel(capabilityAndRecognition, capabilityAndRecognition); + internal Channel CreateChannel(MessageProtections capabilityAndRecognition) { + return this.CreateChannel(capabilityAndRecognition, capabilityAndRecognition); } - internal static Channel CreateChannel(MessageProtections capability, MessageProtections recognition) { + internal Channel CreateChannel(MessageProtections capability, MessageProtections recognition) { var bindingElements = new List<IChannelBindingElement>(); if (capability >= MessageProtections.TamperProtection) { bindingElements.Add(new MockSigningBindingElement()); @@ -99,7 +101,7 @@ namespace DotNetOpenAuth.Test { } var typeProvider = new TestMessageFactory(signing, expiration, replay); - return new TestChannel(typeProvider, bindingElements.ToArray()); + return new TestChannel(typeProvider, bindingElements.ToArray(), this.HostFactories); } internal static IDictionary<string, string> GetStandardTestFields(FieldFill fill) { @@ -143,11 +145,11 @@ namespace DotNetOpenAuth.Test { } } - internal void ParameterizedReceiveTest(string method) { + internal async Task ParameterizedReceiveTestAsync(HttpMethod method) { var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings); TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings); - IDirectedProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo(method, fields)); + IDirectedProtocolMessage requestMessage = await this.Channel.ReadFromRequestAsync(CreateHttpRequestInfo(method, fields), CancellationToken.None); Assert.IsNotNull(requestMessage); Assert.IsInstanceOf<TestMessage>(requestMessage); TestMessage actualMessage = (TestMessage)requestMessage; @@ -156,7 +158,7 @@ namespace DotNetOpenAuth.Test { Assert.AreEqual(expectedMessage.Location, actualMessage.Location); } - internal void ParameterizedReceiveProtectedTest(DateTime? utcCreatedDate, bool invalidSignature) { + internal async Task ParameterizedReceiveProtectedTestAsync(DateTime? utcCreatedDate, bool invalidSignature) { TestMessage expectedMessage = GetStandardTestMessage(FieldFill.CompleteBeforeBindings); var fields = GetStandardTestFields(FieldFill.CompleteBeforeBindings); fields.Add("Signature", invalidSignature ? "badsig" : MockSigningBindingElement.MessageSignature); @@ -165,7 +167,7 @@ namespace DotNetOpenAuth.Test { utcCreatedDate = DateTime.Parse(utcCreatedDate.Value.ToUniversalTime().ToString()); // round off the milliseconds so comparisons work later fields.Add("created_on", XmlConvert.ToString(utcCreatedDate.Value, XmlDateTimeSerializationMode.Utc)); } - IProtocolMessage requestMessage = this.Channel.ReadFromRequest(CreateHttpRequestInfo("GET", fields)); + IProtocolMessage requestMessage = await this.Channel.ReadFromRequestAsync(CreateHttpRequestInfo(HttpMethod.Get, fields), CancellationToken.None); Assert.IsNotNull(requestMessage); Assert.IsInstanceOf<TestSignedDirectedMessage>(requestMessage); TestSignedDirectedMessage actualMessage = (TestSignedDirectedMessage)requestMessage; diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs index cf0f9ca..0abf60f 100644 --- a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs +++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs @@ -67,41 +67,6 @@ namespace DotNetOpenAuth.Test.Messaging { } [Test] - public void AsHttpResponseMessage() { - var responseContent = new byte[10]; - (new Random()).NextBytes(responseContent); - var responseStream = new MemoryStream(responseContent); - var outgoingResponse = new OutgoingWebResponse(); - outgoingResponse.Headers.Add("X-SOME-HEADER", "value"); - outgoingResponse.Headers.Add("Content-Length", responseContent.Length.ToString(CultureInfo.InvariantCulture)); - outgoingResponse.ResponseStream = responseStream; - - var httpResponseMessage = outgoingResponse.AsHttpResponseMessage(); - Assert.That(httpResponseMessage, Is.Not.Null); - Assert.That(httpResponseMessage.Headers.GetValues("X-SOME-HEADER").ToList(), Is.EqualTo(new[] { "value" })); - Assert.That( - httpResponseMessage.Content.Headers.GetValues("Content-Length").ToList(), - Is.EqualTo(new[] { responseContent.Length.ToString(CultureInfo.InvariantCulture) })); - var actualContent = new byte[responseContent.Length + 1]; // give the opportunity to provide a bit more data than we expect. - var bytesRead = httpResponseMessage.Content.ReadAsStreamAsync().Result.Read(actualContent, 0, actualContent.Length); - Assert.That(bytesRead, Is.EqualTo(responseContent.Length)); // verify that only the data we expected came back. - var trimmedActualContent = new byte[bytesRead]; - Array.Copy(actualContent, trimmedActualContent, bytesRead); - Assert.That(trimmedActualContent, Is.EqualTo(responseContent)); - } - - [Test] - public void AsHttpResponseMessageNoContent() { - var outgoingResponse = new OutgoingWebResponse(); - outgoingResponse.Headers.Add("X-SOME-HEADER", "value"); - - var httpResponseMessage = outgoingResponse.AsHttpResponseMessage(); - Assert.That(httpResponseMessage, Is.Not.Null); - Assert.That(httpResponseMessage.Headers.GetValues("X-SOME-HEADER").ToList(), Is.EqualTo(new[] { "value" })); - Assert.That(httpResponseMessage.Content, Is.Null); - } - - [Test] public void ToDictionary() { NameValueCollection nvc = new NameValueCollection(); nvc["a"] = "b"; @@ -142,11 +107,6 @@ namespace DotNetOpenAuth.Test.Messaging { } [Test, ExpectedException(typeof(ArgumentNullException))] - public void ApplyHeadersToResponseNullListenerResponse() { - MessagingUtilities.ApplyHeadersToResponse(new WebHeaderCollection(), (HttpListenerResponse)null); - } - - [Test, ExpectedException(typeof(ArgumentNullException))] public void ApplyHeadersToResponseNullHeaders() { MessagingUtilities.ApplyHeadersToResponse(null, new HttpResponseWrapper(new HttpResponse(new StringWriter()))); } @@ -183,54 +143,25 @@ namespace DotNetOpenAuth.Test.Messaging { } /// <summary> - /// Verifies the overall format of the multipart POST is correct. - /// </summary> - [Test] - public void PostMultipart() { - var httpHandler = new TestWebRequestHandler(); - bool callbackTriggered = false; - httpHandler.Callback = req => { - var m = Regex.Match(req.ContentType, "multipart/form-data; boundary=(.+)"); - Assert.IsTrue(m.Success, "Content-Type HTTP header not set correctly."); - string boundary = m.Groups[1].Value; - boundary = boundary.Substring(0, boundary.IndexOf(';')); // trim off charset - string expectedEntity = "--{0}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n--{0}--\r\n"; - expectedEntity = string.Format(expectedEntity, boundary); - string actualEntity = httpHandler.RequestEntityAsString; - Assert.AreEqual(expectedEntity, actualEntity); - callbackTriggered = true; - Assert.AreEqual(req.ContentLength, actualEntity.Length); - IncomingWebResponse resp = new CachedDirectWebResponse(); - return resp; - }; - var request = (HttpWebRequest)WebRequest.Create("http://someserver"); - var parts = new[] { - MultipartPostPart.CreateFormPart("a", "b"), - }; - request.PostMultipart(httpHandler, parts); - Assert.IsTrue(callbackTriggered); - } - - /// <summary> /// Verifies proper behavior of GetHttpVerb /// </summary> [Test] public void GetHttpVerbTest() { - Assert.AreEqual("GET", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.GetRequest)); - Assert.AreEqual("POST", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PostRequest)); - Assert.AreEqual("HEAD", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.HeadRequest)); - Assert.AreEqual("DELETE", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.DeleteRequest)); - Assert.AreEqual("PUT", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest));
- Assert.AreEqual("PATCH", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PatchRequest));
- Assert.AreEqual("OPTIONS", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.OptionsRequest)); - - Assert.AreEqual("GET", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); - Assert.AreEqual("POST", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); - Assert.AreEqual("HEAD", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.HeadRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); - Assert.AreEqual("DELETE", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.DeleteRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); - Assert.AreEqual("PUT", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest | HttpDeliveryMethods.AuthorizationHeaderRequest));
- Assert.AreEqual("PATCH", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PatchRequest | HttpDeliveryMethods.AuthorizationHeaderRequest));
- Assert.AreEqual("OPTIONS", MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.OptionsRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); + Assert.AreEqual(HttpMethod.Get, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.GetRequest)); + Assert.AreEqual(HttpMethod.Post, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PostRequest)); + Assert.AreEqual(HttpMethod.Head, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.HeadRequest)); + Assert.AreEqual(HttpMethod.Delete, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.DeleteRequest)); + Assert.AreEqual(HttpMethod.Put, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest)); + Assert.AreEqual(new HttpMethod("PATCH"), MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PatchRequest)); + Assert.AreEqual(HttpMethod.Options, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.OptionsRequest)); + + Assert.AreEqual(HttpMethod.Get, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); + Assert.AreEqual(HttpMethod.Post, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); + Assert.AreEqual(HttpMethod.Head, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.HeadRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); + Assert.AreEqual(HttpMethod.Delete, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.DeleteRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); + Assert.AreEqual(HttpMethod.Put, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PutRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); + Assert.AreEqual(new HttpMethod("PATCH"), MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.PatchRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); + Assert.AreEqual(HttpMethod.Options, MessagingUtilities.GetHttpVerb(HttpDeliveryMethods.OptionsRequest | HttpDeliveryMethods.AuthorizationHeaderRequest)); } /// <summary> @@ -250,8 +181,8 @@ namespace DotNetOpenAuth.Test.Messaging { Assert.AreEqual(HttpDeliveryMethods.PostRequest, MessagingUtilities.GetHttpDeliveryMethod("POST")); Assert.AreEqual(HttpDeliveryMethods.HeadRequest, MessagingUtilities.GetHttpDeliveryMethod("HEAD")); Assert.AreEqual(HttpDeliveryMethods.PutRequest, MessagingUtilities.GetHttpDeliveryMethod("PUT")); - Assert.AreEqual(HttpDeliveryMethods.DeleteRequest, MessagingUtilities.GetHttpDeliveryMethod("DELETE"));
- Assert.AreEqual(HttpDeliveryMethods.PatchRequest, MessagingUtilities.GetHttpDeliveryMethod("PATCH"));
+ Assert.AreEqual(HttpDeliveryMethods.DeleteRequest, MessagingUtilities.GetHttpDeliveryMethod("DELETE")); + Assert.AreEqual(HttpDeliveryMethods.PatchRequest, MessagingUtilities.GetHttpDeliveryMethod("PATCH")); Assert.AreEqual(HttpDeliveryMethods.OptionsRequest, MessagingUtilities.GetHttpDeliveryMethod("OPTIONS")); } diff --git a/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs b/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs deleted file mode 100644 index e9ac5aa..0000000 --- a/src/DotNetOpenAuth.Test/Messaging/MultipartPostPartTests.cs +++ /dev/null @@ -1,108 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="MultipartPostPartTests.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Messaging { - using System.CodeDom.Compiler; - using System.Collections.Generic; - using System.IO; - using System.Net; - using DotNetOpenAuth.Messaging; - using NUnit.Framework; - using Validation; - - [TestFixture] - public class MultipartPostPartTests : TestBase { - /// <summary> - /// Verifies that the Length property matches the length actually serialized. - /// </summary> - [Test] - public void FormDataSerializeMatchesLength() { - var part = MultipartPostPart.CreateFormPart("a", "b"); - VerifyLength(part); - } - - /// <summary> - /// Verifies that the length property matches the length actually serialized. - /// </summary> - [Test] - public void FileSerializeMatchesLength() { - using (TempFileCollection tfc = new TempFileCollection()) { - string file = tfc.AddExtension(".txt"); - File.WriteAllText(file, "sometext"); - var part = MultipartPostPart.CreateFormFilePart("someformname", file, "text/plain"); - VerifyLength(part); - } - } - - /// <summary> - /// Verifies file multiparts identify themselves as files and not merely form-data. - /// </summary> - [Test] - public void FilePartAsFile() { - var part = MultipartPostPart.CreateFormFilePart("somename", "somefile", "plain/text", new MemoryStream()); - Assert.AreEqual("file", part.ContentDisposition); - } - - /// <summary> - /// Verifies MultiPartPost sends the right number of bytes. - /// </summary> - [Test] - public void MultiPartPostAscii() { - using (TempFileCollection tfc = new TempFileCollection()) { - string file = tfc.AddExtension("txt"); - File.WriteAllText(file, "sometext"); - this.VerifyFullPost(new List<MultipartPostPart> { - MultipartPostPart.CreateFormPart("a", "b"), - MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"), - }); - } - } - - /// <summary> - /// Verifies MultiPartPost sends the right number of bytes. - /// </summary> - [Test] - public void MultiPartPostMultiByteCharacters() { - using (TempFileCollection tfc = new TempFileCollection()) { - string file = tfc.AddExtension("txt"); - File.WriteAllText(file, "\x1020\x818"); - this.VerifyFullPost(new List<MultipartPostPart> { - MultipartPostPart.CreateFormPart("a", "\x987"), - MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"), - }); - } - } - - private static void VerifyLength(MultipartPostPart part) { - Requires.NotNull(part, "part"); - - var expectedLength = part.Length; - var ms = new MemoryStream(); - var sw = new StreamWriter(ms); - part.Serialize(sw); - sw.Flush(); - var actualLength = ms.Length; - Assert.AreEqual(expectedLength, actualLength); - } - - private void VerifyFullPost(List<MultipartPostPart> parts) { - var request = (HttpWebRequest)WebRequest.Create("http://localhost"); - var handler = new Mocks.TestWebRequestHandler(); - bool posted = false; - handler.Callback = req => { - foreach (string header in req.Headers) { - TestUtilities.TestLogger.InfoFormat("{0}: {1}", header, req.Headers[header]); - } - TestUtilities.TestLogger.InfoFormat(handler.RequestEntityAsString); - Assert.AreEqual(req.ContentLength, handler.RequestEntityStream.Length); - posted = true; - return null; - }; - request.PostMultipart(handler, parts); - Assert.IsTrue(posted, "HTTP POST never sent."); - } - } -} diff --git a/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs deleted file mode 100644 index 3efc471..0000000 --- a/src/DotNetOpenAuth.Test/Messaging/OutgoingWebResponseTests.cs +++ /dev/null @@ -1,38 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OutgoingWebResponseTests.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Messaging { - using System.Net; - using System.Net.Mime; - using System.Text; - using DotNetOpenAuth.Messaging; - using NUnit.Framework; - - [TestFixture] - public class OutgoingWebResponseTests { - /// <summary> - /// Verifies that setting the Body property correctly converts to a byte stream. - /// </summary> - [Test] - public void SetBodyToByteStream() { - var response = new OutgoingWebResponse(); - string stringValue = "abc"; - response.Body = stringValue; - Assert.AreEqual(stringValue.Length, response.ResponseStream.Length); - - // Verify that the actual bytes are correct. - Encoding encoding = new UTF8Encoding(false); // avoid emitting a byte-order mark - var expectedBuffer = encoding.GetBytes(stringValue); - var actualBuffer = new byte[stringValue.Length]; - Assert.AreEqual(stringValue.Length, response.ResponseStream.Read(actualBuffer, 0, stringValue.Length)); - CollectionAssert.AreEqual(expectedBuffer, actualBuffer); - - // Verify that the header was set correctly. - Assert.IsNull(response.Headers[HttpResponseHeader.ContentEncoding]); - Assert.AreEqual(encoding.HeaderName, new ContentType(response.Headers[HttpResponseHeader.ContentType]).CharSet); - } - } -} diff --git a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs deleted file mode 100644 index 52f031e..0000000 --- a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs +++ /dev/null @@ -1,40 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="ResponseTests.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Messaging { - using System; - using System.IO; - using System.Web; - using DotNetOpenAuth.Messaging; - using NUnit.Framework; - - [TestFixture] - public class ResponseTests : TestBase { - [Test, ExpectedException(typeof(InvalidOperationException))] - public void RespondWithoutAspNetContext() { - HttpContext.Current = null; - new OutgoingWebResponse().Respond(); - } - - [Test] - public void Respond() { - StringWriter writer = new StringWriter(); - HttpRequest httpRequest = new HttpRequest("file", "http://server", string.Empty); - HttpResponse httpResponse = new HttpResponse(writer); - HttpContext context = new HttpContext(httpRequest, httpResponse); - HttpContext.Current = context; - - OutgoingWebResponse response = new OutgoingWebResponse(); - response.Status = System.Net.HttpStatusCode.OK; - response.Headers["someHeaderName"] = "someHeaderValue"; - response.Body = "some body"; - response.Respond(); - string results = writer.ToString(); - // For some reason the only output in test is the body... the headers require a web host - Assert.AreEqual(response.Body, results); - } - } -} diff --git a/src/DotNetOpenAuth.Test/MockingHostFactories.cs b/src/DotNetOpenAuth.Test/MockingHostFactories.cs new file mode 100644 index 0000000..b8cbeb0 --- /dev/null +++ b/src/DotNetOpenAuth.Test/MockingHostFactories.cs @@ -0,0 +1,83 @@ +//----------------------------------------------------------------------- +// <copyright file="MockingHostFactories.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.Test { + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using System.Linq; + + using DotNetOpenAuth.OpenId; + + using Validation; + using System; + + internal class MockingHostFactories : IHostFactories { + public MockingHostFactories(Dictionary<Uri, Func<HttpRequestMessage, Task<HttpResponseMessage>>> handlers = null) { + this.Handlers = handlers ?? new Dictionary<Uri, Func<HttpRequestMessage, Task<HttpResponseMessage>>>(); + this.CookieContainer = new CookieContainer(); + this.AllowAutoRedirects = true; + } + + public Dictionary<Uri, Func<HttpRequestMessage, Task<HttpResponseMessage>>> Handlers { get; private set; } + + public CookieContainer CookieContainer { get; set; } + + public bool AllowAutoRedirects { get; set; } + + public bool InstallUntrustedWebReqestHandler { get; set; } + + public HttpMessageHandler CreateHttpMessageHandler() { + var forwardingMessageHandler = new ForwardingMessageHandler(this.Handlers, this); + var cookieDelegatingHandler = new CookieDelegatingHandler(forwardingMessageHandler, this.CookieContainer); + if (this.InstallUntrustedWebReqestHandler) { + var untrustedHandler = new UntrustedWebRequestHandler(cookieDelegatingHandler); + untrustedHandler.AllowAutoRedirect = this.AllowAutoRedirects; + return untrustedHandler; + } else if (this.AllowAutoRedirects) { + return new AutoRedirectHandler(cookieDelegatingHandler); + } else { + return cookieDelegatingHandler; + } + } + + public HttpClient CreateHttpClient(HttpMessageHandler handler = null) { + return new HttpClient(handler ?? this.CreateHttpMessageHandler()); + } + + private class ForwardingMessageHandler : HttpMessageHandler { + private readonly Dictionary<Uri, Func<HttpRequestMessage, Task<HttpResponseMessage>>> handlers; + + private readonly IHostFactories hostFactories; + + public ForwardingMessageHandler(Dictionary<Uri, Func<HttpRequestMessage, Task<HttpResponseMessage>>> handlers, IHostFactories hostFactories) { + Requires.NotNull(handlers, "handlers"); + + this.handlers = handlers; + this.hostFactories = hostFactories; + } + + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + foreach (var pair in this.handlers) { + if (pair.Key.IsBaseOf(request.RequestUri) && pair.Key.AbsolutePath == request.RequestUri.AbsolutePath) { + var response = await pair.Value(request); + if (response != null) { + if (response.RequestMessage == null) { + response.RequestMessage = request; + } + + return response; + } + } + } + + return new HttpResponseMessage(HttpStatusCode.NotFound); + } + } + } +}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs deleted file mode 100644 index 475f4b5..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingChannel.cs +++ /dev/null @@ -1,348 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatingChannel.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Text; - using System.Threading; - using System.Web; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Reflection; - using DotNetOpenAuth.Test.OpenId; - using NUnit.Framework; - using Validation; - - internal class CoordinatingChannel : Channel { - /// <summary> - /// A lock to use when checking and setting the <see cref="waitingForMessage"/> - /// or the <see cref="simulationCompleted"/> fields. - /// </summary> - /// <remarks> - /// This is a static member so that all coordinating channels share a lock - /// since they peak at each others fields. - /// </remarks> - private static readonly object waitingForMessageCoordinationLock = new object(); - - /// <summary> - /// The original product channel whose behavior is being modified to work - /// better in automated testing. - /// </summary> - private Channel wrappedChannel; - - /// <summary> - /// A flag set to true when this party in a two-party test has completed - /// its part of the testing. - /// </summary> - private bool simulationCompleted; - - /// <summary> - /// A thread-coordinating signal that is set when another thread has a - /// message ready for this channel to receive. - /// </summary> - private EventWaitHandle incomingMessageSignal = new AutoResetEvent(false); - - /// <summary> - /// A thread-coordinating signal that is set briefly by this thread whenever - /// a message is picked up. - /// </summary> - private EventWaitHandle messageReceivedSignal = new AutoResetEvent(false); - - /// <summary> - /// A flag used to indicate when this channel is waiting for a message - /// to arrive. - /// </summary> - private bool waitingForMessage; - - /// <summary> - /// An incoming message that has been posted by a remote channel and - /// is waiting for receipt by this channel. - /// </summary> - private IDictionary<string, string> incomingMessage; - - /// <summary> - /// The recipient URL of the <see cref="incomingMessage"/>, where applicable. - /// </summary> - private MessageReceivingEndpoint incomingMessageRecipient; - - /// <summary> - /// The headers of the <see cref="incomingMessage"/>, where applicable. - /// </summary> - private WebHeaderCollection incomingMessageHttpHeaders; - - /// <summary> - /// A delegate that gets a chance to peak at and fiddle with all - /// incoming messages. - /// </summary> - private Action<IProtocolMessage> incomingMessageFilter; - - /// <summary> - /// A delegate that gets a chance to peak at and fiddle with all - /// outgoing messages. - /// </summary> - private Action<IProtocolMessage> outgoingMessageFilter; - - /// <summary> - /// The simulated clients cookies. - /// </summary> - private HttpCookieCollection cookies = new HttpCookieCollection(); - - /// <summary> - /// Initializes a new instance of the <see cref="CoordinatingChannel"/> class. - /// </summary> - /// <param name="wrappedChannel">The wrapped channel. Must not be null.</param> - /// <param name="incomingMessageFilter">The incoming message filter. May be null.</param> - /// <param name="outgoingMessageFilter">The outgoing message filter. May be null.</param> - internal CoordinatingChannel(Channel wrappedChannel, Action<IProtocolMessage> incomingMessageFilter, Action<IProtocolMessage> outgoingMessageFilter) - : base(GetMessageFactory(wrappedChannel), wrappedChannel.BindingElements.ToArray()) { - Requires.NotNull(wrappedChannel, "wrappedChannel"); - - this.wrappedChannel = wrappedChannel; - this.incomingMessageFilter = incomingMessageFilter; - this.outgoingMessageFilter = outgoingMessageFilter; - - // Preserve any customized binding element ordering. - this.CustomizeBindingElementOrder(this.wrappedChannel.OutgoingBindingElements, this.wrappedChannel.IncomingBindingElements); - } - - /// <summary> - /// Gets or sets the coordinating channel used by the other party. - /// </summary> - internal CoordinatingChannel RemoteChannel { get; set; } - - /// <summary> - /// Indicates that the simulation that uses this channel has completed work. - /// </summary> - /// <remarks> - /// Calling this method is not strictly necessary, but it gives the channel - /// coordination a chance to recognize when another channel is left dangling - /// waiting for a message from another channel that may never come. - /// </remarks> - internal void Close() { - lock (waitingForMessageCoordinationLock) { - this.simulationCompleted = true; - if (this.RemoteChannel.waitingForMessage && this.RemoteChannel.incomingMessage == null) { - TestUtilities.TestLogger.Debug("CoordinatingChannel is closing while remote channel is waiting for an incoming message. Signaling channel to unblock it to receive a null message."); - this.RemoteChannel.incomingMessageSignal.Set(); - } - - this.Dispose(); - } - } - - /// <summary> - /// Replays the specified message as if it were received again. - /// </summary> - /// <param name="message">The message to replay.</param> - internal void Replay(IProtocolMessage message) { - this.ProcessIncomingMessage(this.CloneSerializedParts(message)); - } - - /// <summary> - /// Called from a remote party's thread to post a message to this channel for processing. - /// </summary> - /// <param name="message">The message that this channel should receive. This message will be cloned.</param> - internal void PostMessage(IProtocolMessage message) { - if (this.incomingMessage != null) { - // The remote party hasn't picked up the last message we sent them. - // Wait for a short period for them to pick it up before failing. - TestBase.TestLogger.Warn("We're blocked waiting to send a message to the remote party and they haven't processed the last message we sent them."); - this.RemoteChannel.messageReceivedSignal.WaitOne(500); - } - ErrorUtilities.VerifyInternal(this.incomingMessage == null, "Oops, a message is already waiting for the remote party!"); - this.incomingMessage = this.MessageDescriptions.GetAccessor(message).Serialize(); - var directedMessage = message as IDirectedProtocolMessage; - this.incomingMessageRecipient = (directedMessage != null && directedMessage.Recipient != null) ? new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods) : null; - var httpMessage = message as IHttpDirectRequest; - this.incomingMessageHttpHeaders = (httpMessage != null) ? httpMessage.Headers.Clone() : null; - this.incomingMessageSignal.Set(); - } - - internal void SaveCookies(HttpCookieCollection cookies) { - Requires.NotNull(cookies, "cookies"); - foreach (string cookieName in cookies) { - var cookie = cookies[cookieName]; - this.cookies.Set(cookie); - } - } - - protected internal override HttpRequestBase GetRequestFromContext() { - MessageReceivingEndpoint recipient; - WebHeaderCollection headers; - var messageData = this.AwaitIncomingMessage(out recipient, out headers); - CoordinatingHttpRequestInfo result; - if (messageData != null) { - result = new CoordinatingHttpRequestInfo(this, this.MessageFactory, messageData, recipient, this.cookies); - } else { - result = new CoordinatingHttpRequestInfo(recipient, this.cookies); - } - - if (headers != null) { - headers.ApplyTo(result.Headers); - } - - return result; - } - - protected override IProtocolMessage RequestCore(IDirectedProtocolMessage request) { - this.ProcessMessageFilter(request, true); - - // Drop the outgoing message in the other channel's in-slot and let them know it's there. - this.RemoteChannel.PostMessage(request); - - // Now wait for a response... - MessageReceivingEndpoint recipient; - WebHeaderCollection headers; - IDictionary<string, string> responseData = this.AwaitIncomingMessage(out recipient, out headers); - ErrorUtilities.VerifyInternal(recipient == null, "The recipient is expected to be null for direct responses."); - - // And deserialize it. - IDirectResponseProtocolMessage responseMessage = this.MessageFactory.GetNewResponseMessage(request, responseData); - if (responseMessage == null) { - return null; - } - - var responseAccessor = this.MessageDescriptions.GetAccessor(responseMessage); - responseAccessor.Deserialize(responseData); - var responseMessageHttpRequest = responseMessage as IHttpDirectRequest; - if (headers != null && responseMessageHttpRequest != null) { - headers.ApplyTo(responseMessageHttpRequest.Headers); - } - - this.ProcessMessageFilter(responseMessage, false); - return responseMessage; - } - - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { - this.ProcessMessageFilter(response, true); - return new CoordinatingOutgoingWebResponse(response, this.RemoteChannel, this); - } - - protected override OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) { - this.ProcessMessageFilter(message, true); - // In this mock transport, direct and indirect messages are the same. - return this.PrepareDirectResponse(message); - } - - protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { - var mockRequest = (CoordinatingHttpRequestInfo)request; - if (mockRequest.Message != null) { - this.ProcessMessageFilter(mockRequest.Message, false); - } - - return mockRequest.Message; - } - - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { - return this.wrappedChannel.ReadFromResponseCoreTestHook(response); - } - - protected override void ProcessIncomingMessage(IProtocolMessage message) { - this.wrappedChannel.ProcessIncomingMessageTestHook(message); - } - - /// <summary> - /// Clones a message, instantiating the new instance using <i>this</i> channel's - /// message factory. - /// </summary> - /// <typeparam name="T">The type of message to clone.</typeparam> - /// <param name="message">The message to clone.</param> - /// <returns>The new instance of the message.</returns> - /// <remarks> - /// This Clone method should <i>not</i> be used to send message clones to the remote - /// channel since their message factory is not used. - /// </remarks> - protected virtual T CloneSerializedParts<T>(T message) where T : class, IProtocolMessage { - Requires.NotNull(message, "message"); - - IProtocolMessage clonedMessage; - var messageAccessor = this.MessageDescriptions.GetAccessor(message); - var fields = messageAccessor.Serialize(); - - MessageReceivingEndpoint recipient = null; - var directedMessage = message as IDirectedProtocolMessage; - var directResponse = message as IDirectResponseProtocolMessage; - if (directedMessage != null && directedMessage.IsRequest()) { - if (directedMessage.Recipient != null) { - recipient = new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods); - } - - clonedMessage = this.MessageFactory.GetNewRequestMessage(recipient, fields); - } else if (directResponse != null && directResponse.IsDirectResponse()) { - clonedMessage = this.MessageFactory.GetNewResponseMessage(directResponse.OriginatingRequest, fields); - } else { - throw new InvalidOperationException("Totally expected a message to implement one of the two derived interface types."); - } - - ErrorUtilities.VerifyInternal(clonedMessage != null, "Message factory did not generate a message instance for " + message.GetType().Name); - - // Fill the cloned message with data. - var clonedMessageAccessor = this.MessageDescriptions.GetAccessor(clonedMessage); - clonedMessageAccessor.Deserialize(fields); - - return (T)clonedMessage; - } - - private static IMessageFactory GetMessageFactory(Channel channel) { - Requires.NotNull(channel, "channel"); - - return channel.MessageFactoryTestHook; - } - - private IDictionary<string, string> AwaitIncomingMessage(out MessageReceivingEndpoint recipient, out WebHeaderCollection headers) { - // Special care should be taken so that we don't indefinitely - // wait for a message that may never come due to a bug in the product - // or the test. - // There are two scenarios that we need to watch out for: - // 1. Two channels are waiting to receive messages from each other. - // 2. One channel is waiting for a message that will never come because - // the remote party has already finished executing. - lock (waitingForMessageCoordinationLock) { - // It's possible that a message was just barely transmitted either to this - // or the remote channel. So it's ok for the remote channel to be waiting - // if either it or we are already about to receive a message. - ErrorUtilities.VerifyInternal(!this.RemoteChannel.waitingForMessage || this.RemoteChannel.incomingMessage != null || this.incomingMessage != null, "This channel is expecting an incoming message from another channel that is also blocked waiting for an incoming message from us!"); - - // It's permissible that the remote channel has already closed if it left a message - // for us already. - ErrorUtilities.VerifyInternal(!this.RemoteChannel.simulationCompleted || this.incomingMessage != null, "This channel is expecting an incoming message from another channel that has already been closed."); - this.waitingForMessage = true; - } - - this.incomingMessageSignal.WaitOne(); - - lock (waitingForMessageCoordinationLock) { - this.waitingForMessage = false; - var response = this.incomingMessage; - recipient = this.incomingMessageRecipient; - headers = this.incomingMessageHttpHeaders; - this.incomingMessage = null; - this.incomingMessageRecipient = null; - this.incomingMessageHttpHeaders = null; - - // Briefly signal to another thread that might be waiting for our inbox to be empty - this.messageReceivedSignal.Set(); - this.messageReceivedSignal.Reset(); - - return response; - } - } - - private void ProcessMessageFilter(IProtocolMessage message, bool outgoing) { - if (outgoing) { - if (this.outgoingMessageFilter != null) { - this.outgoingMessageFilter(message); - } - } else { - if (this.incomingMessageFilter != null) { - this.incomingMessageFilter(message); - } - } - } - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingHttpRequestInfo.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingHttpRequestInfo.cs deleted file mode 100644 index 497503c..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingHttpRequestInfo.cs +++ /dev/null @@ -1,109 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatingHttpRequestInfo.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Collections.Generic; - using System.Net; - using System.Web; - - using DotNetOpenAuth.Messaging; - using Validation; - - internal class CoordinatingHttpRequestInfo : HttpRequestInfo { - private readonly Channel channel; - - private readonly IDictionary<string, string> messageData; - - private readonly IMessageFactory messageFactory; - - private readonly MessageReceivingEndpoint recipient; - - private IDirectedProtocolMessage message; - - /// <summary> - /// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class - /// that will generate a message when the <see cref="Message"/> property getter is called. - /// </summary> - /// <param name="channel">The channel.</param> - /// <param name="messageFactory">The message factory.</param> - /// <param name="messageData">The message data.</param> - /// <param name="recipient">The recipient.</param> - /// <param name="cookies">Cookies included in the incoming request.</param> - internal CoordinatingHttpRequestInfo( - Channel channel, - IMessageFactory messageFactory, - IDictionary<string, string> messageData, - MessageReceivingEndpoint recipient, - HttpCookieCollection cookies) - : this(recipient, cookies) { - Requires.NotNull(channel, "channel"); - Requires.NotNull(messageFactory, "messageFactory"); - Requires.NotNull(messageData, "messageData"); - this.channel = channel; - this.messageData = messageData; - this.messageFactory = messageFactory; - } - - /// <summary> - /// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class - /// that will not generate any message. - /// </summary> - /// <param name="recipient">The recipient.</param> - /// <param name="cookies">Cookies included in the incoming request.</param> - internal CoordinatingHttpRequestInfo(MessageReceivingEndpoint recipient, HttpCookieCollection cookies) - : base(GetHttpVerb(recipient), recipient != null ? recipient.Location : new Uri("http://host/path"), cookies: cookies) { - this.recipient = recipient; - } - - /// <summary> - /// Initializes a new instance of the <see cref="CoordinatingHttpRequestInfo"/> class. - /// </summary> - /// <param name="message">The message being passed in through a mock transport. May be null.</param> - /// <param name="httpMethod">The HTTP method that the incoming request came in on, whether or not <paramref name="message"/> is null.</param> - internal CoordinatingHttpRequestInfo(IDirectedProtocolMessage message, HttpDeliveryMethods httpMethod) - : base(GetHttpVerb(httpMethod), message.Recipient) { - this.message = message; - } - - /// <summary> - /// Gets the message deserialized from the remote channel. - /// </summary> - internal IDirectedProtocolMessage Message { - get { - if (this.message == null && this.messageData != null) { - var message = this.messageFactory.GetNewRequestMessage(this.recipient, this.messageData); - if (message != null) { - this.channel.MessageDescriptions.GetAccessor(message).Deserialize(this.messageData); - this.message = message; - } - } - - return this.message; - } - } - - private static string GetHttpVerb(MessageReceivingEndpoint recipient) { - if (recipient == null) { - return "GET"; - } - - return GetHttpVerb(recipient.AllowedMethods); - } - - private static string GetHttpVerb(HttpDeliveryMethods httpMethod) { - if ((httpMethod & HttpDeliveryMethods.GetRequest) != 0) { - return "GET"; - } - - if ((httpMethod & HttpDeliveryMethods.PostRequest) != 0) { - return "POST"; - } - - throw new ArgumentOutOfRangeException(); - } - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuth2AuthServerChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuth2AuthServerChannel.cs deleted file mode 100644 index 463b149..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuth2AuthServerChannel.cs +++ /dev/null @@ -1,33 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatingOAuth2AuthServerChannel.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth2; - using DotNetOpenAuth.OAuth2.ChannelElements; - - internal class CoordinatingOAuth2AuthServerChannel : CoordinatingChannel, IOAuth2ChannelWithAuthorizationServer { - private OAuth2AuthorizationServerChannel wrappedChannel; - - internal CoordinatingOAuth2AuthServerChannel(Channel wrappedChannel, Action<IProtocolMessage> incomingMessageFilter, Action<IProtocolMessage> outgoingMessageFilter) - : base(wrappedChannel, incomingMessageFilter, outgoingMessageFilter) { - this.wrappedChannel = (OAuth2AuthorizationServerChannel)wrappedChannel; - } - - public IAuthorizationServerHost AuthorizationServer { - get { return this.wrappedChannel.AuthorizationServer; } - } - - public IScopeSatisfiedCheck ScopeSatisfiedCheck { - get { return this.wrappedChannel.ScopeSatisfiedCheck; } - set { this.wrappedChannel.ScopeSatisfiedCheck = value; } - } - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuth2ClientChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuth2ClientChannel.cs deleted file mode 100644 index 96091ac..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuth2ClientChannel.cs +++ /dev/null @@ -1,37 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatingOAuth2ClientChannel.cs" company="Andrew Arnott"> -// Copyright (c) Andrew Arnott. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth2.ChannelElements; - - internal class CoordinatingOAuth2ClientChannel : CoordinatingChannel, IOAuth2ChannelWithClient { - private OAuth2ClientChannel wrappedChannel; - - internal CoordinatingOAuth2ClientChannel(Channel wrappedChannel, Action<IProtocolMessage> incomingMessageFilter, Action<IProtocolMessage> outgoingMessageFilter) - : base(wrappedChannel, incomingMessageFilter, outgoingMessageFilter) { - this.wrappedChannel = (OAuth2ClientChannel)wrappedChannel; - } - - public string ClientIdentifier { - get { return this.wrappedChannel.ClientIdentifier; } - set { this.wrappedChannel.ClientIdentifier = value; } - } - - public DotNetOpenAuth.OAuth2.ClientCredentialApplicator ClientCredentialApplicator { - get { return this.wrappedChannel.ClientCredentialApplicator; } - set { this.wrappedChannel.ClientCredentialApplicator = value; } - } - - public System.Xml.XmlDictionaryReaderQuotas JsonReaderQuotas { - get { return this.XmlDictionaryReaderQuotas; } - } - } -}
\ No newline at end of file diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs deleted file mode 100644 index 9b552d3..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthConsumerChannel.cs +++ /dev/null @@ -1,155 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatingOAuthConsumerChannel.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Threading; - using System.Web; - - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Bindings; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - using Validation; - - /// <summary> - /// A special channel used in test simulations to pass messages directly between two parties. - /// </summary> - internal class CoordinatingOAuthConsumerChannel : OAuthConsumerChannel { - private EventWaitHandle incomingMessageSignal = new AutoResetEvent(false); - - /// <summary> - /// Initializes a new instance of the <see cref="CoordinatingOAuthConsumerChannel"/> class. - /// </summary> - /// <param name="signingBindingElement">The signing element for the Consumer to use. Null for the Service Provider.</param> - /// <param name="tokenManager">The token manager to use.</param> - /// <param name="securitySettings">The security settings.</param> - internal CoordinatingOAuthConsumerChannel(ITamperProtectionChannelBindingElement signingBindingElement, IConsumerTokenManager tokenManager, DotNetOpenAuth.OAuth.ConsumerSecuritySettings securitySettings) - : base( - signingBindingElement, - new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge), - tokenManager, - securitySettings) { - } - - internal EventWaitHandle IncomingMessageSignal { - get { return this.incomingMessageSignal; } - } - - internal IProtocolMessage IncomingMessage { get; set; } - - internal OutgoingWebResponse IncomingRawResponse { get; set; } - - /// <summary> - /// Gets or sets the coordinating channel used by the other party. - /// </summary> - internal CoordinatingOAuthServiceProviderChannel RemoteChannel { get; set; } - - internal OutgoingWebResponse RequestProtectedResource(AccessProtectedResourceRequest request) { - ((ITamperResistantOAuthMessage)request).HttpMethod = this.GetHttpMethod(((ITamperResistantOAuthMessage)request).HttpMethods); - this.ProcessOutgoingMessage(request); - var requestInfo = this.SpoofHttpMethod(request); - TestBase.TestLogger.InfoFormat("Sending protected resource request: {0}", requestInfo.Message); - // Drop the outgoing message in the other channel's in-slot and let them know it's there. - this.RemoteChannel.IncomingMessage = requestInfo.Message; - this.RemoteChannel.IncomingMessageSignal.Set(); - return this.AwaitIncomingRawResponse(); - } - - protected internal override HttpRequestBase GetRequestFromContext() { - var directedMessage = (IDirectedProtocolMessage)this.AwaitIncomingMessage(); - return new CoordinatingHttpRequestInfo(directedMessage, directedMessage.HttpMethods); - } - - protected override IProtocolMessage RequestCore(IDirectedProtocolMessage request) { - var requestInfo = this.SpoofHttpMethod(request); - // Drop the outgoing message in the other channel's in-slot and let them know it's there. - this.RemoteChannel.IncomingMessage = requestInfo.Message; - this.RemoteChannel.IncomingMessageSignal.Set(); - // Now wait for a response... - return this.AwaitIncomingMessage(); - } - - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { - this.RemoteChannel.IncomingMessage = this.CloneSerializedParts(response); - this.RemoteChannel.IncomingMessageSignal.Set(); - return new OutgoingWebResponse(); // not used, but returning null is not allowed - } - - protected override OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) { - // In this mock transport, direct and indirect messages are the same. - return this.PrepareDirectResponse(message); - } - - protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { - var mockRequest = (CoordinatingHttpRequestInfo)request; - return mockRequest.Message; - } - - /// <summary> - /// Spoof HTTP request information for signing/verification purposes. - /// </summary> - /// <param name="message">The message to add a pretend HTTP method to.</param> - /// <returns>A spoofed HttpRequestInfo that wraps the new message.</returns> - private CoordinatingHttpRequestInfo SpoofHttpMethod(IDirectedProtocolMessage message) { - var signedMessage = message as ITamperResistantOAuthMessage; - if (signedMessage != null) { - string httpMethod = this.GetHttpMethod(signedMessage.HttpMethods); - signedMessage.HttpMethod = httpMethod; - } - - var requestInfo = new CoordinatingHttpRequestInfo(this.CloneSerializedParts(message), message.HttpMethods); - return requestInfo; - } - - private IProtocolMessage AwaitIncomingMessage() { - this.incomingMessageSignal.WaitOne(); - IProtocolMessage response = this.IncomingMessage; - this.IncomingMessage = null; - return response; - } - - private OutgoingWebResponse AwaitIncomingRawResponse() { - this.incomingMessageSignal.WaitOne(); - OutgoingWebResponse response = this.IncomingRawResponse; - this.IncomingRawResponse = null; - return response; - } - - private T CloneSerializedParts<T>(T message) where T : class, IProtocolMessage { - Requires.NotNull(message, "message"); - - IProtocolMessage clonedMessage; - var messageAccessor = this.MessageDescriptions.GetAccessor(message); - var fields = messageAccessor.Serialize(); - - MessageReceivingEndpoint recipient = null; - var directedMessage = message as IDirectedProtocolMessage; - var directResponse = message as IDirectResponseProtocolMessage; - if (directedMessage != null && directedMessage.IsRequest()) { - if (directedMessage.Recipient != null) { - recipient = new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods); - } - - clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewRequestMessage(recipient, fields); - } else if (directResponse != null && directResponse.IsDirectResponse()) { - clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewResponseMessage(directResponse.OriginatingRequest, fields); - } else { - throw new InvalidOperationException("Totally expected a message to implement one of the two derived interface types."); - } - - // Fill the cloned message with data. - var clonedMessageAccessor = this.MessageDescriptions.GetAccessor(clonedMessage); - clonedMessageAccessor.Deserialize(fields); - - return (T)clonedMessage; - } - - private string GetHttpMethod(HttpDeliveryMethods methods) { - return (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET"; - } - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs deleted file mode 100644 index a6f2a7f..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOAuthServiceProviderChannel.cs +++ /dev/null @@ -1,163 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatingOAuthServiceProviderChannel.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Threading; - using System.Web; - - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Bindings; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - using NUnit.Framework; - using Validation; - - /// <summary> - /// A special channel used in test simulations to pass messages directly between two parties. - /// </summary> - internal class CoordinatingOAuthServiceProviderChannel : OAuthServiceProviderChannel { - private EventWaitHandle incomingMessageSignal = new AutoResetEvent(false); - - /// <summary> - /// Initializes a new instance of the <see cref="CoordinatingOAuthServiceProviderChannel"/> class. - /// </summary> - /// <param name="signingBindingElement">The signing element for the Consumer to use. Null for the Service Provider.</param> - /// <param name="tokenManager">The token manager to use.</param> - /// <param name="securitySettings">The security settings.</param> - internal CoordinatingOAuthServiceProviderChannel(ITamperProtectionChannelBindingElement signingBindingElement, IServiceProviderTokenManager tokenManager, DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings securitySettings) - : base( - signingBindingElement, - new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge), - tokenManager, - securitySettings, - new OAuthServiceProviderMessageFactory(tokenManager)) { - } - - internal EventWaitHandle IncomingMessageSignal { - get { return this.incomingMessageSignal; } - } - - internal IProtocolMessage IncomingMessage { get; set; } - - internal OutgoingWebResponse IncomingRawResponse { get; set; } - - /// <summary> - /// Gets or sets the coordinating channel used by the other party. - /// </summary> - internal CoordinatingOAuthConsumerChannel RemoteChannel { get; set; } - - internal OutgoingWebResponse RequestProtectedResource(AccessProtectedResourceRequest request) { - ((ITamperResistantOAuthMessage)request).HttpMethod = GetHttpMethod(((ITamperResistantOAuthMessage)request).HttpMethods); - this.ProcessOutgoingMessage(request); - var requestInfo = this.SpoofHttpMethod(request); - TestBase.TestLogger.InfoFormat("Sending protected resource request: {0}", requestInfo.Message); - // Drop the outgoing message in the other channel's in-slot and let them know it's there. - this.RemoteChannel.IncomingMessage = requestInfo.Message; - this.RemoteChannel.IncomingMessageSignal.Set(); - return this.AwaitIncomingRawResponse(); - } - - internal void SendDirectRawResponse(OutgoingWebResponse response) { - this.RemoteChannel.IncomingRawResponse = response; - this.RemoteChannel.IncomingMessageSignal.Set(); - } - - protected internal override HttpRequestBase GetRequestFromContext() { - var directedMessage = (IDirectedProtocolMessage)this.AwaitIncomingMessage(); - return new CoordinatingHttpRequestInfo(directedMessage, directedMessage.HttpMethods); - } - - protected override IProtocolMessage RequestCore(IDirectedProtocolMessage request) { - var requestInfo = this.SpoofHttpMethod(request); - // Drop the outgoing message in the other channel's in-slot and let them know it's there. - this.RemoteChannel.IncomingMessage = requestInfo.Message; - this.RemoteChannel.IncomingMessageSignal.Set(); - // Now wait for a response... - return this.AwaitIncomingMessage(); - } - - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { - this.RemoteChannel.IncomingMessage = this.CloneSerializedParts(response); - this.RemoteChannel.IncomingMessageSignal.Set(); - return new OutgoingWebResponse(); // not used, but returning null is not allowed - } - - protected override OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) { - // In this mock transport, direct and indirect messages are the same. - return this.PrepareDirectResponse(message); - } - - protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestBase request) { - var mockRequest = (CoordinatingHttpRequestInfo)request; - return mockRequest.Message; - } - - private static string GetHttpMethod(HttpDeliveryMethods methods) { - return (methods & HttpDeliveryMethods.PostRequest) != 0 ? "POST" : "GET"; - } - - /// <summary> - /// Spoof HTTP request information for signing/verification purposes. - /// </summary> - /// <param name="message">The message to add a pretend HTTP method to.</param> - /// <returns>A spoofed HttpRequestInfo that wraps the new message.</returns> - private CoordinatingHttpRequestInfo SpoofHttpMethod(IDirectedProtocolMessage message) { - var signedMessage = message as ITamperResistantOAuthMessage; - if (signedMessage != null) { - string httpMethod = GetHttpMethod(signedMessage.HttpMethods); - signedMessage.HttpMethod = httpMethod; - } - - var requestInfo = new CoordinatingHttpRequestInfo(this.CloneSerializedParts(message), message.HttpMethods); - return requestInfo; - } - - private IProtocolMessage AwaitIncomingMessage() { - this.IncomingMessageSignal.WaitOne(); - Assert.That(this.IncomingMessage, Is.Not.Null, "Incoming message signaled, but none supplied."); - IProtocolMessage response = this.IncomingMessage; - this.IncomingMessage = null; - return response; - } - - private OutgoingWebResponse AwaitIncomingRawResponse() { - this.IncomingMessageSignal.WaitOne(); - OutgoingWebResponse response = this.IncomingRawResponse; - this.IncomingRawResponse = null; - return response; - } - - private T CloneSerializedParts<T>(T message) where T : class, IProtocolMessage { - Requires.NotNull(message, "message"); - - IProtocolMessage clonedMessage; - var messageAccessor = this.MessageDescriptions.GetAccessor(message); - var fields = messageAccessor.Serialize(); - - MessageReceivingEndpoint recipient = null; - var directedMessage = message as IDirectedProtocolMessage; - var directResponse = message as IDirectResponseProtocolMessage; - if (directedMessage != null && directedMessage.IsRequest()) { - if (directedMessage.Recipient != null) { - recipient = new MessageReceivingEndpoint(directedMessage.Recipient, directedMessage.HttpMethods); - } - - clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewRequestMessage(recipient, fields); - } else if (directResponse != null && directResponse.IsDirectResponse()) { - clonedMessage = this.RemoteChannel.MessageFactoryTestHook.GetNewResponseMessage(directResponse.OriginatingRequest, fields); - } else { - throw new InvalidOperationException("Totally expected a message to implement one of the two derived interface types."); - } - - // Fill the cloned message with data. - var clonedMessageAccessor = this.MessageDescriptions.GetAccessor(clonedMessage); - clonedMessageAccessor.Deserialize(fields); - - return (T)clonedMessage; - } - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs deleted file mode 100644 index 9df791c..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs +++ /dev/null @@ -1,47 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="CoordinatingOutgoingWebResponse.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Linq; - using System.Text; - using DotNetOpenAuth.Messaging; - using Validation; - - internal class CoordinatingOutgoingWebResponse : OutgoingWebResponse { - private CoordinatingChannel receivingChannel; - - private CoordinatingChannel sendingChannel; - - /// <summary> - /// Initializes a new instance of the <see cref="CoordinatingOutgoingWebResponse"/> class. - /// </summary> - /// <param name="message">The direct response message to send to the remote channel. This message will be cloned.</param> - /// <param name="receivingChannel">The receiving channel.</param> - /// <param name="sendingChannel">The sending channel.</param> - internal CoordinatingOutgoingWebResponse(IProtocolMessage message, CoordinatingChannel receivingChannel, CoordinatingChannel sendingChannel) { - Requires.NotNull(message, "message"); - Requires.NotNull(receivingChannel, "receivingChannel"); - Requires.NotNull(sendingChannel, "sendingChannel"); - - this.receivingChannel = receivingChannel; - this.sendingChannel = sendingChannel; - this.OriginalMessage = message; - } - - [EditorBrowsable(EditorBrowsableState.Never)] - public override void Send() { - this.Respond(); - } - - public override void Respond() { - this.sendingChannel.SaveCookies(this.Cookies); - this.receivingChannel.PostMessage(this.OriginalMessage); - } - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs index 494a1c1..7fac125 100644 --- a/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs +++ b/src/DotNetOpenAuth.Test/Mocks/InMemoryTokenManager.cs @@ -14,7 +14,7 @@ namespace DotNetOpenAuth.Test.Mocks { using DotNetOpenAuth.OAuth.Messages; using DotNetOpenAuth.Test.OAuth; - internal class InMemoryTokenManager : IConsumerTokenManager, IServiceProviderTokenManager { + internal class InMemoryTokenManager : IServiceProviderTokenManager { private KeyedCollectionDelegate<string, ConsumerInfo> consumers = new KeyedCollectionDelegate<string, ConsumerInfo>(c => c.Key); private KeyedCollectionDelegate<string, TokenInfo> tokens = new KeyedCollectionDelegate<string, TokenInfo>(t => t.Token); @@ -28,18 +28,6 @@ namespace DotNetOpenAuth.Test.Mocks { /// </summary> private List<string> accessTokens = new List<string>(); - #region IConsumerTokenManager Members - - public string ConsumerKey { - get { return this.consumers.Single().Key; } - } - - public string ConsumerSecret { - get { return this.consumers.Single().Secret; } - } - - #endregion - #region ITokenManager Members public string GetTokenSecret(string token) { diff --git a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs index d20671e..349be56 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockHttpRequest.cs @@ -10,7 +10,9 @@ namespace DotNetOpenAuth.Test.Mocks { using System.Globalization; using System.IO; using System.Net; + using System.Net.Http; using System.Text; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; @@ -19,71 +21,8 @@ namespace DotNetOpenAuth.Test.Mocks { using DotNetOpenAuth.Yadis; using Validation; - internal class MockHttpRequest { - private readonly Dictionary<Uri, IncomingWebResponse> registeredMockResponses = new Dictionary<Uri, IncomingWebResponse>(); - - private MockHttpRequest(IDirectWebRequestHandler mockHandler) { - Requires.NotNull(mockHandler, "mockHandler"); - this.MockWebRequestHandler = mockHandler; - } - - internal IDirectWebRequestHandler MockWebRequestHandler { get; private set; } - - internal static MockHttpRequest CreateUntrustedMockHttpHandler() { - TestWebRequestHandler testHandler = new TestWebRequestHandler(); - UntrustedWebRequestHandler untrustedHandler = new UntrustedWebRequestHandler(testHandler); - if (!untrustedHandler.WhitelistHosts.Contains("localhost")) { - untrustedHandler.WhitelistHosts.Add("localhost"); - } - untrustedHandler.WhitelistHosts.Add(OpenIdTestBase.OPUri.Host); - MockHttpRequest mock = new MockHttpRequest(untrustedHandler); - testHandler.Callback = mock.GetMockResponse; - return mock; - } - - internal void RegisterMockResponse(IncomingWebResponse response) { - Requires.NotNull(response, "response"); - if (this.registeredMockResponses.ContainsKey(response.RequestUri)) { - Logger.Http.WarnFormat("Mock HTTP response already registered for {0}.", response.RequestUri); - } else { - this.registeredMockResponses.Add(response.RequestUri, response); - } - } - - internal void RegisterMockResponse(Uri requestUri, string contentType, string responseBody) { - this.RegisterMockResponse(requestUri, requestUri, contentType, responseBody); - } - - internal void RegisterMockResponse(Uri requestUri, Uri responseUri, string contentType, string responseBody) { - this.RegisterMockResponse(requestUri, responseUri, contentType, new WebHeaderCollection(), responseBody); - } - - internal void RegisterMockResponse(Uri requestUri, Uri responseUri, string contentType, WebHeaderCollection headers, string responseBody) { - Requires.NotNull(requestUri, "requestUri"); - Requires.NotNull(responseUri, "responseUri"); - Requires.NotNullOrEmpty(contentType, "contentType"); - - // Set up the redirect if appropriate - if (requestUri != responseUri) { - this.RegisterMockRedirect(requestUri, responseUri); - } - - string contentEncoding = null; - MemoryStream stream = new MemoryStream(); - StreamWriter sw = new StreamWriter(stream); - sw.Write(responseBody); - sw.Flush(); - stream.Seek(0, SeekOrigin.Begin); - this.RegisterMockResponse(new CachedDirectWebResponse(responseUri, responseUri, headers ?? new WebHeaderCollection(), HttpStatusCode.OK, contentType, contentEncoding, stream)); - } - - internal void RegisterMockXrdsResponses(IDictionary<string, string> requestUriAndResponseBody) { - foreach (var pair in requestUriAndResponseBody) { - this.RegisterMockResponse(new Uri(pair.Key), "text/xml; saml=false; https=false; charset=UTF-8", pair.Value); - } - } - - internal void RegisterMockXrdsResponse(IdentifierDiscoveryResult endpoint) { + internal static class MockHttpRequest { + internal static void RegisterMockXrdsResponse(this TestBase test, IdentifierDiscoveryResult endpoint) { Requires.NotNull(endpoint, "endpoint"); string identityUri; @@ -92,13 +31,14 @@ namespace DotNetOpenAuth.Test.Mocks { } else { identityUri = endpoint.UserSuppliedIdentifier ?? endpoint.ClaimedIdentifier; } - this.RegisterMockXrdsResponse(new Uri(identityUri), new IdentifierDiscoveryResult[] { endpoint }); + + RegisterMockXrdsResponse(test, new Uri(identityUri), new IdentifierDiscoveryResult[] { endpoint }); } - internal void RegisterMockXrdsResponse(Uri respondingUri, IEnumerable<IdentifierDiscoveryResult> endpoints) { + internal static void RegisterMockXrdsResponse(this TestBase test, Uri respondingUri, IEnumerable<IdentifierDiscoveryResult> endpoints) { Requires.NotNull(endpoints, "endpoints"); - StringBuilder xrds = new StringBuilder(); + var xrds = new StringBuilder(); xrds.AppendLine(@"<xrds:XRDS xmlns:xrds='xri://$xrds' xmlns:openid='http://openid.net/xmlns/1.0' xmlns='xri://$xrd*($v*2.0)'> <XRD>"); foreach (var endpoint in endpoints) { @@ -127,10 +67,10 @@ namespace DotNetOpenAuth.Test.Mocks { </XRD> </xrds:XRDS>"); - this.RegisterMockResponse(respondingUri, ContentTypes.Xrds, xrds.ToString()); + test.Handle(respondingUri).By(xrds.ToString(), ContentTypes.Xrds); } - internal void RegisterMockXrdsResponse(UriIdentifier directedIdentityAssignedIdentifier, IdentifierDiscoveryResult providerEndpoint) { + internal static void RegisterMockXrdsResponse(this TestBase test, UriIdentifier directedIdentityAssignedIdentifier, IdentifierDiscoveryResult providerEndpoint) { IdentifierDiscoveryResult identityEndpoint = IdentifierDiscoveryResult.CreateForClaimedIdentifier( directedIdentityAssignedIdentifier, directedIdentityAssignedIdentifier, @@ -138,16 +78,16 @@ namespace DotNetOpenAuth.Test.Mocks { new ProviderEndpointDescription(providerEndpoint.ProviderEndpoint, providerEndpoint.Capabilities), 10, 10); - this.RegisterMockXrdsResponse(identityEndpoint); + RegisterMockXrdsResponse(test, identityEndpoint); } - internal Identifier RegisterMockXrdsResponse(string embeddedResourcePath) { - UriIdentifier id = new Uri(new Uri("http://localhost/"), embeddedResourcePath); - this.RegisterMockResponse(id, "application/xrds+xml", OpenIdTestBase.LoadEmbeddedFile(embeddedResourcePath)); - return id; + internal static void RegisterMockXrdsResponse(this TestBase test, string embeddedResourcePath, out Identifier id) { + id = new Uri(new Uri("http://localhost/"), embeddedResourcePath); + test.Handle(new Uri(id)) + .By(OpenIdTestBase.LoadEmbeddedFile(embeddedResourcePath), "application/xrds+xml"); } - internal void RegisterMockRPDiscovery() { + internal static void RegisterMockRPDiscovery(this TestBase test, bool ssl) { string template = @"<xrds:XRDS xmlns:xrds='xri://$xrds' xmlns:openid='http://openid.net/xmlns/1.0' xmlns='xri://$xrd*($v*2.0)'> <XRD> <Service priority='10'> @@ -164,44 +104,62 @@ namespace DotNetOpenAuth.Test.Mocks { HttpUtility.HtmlEncode(OpenIdTestBase.RPRealmUri.AbsoluteUri), HttpUtility.HtmlEncode(OpenIdTestBase.RPRealmUriSsl.AbsoluteUri)); - this.RegisterMockResponse(OpenIdTestBase.RPRealmUri, ContentTypes.Xrds, xrds); - this.RegisterMockResponse(OpenIdTestBase.RPRealmUriSsl, ContentTypes.Xrds, xrds); + test.Handle(ssl ? OpenIdTestBase.RPRealmUriSsl : OpenIdTestBase.RPRealmUri) + .By(xrds, ContentTypes.Xrds); } - internal void DeleteResponse(Uri requestUri) { - this.registeredMockResponses.Remove(requestUri); + internal static void RegisterMockRedirect(this TestBase test, Uri origin, Uri redirectLocation) { + var response = new HttpResponseMessage(HttpStatusCode.Redirect); + response.Headers.Location = redirectLocation; + test.Handle(origin).By(req => response); } - internal void RegisterMockRedirect(Uri origin, Uri redirectLocation) { - var redirectionHeaders = new WebHeaderCollection { - { HttpResponseHeader.Location, redirectLocation.AbsoluteUri }, - }; - IncomingWebResponse response = new CachedDirectWebResponse(origin, origin, redirectionHeaders, HttpStatusCode.Redirect, null, null, new MemoryStream()); - this.RegisterMockResponse(response); + internal static void RegisterMockXrdsResponses(this TestBase test, IEnumerable<KeyValuePair<string, string>> urlXrdsPairs) { + Requires.NotNull(urlXrdsPairs, "urlXrdsPairs"); + + foreach (var keyValuePair in urlXrdsPairs) { + test.Handle(new Uri(keyValuePair.Key)).By(keyValuePair.Value, ContentTypes.Xrds); + } } - internal void RegisterMockNotFound(Uri requestUri) { - CachedDirectWebResponse errorResponse = new CachedDirectWebResponse( - requestUri, - requestUri, - new WebHeaderCollection(), - HttpStatusCode.NotFound, - "text/plain", - Encoding.UTF8.WebName, - new MemoryStream(Encoding.UTF8.GetBytes("Not found."))); - this.RegisterMockResponse(errorResponse); + internal static void RegisterMockResponse(this TestBase test, Uri url, string contentType, string content) { + test.Handle(url).By(content, contentType); } - private IncomingWebResponse GetMockResponse(HttpWebRequest request) { - IncomingWebResponse response; - if (this.registeredMockResponses.TryGetValue(request.RequestUri, out response)) { - // reset response stream position so this response can be reused on a subsequent request. - response.ResponseStream.Seek(0, SeekOrigin.Begin); + internal static void RegisterMockResponse(this TestBase test, Uri requestUri, Uri responseUri, string contentType, string content) { + RegisterMockResponse(test, requestUri, responseUri, contentType, null, content); + } + + internal static void RegisterMockResponse(this TestBase test, Uri requestUri, Uri responseUri, string contentType, WebHeaderCollection headers, string content) { + Requires.NotNull(requestUri, "requestUri"); + Requires.NotNull(responseUri, "responseUri"); + Requires.NotNullOrEmpty(contentType, "contentType"); + + test.Handle(requestUri).By(req => { + var response = new HttpResponseMessage(); + response.RequestMessage = req; + + if (requestUri != responseUri) { + // Simulate having followed redirects to get the final response. + var clonedRequest = MessagingUtilities.Clone(req); + clonedRequest.RequestUri = responseUri; + response.RequestMessage = clonedRequest; + } + + response.CopyHeadersFrom(headers); + response.Content = new StringContent(content, Encoding.Default, contentType); return response; - } else { - ////Assert.Fail("Unexpected HTTP request: {0}", uri); - Logger.Http.WarnFormat("Unexpected HTTP request: {0}", request.RequestUri); - return new CachedDirectWebResponse(request.RequestUri, request.RequestUri, new WebHeaderCollection(), HttpStatusCode.NotFound, "text/html", null, new MemoryStream()); + }); + } + + private static void CopyHeadersFrom(this HttpResponseMessage message, WebHeaderCollection headers) { + if (headers != null) { + foreach (string headerName in headers) { + string[] headerValues = headers.GetValues(headerName); + if (!message.Headers.TryAddWithoutValidation(headerName, headerValues)) { + message.Content.Headers.TryAddWithoutValidation(headerName, headerValues); + } + } } } } diff --git a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs b/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs deleted file mode 100644 index f020923..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/MockIdentifier.cs +++ /dev/null @@ -1,71 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="MockIdentifier.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Collections.Generic; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OpenId; - using DotNetOpenAuth.OpenId.RelyingParty; - using Validation; - - /// <summary> - /// Performs similar to an ordinary <see cref="Identifier"/>, but when called upon - /// to perform discovery, it returns a preset list of sevice endpoints to avoid - /// having a dependency on a hosted web site to actually perform discovery on. - /// </summary> - internal class MockIdentifier : Identifier { - private IEnumerable<IdentifierDiscoveryResult> endpoints; - - private MockHttpRequest mockHttpRequest; - - private Identifier wrappedIdentifier; - - public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<IdentifierDiscoveryResult> endpoints) - : base(wrappedIdentifier.OriginalString, false) { - Requires.NotNull(wrappedIdentifier, "wrappedIdentifier"); - Requires.NotNull(mockHttpRequest, "mockHttpRequest"); - Requires.NotNull(endpoints, "endpoints"); - - this.wrappedIdentifier = wrappedIdentifier; - this.endpoints = endpoints; - this.mockHttpRequest = mockHttpRequest; - - // Register a mock HTTP response to enable discovery of this identifier within the RP - // without having to host an ASP.NET site within the test. - mockHttpRequest.RegisterMockXrdsResponse(new Uri(wrappedIdentifier.ToString()), endpoints); - } - - internal IEnumerable<IdentifierDiscoveryResult> DiscoveryEndpoints { - get { return this.endpoints; } - } - - public override string ToString() { - return this.wrappedIdentifier.ToString(); - } - - public override bool Equals(object obj) { - return this.wrappedIdentifier.Equals(obj); - } - - public override int GetHashCode() { - return this.wrappedIdentifier.GetHashCode(); - } - - internal override Identifier TrimFragment() { - return this; - } - - internal override bool TryRequireSsl(out Identifier secureIdentifier) { - // We take special care to make our wrapped identifier secure, but still - // return a mocked (secure) identifier. - Identifier secureWrappedIdentifier; - bool result = this.wrappedIdentifier.TryRequireSsl(out secureWrappedIdentifier); - secureIdentifier = new MockIdentifier(secureWrappedIdentifier, this.mockHttpRequest, this.endpoints); - return result; - } - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/MockIdentifierDiscoveryService.cs b/src/DotNetOpenAuth.Test/Mocks/MockIdentifierDiscoveryService.cs deleted file mode 100644 index 0118851..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/MockIdentifierDiscoveryService.cs +++ /dev/null @@ -1,47 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="MockIdentifierDiscoveryService.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OpenId; - using DotNetOpenAuth.OpenId.RelyingParty; - - internal class MockIdentifierDiscoveryService : IIdentifierDiscoveryService { - /// <summary> - /// Initializes a new instance of the <see cref="MockIdentifierDiscoveryService"/> class. - /// </summary> - public MockIdentifierDiscoveryService() { - } - - #region IIdentifierDiscoveryService Members - - /// <summary> - /// Performs discovery on the specified identifier. - /// </summary> - /// <param name="identifier">The identifier to perform discovery on.</param> - /// <param name="requestHandler">The means to place outgoing HTTP requests.</param> - /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param> - /// <returns> - /// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty. - /// </returns> - public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) { - var mockIdentifier = identifier as MockIdentifier; - if (mockIdentifier == null) { - abortDiscoveryChain = false; - return Enumerable.Empty<IdentifierDiscoveryResult>(); - } - - abortDiscoveryChain = true; - return mockIdentifier.DiscoveryEndpoints; - } - - #endregion - } -} diff --git a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs index 8509c03..38f9daf 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockRealm.cs @@ -7,6 +7,9 @@ namespace DotNetOpenAuth.Test.Mocks { using System; using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using Validation; @@ -30,15 +33,16 @@ namespace DotNetOpenAuth.Test.Mocks { /// Searches for an XRDS document at the realm URL, and if found, searches /// for a description of a relying party endpoints (OpenId login pages). /// </summary> - /// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param> + /// <param name="hostFactories">The host factories.</param> /// <param name="allowRedirects">Whether redirects may be followed when discovering the Realm. /// This may be true when creating an unsolicited assertion, but must be /// false when performing return URL verification per 2.0 spec section 9.2.1.</param> + /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The details of the endpoints if found, otherwise null. /// </returns> - internal override IEnumerable<RelyingPartyEndpointDescription> DiscoverReturnToEndpoints(IDirectWebRequestHandler requestHandler, bool allowRedirects) { - return this.relyingPartyDescriptions; + internal override Task<IEnumerable<RelyingPartyEndpointDescription>> DiscoverReturnToEndpointsAsync(IHostFactories hostFactories, bool allowRedirects, CancellationToken cancellationToken) { + return Task.FromResult<IEnumerable<RelyingPartyEndpointDescription>>(this.relyingPartyDescriptions); } } } diff --git a/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs index 1733f17..58a2367 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockReplayProtectionBindingElement.cs @@ -5,6 +5,9 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.Mocks { + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using NUnit.Framework; @@ -23,17 +26,17 @@ namespace DotNetOpenAuth.Test.Mocks { /// </summary> public Channel Channel { get; set; } - MessageProtections? IChannelBindingElement.ProcessOutgoingMessage(IProtocolMessage message) { + Task<MessageProtections?> IChannelBindingElement.ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var replayMessage = message as IReplayProtectedProtocolMessage; if (replayMessage != null) { replayMessage.Nonce = "someNonce"; - return MessageProtections.ReplayProtection; + return MessageProtectionTasks.ReplayProtection; } - return null; + return MessageProtectionTasks.Null; } - MessageProtections? IChannelBindingElement.ProcessIncomingMessage(IProtocolMessage message) { + Task<MessageProtections?> IChannelBindingElement.ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var replayMessage = message as IReplayProtectedProtocolMessage; if (replayMessage != null) { Assert.AreEqual("someNonce", replayMessage.Nonce, "The nonce didn't serialize correctly, or something"); @@ -42,10 +45,10 @@ namespace DotNetOpenAuth.Test.Mocks { throw new ReplayedMessageException(message); } this.messageReceived = true; - return MessageProtections.ReplayProtection; + return MessageProtectionTasks.ReplayProtection; } - return null; + return MessageProtectionTasks.Null; } #endregion diff --git a/src/DotNetOpenAuth.Test/Mocks/MockSigningBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockSigningBindingElement.cs index aa68b0b..f0b2bfc 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockSigningBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockSigningBindingElement.cs @@ -9,6 +9,9 @@ namespace DotNetOpenAuth.Test.Mocks { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; @@ -26,26 +29,26 @@ namespace DotNetOpenAuth.Test.Mocks { /// </summary> public Channel Channel { get; set; } - MessageProtections? IChannelBindingElement.ProcessOutgoingMessage(IProtocolMessage message) { - ITamperResistantProtocolMessage signedMessage = message as ITamperResistantProtocolMessage; + Task<MessageProtections?> IChannelBindingElement.ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { + var signedMessage = message as ITamperResistantProtocolMessage; if (signedMessage != null) { signedMessage.Signature = MessageSignature; - return MessageProtections.TamperProtection; + return MessageProtectionTasks.TamperProtection; } - return null; + return MessageProtectionTasks.Null; } - MessageProtections? IChannelBindingElement.ProcessIncomingMessage(IProtocolMessage message) { - ITamperResistantProtocolMessage signedMessage = message as ITamperResistantProtocolMessage; + Task<MessageProtections?> IChannelBindingElement.ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { + var signedMessage = message as ITamperResistantProtocolMessage; if (signedMessage != null) { if (signedMessage.Signature != MessageSignature) { throw new InvalidSignatureException(message); } - return MessageProtections.TamperProtection; + return MessageProtectionTasks.TamperProtection; } - return null; + return MessageProtectionTasks.Null; } #endregion diff --git a/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs b/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs index 2b3249f..35d7f1b 100644 --- a/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs +++ b/src/DotNetOpenAuth.Test/Mocks/MockTransformationBindingElement.cs @@ -9,11 +9,14 @@ namespace DotNetOpenAuth.Test.Mocks { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using NUnit.Framework; internal class MockTransformationBindingElement : IChannelBindingElement { - private string transform; + private readonly string transform; internal MockTransformationBindingElement(string transform) { if (transform == null) { @@ -34,25 +37,25 @@ namespace DotNetOpenAuth.Test.Mocks { /// </summary> public Channel Channel { get; set; } - MessageProtections? IChannelBindingElement.ProcessOutgoingMessage(IProtocolMessage message) { + Task<MessageProtections?> IChannelBindingElement.ProcessOutgoingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var testMessage = message as TestMessage; if (testMessage != null) { testMessage.Name = this.transform + testMessage.Name; - return MessageProtections.None; + return MessageProtectionTasks.None; } - return null; + return MessageProtectionTasks.Null; } - MessageProtections? IChannelBindingElement.ProcessIncomingMessage(IProtocolMessage message) { + Task<MessageProtections?> IChannelBindingElement.ProcessIncomingMessageAsync(IProtocolMessage message, CancellationToken cancellationToken) { var testMessage = message as TestMessage; if (testMessage != null) { StringAssert.StartsWith(this.transform, testMessage.Name); testMessage.Name = testMessage.Name.Substring(this.transform.Length); - return MessageProtections.None; + return MessageProtectionTasks.None; } - return null; + return MessageProtectionTasks.Null; } #endregion diff --git a/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs index 263f0fd..344598f 100644 --- a/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs @@ -7,15 +7,32 @@ namespace DotNetOpenAuth.Test.Mocks { using System; using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OpenId; /// <summary> /// A Channel derived type that passes null to the protected constructor. /// </summary> internal class TestBadChannel : Channel { - internal TestBadChannel(bool badConstructorParam) - : base(badConstructorParam ? null : new TestMessageFactory()) { + /// <summary> + /// Initializes a new instance of the <see cref="TestBadChannel" /> class. + /// </summary> + /// <param name="messageFactory">The message factory. Could be <see cref="TestMessageFactory"/></param> + /// <param name="bindingElements">The binding elements.</param> + /// <param name="hostFactories">The host factories.</param> + internal TestBadChannel(IMessageFactory messageFactory, IChannelBindingElement[] bindingElements, IHostFactories hostFactories) + : base(messageFactory, bindingElements, hostFactories) { + } + + /// <summary> + /// Initializes a new instance of the <see cref="TestBadChannel"/> class. + /// </summary> + internal TestBadChannel() + : this(new TestMessageFactory(), new IChannelBindingElement[0], new DefaultOpenIdHostFactories()) { } internal new void Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) { @@ -34,15 +51,15 @@ namespace DotNetOpenAuth.Test.Mocks { return base.Receive(fields, recipient); } - internal new IProtocolMessage ReadFromRequest(HttpRequestBase request) { - return base.ReadFromRequest(request); + internal new Task<IDirectedProtocolMessage> ReadFromRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + return base.ReadFromRequestAsync(request, cancellationToken); } - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + protected override Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken) { throw new NotImplementedException(); } - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) { throw new NotImplementedException(); } } diff --git a/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs b/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs index 1472231..5b318d5 100644 --- a/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs +++ b/src/DotNetOpenAuth.Test/Mocks/TestChannel.cs @@ -8,21 +8,26 @@ namespace DotNetOpenAuth.Test.Mocks { using System; using System.Collections.Generic; using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; + using DotNetOpenAuth.OpenId; internal class TestChannel : Channel { - internal TestChannel() - : this(new TestMessageFactory()) { + internal TestChannel(IHostFactories hostFactories = null) + : this(new TestMessageFactory(), new IChannelBindingElement[0], hostFactories ?? new DefaultOpenIdHostFactories()) { } - internal TestChannel(MessageDescriptionCollection messageDescriptions) - : this() { + internal TestChannel(MessageDescriptionCollection messageDescriptions, IHostFactories hostFactories = null) + : this(hostFactories) { this.MessageDescriptions = messageDescriptions; } - internal TestChannel(IMessageFactory messageTypeProvider, params IChannelBindingElement[] bindingElements) - : base(messageTypeProvider, bindingElements) { + internal TestChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements, IHostFactories hostFactories) + : base(messageTypeProvider, bindingElements, hostFactories) { } /// <summary> @@ -40,15 +45,15 @@ namespace DotNetOpenAuth.Test.Mocks { return base.Receive(fields, recipient); } - protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) { + protected override Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response, CancellationToken cancellationToken) { throw new NotImplementedException("ReadFromResponseInternal"); } - protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) { + protected override HttpRequestMessage CreateHttpRequest(IDirectedProtocolMessage request) { throw new NotImplementedException("CreateHttpRequest"); } - protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) { + protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) { throw new NotImplementedException("SendDirectMessageResponse"); } } diff --git a/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs b/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs deleted file mode 100644 index b38a3d8..0000000 --- a/src/DotNetOpenAuth.Test/Mocks/TestWebRequestHandler.cs +++ /dev/null @@ -1,116 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="TestWebRequestHandler.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.Mocks { - using System; - using System.IO; - using System.Net; - using System.Text; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth.ChannelElements; - - internal class TestWebRequestHandler : IDirectWebRequestHandler { - private Stream postEntity; - - /// <summary> - /// Gets or sets the callback used to provide the mock response for the mock request. - /// </summary> - internal Func<HttpWebRequest, IncomingWebResponse> Callback { get; set; } - - /// <summary> - /// Gets the stream that was written out as if on an HTTP request. - /// </summary> - internal Stream RequestEntityStream { - get { - if (this.postEntity == null) { - return null; - } - - Stream result = new MemoryStream(); - long originalPosition = this.postEntity.Position; - this.postEntity.Position = 0; - this.postEntity.CopyTo(result); - this.postEntity.Position = originalPosition; - result.Position = 0; - return result; - } - } - - /// <summary> - /// Gets the stream that was written out as if on an HTTP request as an ordinary string. - /// </summary> - internal string RequestEntityAsString { - get { - if (this.postEntity == null) { - return null; - } - - StreamReader reader = new StreamReader(this.RequestEntityStream); - return reader.ReadToEnd(); - } - } - - #region IWebRequestHandler Members - - public bool CanSupport(DirectWebRequestOptions options) { - return true; - } - - /// <summary> - /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param> - /// <returns> - /// The writer the caller should write out the entity data to. - /// </returns> - public Stream GetRequestStream(HttpWebRequest request) { - return this.GetRequestStream(request, DirectWebRequestOptions.None); - } - - public Stream GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) { - this.postEntity = new MemoryStream(); - return this.postEntity; - } - - /// <summary> - /// Processes an <see cref="HttpWebRequest"/> and converts the - /// <see cref="HttpWebResponse"/> to a <see cref="Response"/> instance. - /// </summary> - /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param> - /// <returns> - /// An instance of <see cref="Response"/> describing the response. - /// </returns> - public IncomingWebResponse GetResponse(HttpWebRequest request) { - return this.GetResponse(request, DirectWebRequestOptions.None); - } - - public IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options) { - if (this.Callback == null) { - throw new InvalidOperationException("Set the Callback property first."); - } - - return this.Callback(request); - } - - #endregion - - #region IDirectSslWebRequestHandler Members - - public Stream GetRequestStream(HttpWebRequest request, bool requireSsl) { - ErrorUtilities.VerifyProtocol(!requireSsl || request.RequestUri.Scheme == Uri.UriSchemeHttps, "disallowed request"); - return this.GetRequestStream(request); - } - - public IncomingWebResponse GetResponse(HttpWebRequest request, bool requireSsl) { - ErrorUtilities.VerifyProtocol(!requireSsl || request.RequestUri.Scheme == Uri.UriSchemeHttps, "disallowed request"); - var result = this.GetResponse(request); - ErrorUtilities.VerifyProtocol(!requireSsl || result.FinalUri.Scheme == Uri.UriSchemeHttps, "disallowed request"); - return result; - } - - #endregion - } -} diff --git a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs index a295732..c7b2bfa 100644 --- a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs +++ b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs @@ -8,6 +8,9 @@ namespace DotNetOpenAuth.Test.OAuth { using System; using System.IO; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; @@ -17,50 +20,76 @@ namespace DotNetOpenAuth.Test.OAuth { [TestFixture] public class AppendixScenarios : TestBase { [Test] - public void SpecAppendixAExample() { - ServiceProviderDescription serviceDescription = new ServiceProviderDescription() { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/request_token", HttpDeliveryMethods.PostRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://photos.example.net/authorize", HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/access_token", HttpDeliveryMethods.PostRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { - new PlaintextSigningBindingElement(), - new HmacSha1SigningBindingElement(), - }, + public async Task SpecAppendixAExample() { + var serviceDescription = new ServiceProviderDescription( + "https://photos.example.net/request_token", + "http://photos.example.net/authorize", + "https://photos.example.net/access_token"); + var serviceHostDescription = new ServiceProviderHostDescription { + RequestTokenEndpoint = new MessageReceivingEndpoint(serviceDescription.TemporaryCredentialsRequestEndpoint, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), + UserAuthorizationEndpoint = new MessageReceivingEndpoint(serviceDescription.ResourceOwnerAuthorizationEndpoint, HttpDeliveryMethods.GetRequest), + AccessTokenEndpoint = new MessageReceivingEndpoint(serviceDescription.TokenRequestEndpoint, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement(), }, }; - MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); - ConsumerDescription consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44"); + var accessPhotoEndpoint = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original"); + var consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44"); - OAuthCoordinator coordinator = new OAuthCoordinator( - consumerDescription, - serviceDescription, - consumer => { - consumer.Channel.PrepareResponse(consumer.PrepareRequestUserAuthorization(new Uri("http://printer.example.com/request_token_ready"), null, null)); // .Send() dropped because this is just a simulation - string accessToken = consumer.ProcessUserAuthorization().AccessToken; - var photoRequest = consumer.CreateAuthorizingMessage(accessPhotoEndpoint, accessToken); - OutgoingWebResponse protectedPhoto = ((CoordinatingOAuthConsumerChannel)consumer.Channel).RequestProtectedResource(photoRequest); - Assert.IsNotNull(protectedPhoto); - Assert.AreEqual(HttpStatusCode.OK, protectedPhoto.Status); - Assert.AreEqual("image/jpeg", protectedPhoto.Headers[HttpResponseHeader.ContentType]); - Assert.AreNotEqual(0, protectedPhoto.ResponseStream.Length); - }, - sp => { - var requestTokenMessage = sp.ReadTokenRequest(); - sp.Channel.PrepareResponse(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage)); // .Send() dropped because this is just a simulation - var authRequest = sp.ReadAuthorizationRequest(); + var tokenManager = new InMemoryTokenManager(); + tokenManager.AddConsumer(consumerDescription); + var sp = new ServiceProvider(serviceHostDescription, tokenManager); + + Handle(serviceDescription.TemporaryCredentialsRequestEndpoint).By( + async (request, ct) => { + var requestTokenMessage = await sp.ReadTokenRequestAsync(request, ct); + return await sp.Channel.PrepareResponseAsync(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage)); + }); + Handle(serviceDescription.ResourceOwnerAuthorizationEndpoint).By( + async (request, ct) => { + var authRequest = await sp.ReadAuthorizationRequestAsync(request, ct); ((InMemoryTokenManager)sp.TokenManager).AuthorizeRequestToken(authRequest.RequestToken); - sp.Channel.PrepareResponse(sp.PrepareAuthorizationResponse(authRequest)); // .Send() dropped because this is just a simulation - var accessRequest = sp.ReadAccessTokenRequest(); - sp.Channel.PrepareResponse(sp.PrepareAccessTokenMessage(accessRequest)); // .Send() dropped because this is just a simulation - string accessToken = sp.ReadProtectedResourceAuthorization().AccessToken; - ((CoordinatingOAuthServiceProviderChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse { - ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }), - Headers = new WebHeaderCollection { - { HttpResponseHeader.ContentType, "image/jpeg" }, - }, - }); + return await sp.Channel.PrepareResponseAsync(sp.PrepareAuthorizationResponse(authRequest)); + }); + Handle(serviceDescription.TokenRequestEndpoint).By( + async (request, ct) => { + var accessRequest = await sp.ReadAccessTokenRequestAsync(request, ct); + return await sp.Channel.PrepareResponseAsync(sp.PrepareAccessTokenMessage(accessRequest), ct); }); + Handle(accessPhotoEndpoint).By( + async (request, ct) => { + string accessToken = (await sp.ReadProtectedResourceAuthorizationAsync(request)).AccessToken; + Assert.That(accessToken, Is.Not.Null.And.Not.Empty); + var responseMessage = new HttpResponseMessage { Content = new ByteArrayContent(new byte[] { 0x33, 0x66 }), }; + responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); + return responseMessage; + }); + + var consumer = new Consumer( + consumerDescription.ConsumerKey, + consumerDescription.ConsumerSecret, + serviceDescription, + new MemoryTemporaryCredentialStorage()); + consumer.HostFactories = this.HostFactories; + var authorizeUrl = await consumer.RequestUserAuthorizationAsync(new Uri("http://printer.example.com/request_token_ready")); + Uri authorizeResponseUri; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(authorizeUrl)) { + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); + authorizeResponseUri = response.Headers.Location; + } + } + + var accessTokenResponse = await consumer.ProcessUserAuthorizationAsync(authorizeResponseUri); + Assert.That(accessTokenResponse, Is.Not.Null); - coordinator.Run(); + using (var authorizingClient = consumer.CreateHttpClient(accessTokenResponse.AccessToken)) { + using (var protectedPhoto = await authorizingClient.GetAsync(accessPhotoEndpoint)) { + Assert.That(protectedPhoto, Is.Not.Null); + protectedPhoto.EnsureSuccessStatusCode(); + Assert.That("image/jpeg", Is.EqualTo(protectedPhoto.Content.Headers.ContentType.MediaType)); + Assert.That(protectedPhoto.Content.Headers.ContentLength, Is.Not.EqualTo(0)); + } + } } } } diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs index 49260eb..e436143 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs @@ -5,6 +5,8 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OAuth.ChannelElements { + using System.Net.Http; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth; @@ -33,7 +35,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { ((ITamperResistantOAuthMessage)message).ConsumerSecret = "ExJXsYl7Or8OfK98"; ((ITamperResistantOAuthMessage)message).TokenSecret = "b197333b-470a-43b3-bcd7-49d6d2229c4c"; var signedMessage = (ITamperResistantOAuthMessage)message; - signedMessage.HttpMethod = "GET"; + signedMessage.HttpMethod = HttpMethod.Get; signedMessage.SignatureMethod = "HMAC-SHA1"; MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(message); dictionary["oauth_timestamp"] = "1353545248"; diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs index b081038..fdf652c 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs @@ -10,7 +10,10 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { using System.Collections.Specialized; using System.IO; using System.Net; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Xml; using DotNetOpenAuth.Messaging; @@ -24,41 +27,32 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { [TestFixture] public class OAuthChannelTests : TestBase { private OAuthChannel channel; - private TestWebRequestHandler webRequestHandler; private SigningBindingElementBase signingElement; private INonceStore nonceStore; private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.ServiceProvider.SecuritySettings.CreateSecuritySettings(); - private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings(); [SetUp] public override void SetUp() { base.SetUp(); - this.webRequestHandler = new TestWebRequestHandler(); this.signingElement = new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()); this.nonceStore = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge); - this.channel = new OAuthServiceProviderChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory()); - this.channel.WebRequestHandler = this.webRequestHandler; + this.channel = new OAuthServiceProviderChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory(), this.HostFactories); } [Test, ExpectedException(typeof(ArgumentException))] public void CtorNullSigner() { - new OAuthConsumerChannel(null, this.nonceStore, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory()); + new OAuthServiceProviderChannel(null, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory()); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CtorNullStore() { - new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), null, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory()); + new OAuthServiceProviderChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), null, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory()); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CtorNullTokenManager() { - new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, null, this.consumerSecuritySettings, new TestMessageFactory()); - } - - [Test] - public void CtorSimpleConsumer() { - new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IConsumerTokenManager)new InMemoryTokenManager(), this.consumerSecuritySettings); + new OAuthServiceProviderChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, null, this.serviceProviderSecuritySettings, new TestMessageFactory()); } [Test] @@ -67,8 +61,8 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { } [Test] - public void ReadFromRequestAuthorization() { - this.ParameterizedReceiveTest(HttpDeliveryMethods.AuthorizationHeaderRequest); + public async Task ReadFromRequestAuthorization() { + await this.ParameterizedReceiveTestAsync(HttpDeliveryMethods.AuthorizationHeaderRequest); } /// <summary> @@ -76,7 +70,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { /// from the Authorization header, the query string and the entity form data. /// </summary> [Test] - public void ReadFromRequestAuthorizationScattered() { + public async Task ReadFromRequestAuthorizationScattered() { // Start by creating a standard POST HTTP request. var postedFields = new Dictionary<string, string> { { "age", "15" }, @@ -97,7 +91,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { var requestInfo = new HttpRequestInfo("POST", builder.Uri, form: postedFields.ToNameValueCollection(), headers: headers); - IDirectedProtocolMessage requestMessage = this.channel.ReadFromRequest(requestInfo); + IDirectedProtocolMessage requestMessage = await this.channel.ReadFromRequestAsync(requestInfo.AsHttpRequestMessage(), CancellationToken.None); Assert.IsNotNull(requestMessage); Assert.IsInstanceOf<TestMessage>(requestMessage); @@ -108,36 +102,35 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { } [Test] - public void ReadFromRequestForm() { - this.ParameterizedReceiveTest(HttpDeliveryMethods.PostRequest); + public async Task ReadFromRequestForm() { + await this.ParameterizedReceiveTestAsync(HttpDeliveryMethods.PostRequest); } [Test] - public void ReadFromRequestQueryString() { - this.ParameterizedReceiveTest(HttpDeliveryMethods.GetRequest); + public async Task ReadFromRequestQueryString() { + await this.ParameterizedReceiveTestAsync(HttpDeliveryMethods.GetRequest); } [Test] - public void SendDirectMessageResponse() { + public async Task SendDirectMessageResponse() { IProtocolMessage message = new TestDirectedMessage { Age = 15, Name = "Andrew", Location = new Uri("http://hostb/pathB"), }; - OutgoingWebResponse response = this.channel.PrepareResponse(message); - Assert.AreSame(message, response.OriginalMessage); - Assert.AreEqual(HttpStatusCode.OK, response.Status); - Assert.AreEqual(2, response.Headers.Count); + var response = await this.channel.PrepareResponseAsync(message); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(Channel.HttpFormUrlEncodedContentType.MediaType, response.Content.Headers.ContentType.MediaType); - NameValueCollection body = HttpUtility.ParseQueryString(response.Body); + NameValueCollection body = HttpUtility.ParseQueryString(await response.Content.ReadAsStringAsync()); Assert.AreEqual("15", body["age"]); Assert.AreEqual("Andrew", body["Name"]); Assert.AreEqual("http://hostb/pathB", body["Location"]); } [Test] - public void ReadFromResponse() { + public async Task ReadFromResponse() { var fields = new Dictionary<string, string> { { "age", "15" }, { "Name", "Andrew" }, @@ -150,7 +143,9 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { writer.Write(MessagingUtilities.CreateQueryString(fields)); writer.Flush(); ms.Seek(0, SeekOrigin.Begin); - IDictionary<string, string> deserializedFields = this.channel.ReadFromResponseCoreTestHook(new CachedDirectWebResponse { CachedResponseStream = ms }); + IDictionary<string, string> deserializedFields = await this.channel.ReadFromResponseCoreAsyncTestHook( + new HttpResponseMessage { Content = new StreamContent(ms) }, + CancellationToken.None); Assert.AreEqual(fields.Count, deserializedFields.Count); foreach (string key in fields.Keys) { Assert.AreEqual(fields[key], deserializedFields[key]); @@ -158,34 +153,34 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { } [Test, ExpectedException(typeof(ArgumentNullException))] - public void RequestNull() { - this.channel.Request(null); + public async Task RequestNull() { + await this.channel.RequestAsync(null, CancellationToken.None); } [Test, ExpectedException(typeof(ArgumentException))] - public void RequestNullRecipient() { + public async Task RequestNullRecipient() { IDirectedProtocolMessage message = new TestDirectedMessage(MessageTransport.Direct); - this.channel.Request(message); + await this.channel.RequestAsync(message, CancellationToken.None); } [Test, ExpectedException(typeof(NotSupportedException))] - public void RequestBadPreferredScheme() { + public async Task RequestBadPreferredScheme() { TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Direct); message.Recipient = new Uri("http://localtest"); message.HttpMethods = HttpDeliveryMethods.None; - this.channel.Request(message); + await this.channel.RequestAsync(message, CancellationToken.None); } [Test] - public void RequestUsingAuthorizationHeader() { - this.ParameterizedRequestTest(HttpDeliveryMethods.AuthorizationHeaderRequest); + public async Task RequestUsingAuthorizationHeader() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.AuthorizationHeaderRequest); } /// <summary> /// Verifies that message parts can be distributed to the query, form, and Authorization header. /// </summary> [Test] - public void RequestUsingAuthorizationHeaderScattered() { + public async Task RequestUsingAuthorizationHeaderScattered() { TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) { Age = 15, Name = "Andrew", @@ -201,9 +196,9 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { request.Recipient = new Uri("http://localhost/?appearinquery=queryish"); request.HttpMethods = HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest; - HttpWebRequest webRequest = this.channel.InitializeRequest(request); + var webRequest = await this.channel.InitializeRequestAsync(request, CancellationToken.None); Assert.IsNotNull(webRequest); - Assert.AreEqual("POST", webRequest.Method); + Assert.AreEqual(HttpMethod.Post, webRequest.Method); Assert.AreEqual(request.Recipient, webRequest.RequestUri); var declaredParts = new Dictionary<string, string> { @@ -213,23 +208,23 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, }; - Assert.AreEqual(CreateAuthorizationHeader(declaredParts), webRequest.Headers[HttpRequestHeader.Authorization]); - Assert.AreEqual("appearinform=formish", this.webRequestHandler.RequestEntityAsString); + Assert.AreEqual(CreateAuthorizationHeader(declaredParts), webRequest.Headers.Authorization.ToString()); + Assert.AreEqual("appearinform=formish", await webRequest.Content.ReadAsStringAsync()); } [Test] - public void RequestUsingGet() { - this.ParameterizedRequestTest(HttpDeliveryMethods.GetRequest); + public async Task RequestUsingGet() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.GetRequest); } [Test] - public void RequestUsingPost() { - this.ParameterizedRequestTest(HttpDeliveryMethods.PostRequest); + public async Task RequestUsingPost() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.PostRequest); } [Test] - public void RequestUsingHead() { - this.ParameterizedRequestTest(HttpDeliveryMethods.HeadRequest); + public async Task RequestUsingHead() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.HeadRequest); } /// <summary> @@ -238,14 +233,14 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { [Test] public void SendDirectMessageResponseHonorsHttpStatusCodes() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); - OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message); - Assert.AreEqual(HttpStatusCode.OK, directResponse.Status); + var directResponse = this.channel.PrepareDirectResponseTestHook(message); + Assert.AreEqual(HttpStatusCode.OK, directResponse.StatusCode); var httpMessage = new TestDirectResponseMessageWithHttpStatus(); MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, httpMessage); httpMessage.HttpStatusCode = HttpStatusCode.NotAcceptable; directResponse = this.channel.PrepareDirectResponseTestHook(httpMessage); - Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.Status); + Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.StatusCode); } private static string CreateAuthorizationHeader(IDictionary<string, string> fields) { @@ -296,8 +291,8 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { return new HttpRequestInfo(request.Method, request.RequestUri, request.Headers, postEntity); } - private void ParameterizedRequestTest(HttpDeliveryMethods scheme) { - TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) { + private async Task ParameterizedRequestTestAsync(HttpDeliveryMethods scheme) { + var request = new TestDirectedMessage(MessageTransport.Direct) { Age = 15, Name = "Andrew", Location = new Uri("http://hostb/pathB"), @@ -306,30 +301,29 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { HttpMethods = scheme, }; - CachedDirectWebResponse rawResponse = null; - this.webRequestHandler.Callback = (req) => { - Assert.IsNotNull(req); - HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream); - Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), reqInfo.HttpMethod); - var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage; - Assert.IsNotNull(incomingMessage); - Assert.AreEqual(request.Age, incomingMessage.Age); - Assert.AreEqual(request.Name, incomingMessage.Name); - Assert.AreEqual(request.Location, incomingMessage.Location); - Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp); - - var responseFields = new Dictionary<string, string> { - { "age", request.Age.ToString() }, - { "Name", request.Name }, - { "Location", request.Location.AbsoluteUri }, - { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, - }; - rawResponse = new CachedDirectWebResponse(); - rawResponse.SetResponse(MessagingUtilities.CreateQueryString(responseFields)); - return rawResponse; - }; - - IProtocolMessage response = this.channel.Request(request); + Handle(request.Recipient).By( + async (req, ct) => { + Assert.IsNotNull(req); + Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), req.Method); + var incomingMessage = (await this.channel.ReadFromRequestAsync(req, CancellationToken.None)) as TestMessage; + Assert.IsNotNull(incomingMessage); + Assert.AreEqual(request.Age, incomingMessage.Age); + Assert.AreEqual(request.Name, incomingMessage.Name); + Assert.AreEqual(request.Location, incomingMessage.Location); + Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp); + + var responseFields = new Dictionary<string, string> { + { "age", request.Age.ToString() }, + { "Name", request.Name }, + { "Location", request.Location.AbsoluteUri }, + { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, + }; + var rawResponse = new HttpResponseMessage(); + rawResponse.Content = new StringContent(MessagingUtilities.CreateQueryString(responseFields)); + return rawResponse; + }); + + IProtocolMessage response = await this.channel.RequestAsync(request, CancellationToken.None); Assert.IsNotNull(response); Assert.IsInstanceOf<TestMessage>(response); TestMessage responseMessage = (TestMessage)response; @@ -338,7 +332,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { Assert.AreEqual(request.Location, responseMessage.Location); } - private void ParameterizedReceiveTest(HttpDeliveryMethods scheme) { + private async Task ParameterizedReceiveTestAsync(HttpDeliveryMethods scheme) { var fields = new Dictionary<string, string> { { "age", "15" }, { "Name", "Andrew" }, @@ -346,7 +340,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) }, { "realm", "someValue" }, }; - IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields)); + IProtocolMessage requestMessage = await this.channel.ReadFromRequestAsync(CreateHttpRequestInfo(scheme, fields).AsHttpRequestMessage(), CancellationToken.None); Assert.IsNotNull(requestMessage); Assert.IsInstanceOf<TestMessage>(requestMessage); TestMessage testMessage = (TestMessage)requestMessage; diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs index b3869e7..b8d4f2b 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs @@ -5,6 +5,9 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OAuth.ChannelElements { + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; @@ -15,20 +18,20 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { [TestFixture] public class PlaintextSigningBindingElementTest { [Test] - public void HttpsSignatureGeneration() { + public async Task HttpsSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version); message.ConsumerSecret = "cs"; message.TokenSecret = "ts"; - Assert.IsNotNull(target.ProcessOutgoingMessage(message)); + Assert.IsNotNull(await target.ProcessOutgoingMessageAsync(message, CancellationToken.None)); Assert.AreEqual("PLAINTEXT", message.SignatureMethod); Assert.AreEqual("cs&ts", message.Signature); } [Test] - public void HttpsSignatureVerification() { + public async Task HttpsSignatureVerification() { MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperProtectionChannelBindingElement target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); @@ -37,11 +40,11 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; message.SignatureMethod = "PLAINTEXT"; message.Signature = "cs&ts"; - Assert.IsNotNull(target.ProcessIncomingMessage(message)); + Assert.IsNotNull(target.ProcessIncomingMessageAsync(message, CancellationToken.None)); } [Test] - public void HttpsSignatureVerificationNotApplicable() { + public async Task HttpsSignatureVerificationNotApplicable() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); @@ -50,11 +53,11 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; message.SignatureMethod = "ANOTHERALGORITHM"; message.Signature = "somethingelse"; - Assert.AreEqual(MessageProtections.None, target.ProcessIncomingMessage(message), "PLAINTEXT binding element should opt-out where it doesn't understand."); + Assert.AreEqual(MessageProtections.None, await target.ProcessIncomingMessageAsync(message, CancellationToken.None), "PLAINTEXT binding element should opt-out where it doesn't understand."); } [Test] - public void HttpSignatureGeneration() { + public async Task HttpSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); @@ -63,13 +66,13 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; // Since this is (non-encrypted) HTTP, so the plain text signer should not be used - Assert.IsNull(target.ProcessOutgoingMessage(message)); + Assert.IsNull(await target.ProcessOutgoingMessageAsync(message, CancellationToken.None)); Assert.IsNull(message.SignatureMethod); Assert.IsNull(message.Signature); } [Test] - public void HttpSignatureVerification() { + public async Task HttpSignatureVerification() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); @@ -78,7 +81,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; message.SignatureMethod = "PLAINTEXT"; message.Signature = "cs%26ts"; - Assert.IsNull(target.ProcessIncomingMessage(message), "PLAINTEXT signature binding element should refuse to participate in non-encrypted messages."); + Assert.IsNull(await target.ProcessIncomingMessageAsync(message, CancellationToken.None), "PLAINTEXT signature binding element should refuse to participate in non-encrypted messages."); } } } diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs index 490399c..e356c64 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { using System.Collections.Generic; + using System.Net.Http; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth; @@ -80,7 +82,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.AccessToken = "tokenpublic"; var signedMessage = (ITamperResistantOAuthMessage)message; - signedMessage.HttpMethod = "GET"; + signedMessage.HttpMethod = HttpMethod.Get; signedMessage.SignatureMethod = "HMAC-SHA1"; MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(message); @@ -115,7 +117,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.ConsumerKey = "nerdbank.org"; ((ITamperResistantOAuthMessage)message).ConsumerSecret = "nerdbanksecret"; var signedMessage = (ITamperResistantOAuthMessage)message; - signedMessage.HttpMethod = "GET"; + signedMessage.HttpMethod = HttpMethod.Get; signedMessage.SignatureMethod = "HMAC-SHA1"; MessageDictionary dictionary = messageDescriptions.GetAccessor(message); dictionary["oauth_timestamp"] = "1222665749"; diff --git a/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs b/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs index 74752f8..5c25d30 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs @@ -5,6 +5,8 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OAuth { + using DotNetOpenAuth.OAuth; + /// <summary> /// Information necessary to initialize a <see cref="Consumer"/>, /// and to tell a <see cref="ServiceProvider"/> about it. diff --git a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs deleted file mode 100644 index 21c1775..0000000 --- a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs +++ /dev/null @@ -1,71 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OAuthCoordinator.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.OAuth { - using System; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Bindings; - using DotNetOpenAuth.OAuth; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.Test.Mocks; - using Validation; - - /// <summary> - /// Runs a Consumer and Service Provider simultaneously so they can interact in a full simulation. - /// </summary> - internal class OAuthCoordinator : CoordinatorBase<WebConsumer, ServiceProvider> { - private ConsumerDescription consumerDescription; - private ServiceProviderDescription serviceDescription; - private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.ServiceProvider.SecuritySettings.CreateSecuritySettings(); - private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings(); - - /// <summary>Initializes a new instance of the <see cref="OAuthCoordinator"/> class.</summary> - /// <param name="consumerDescription">The description of the consumer.</param> - /// <param name="serviceDescription">The service description that will be used to construct the Consumer and ServiceProvider objects.</param> - /// <param name="consumerAction">The code path of the Consumer.</param> - /// <param name="serviceProviderAction">The code path of the Service Provider.</param> - internal OAuthCoordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action<WebConsumer> consumerAction, Action<ServiceProvider> serviceProviderAction) - : base(consumerAction, serviceProviderAction) { - Requires.NotNull(consumerDescription, "consumerDescription"); - Requires.NotNull(serviceDescription, "serviceDescription"); - - this.consumerDescription = consumerDescription; - this.serviceDescription = serviceDescription; - } - - /// <summary> - /// Starts the simulation. - /// </summary> - internal override void Run() { - // Clone the template signing binding element. - var signingElement = this.serviceDescription.CreateTamperProtectionElement(); - var consumerSigningElement = signingElement.Clone(); - var spSigningElement = signingElement.Clone(); - - // Prepare token managers - InMemoryTokenManager consumerTokenManager = new InMemoryTokenManager(); - InMemoryTokenManager serviceTokenManager = new InMemoryTokenManager(); - consumerTokenManager.AddConsumer(this.consumerDescription); - serviceTokenManager.AddConsumer(this.consumerDescription); - - // Prepare channels that will pass messages directly back and forth. - var consumerChannel = new CoordinatingOAuthConsumerChannel(consumerSigningElement, (IConsumerTokenManager)consumerTokenManager, this.consumerSecuritySettings); - var serviceProviderChannel = new CoordinatingOAuthServiceProviderChannel(spSigningElement, (IServiceProviderTokenManager)serviceTokenManager, this.serviceProviderSecuritySettings); - consumerChannel.RemoteChannel = serviceProviderChannel; - serviceProviderChannel.RemoteChannel = consumerChannel; - - // Prepare the Consumer and Service Provider objects - WebConsumer consumer = new WebConsumer(this.serviceDescription, consumerTokenManager) { - OAuthChannel = consumerChannel, - }; - ServiceProvider serviceProvider = new ServiceProvider(this.serviceDescription, serviceTokenManager, new NonceMemoryStore()) { - OAuthChannel = serviceProviderChannel, - }; - - this.RunCore(consumer, serviceProvider); - } - } -} diff --git a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs index cdc8de5..3da3112 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs @@ -11,7 +11,7 @@ namespace DotNetOpenAuth.Test.OAuth { using NUnit.Framework; /// <summary> - /// Tests for the <see cref="ServiceProviderEndpoints"/> class. + /// Tests for the <see cref="ServiceProviderHostDescription"/> class. /// </summary> [TestFixture] public class ServiceProviderDescriptionTests : TestBase { @@ -20,8 +20,8 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test] public void UserAuthorizationUriTest() { - ServiceProviderDescription target = new ServiceProviderDescription(); - MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest); + var target = new ServiceProviderHostDescription(); + var expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.UserAuthorizationEndpoint = expected; actual = target.UserAuthorizationEndpoint; @@ -36,8 +36,8 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test] public void RequestTokenUriTest() { - var target = new ServiceProviderDescription(); - MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/requesttoken", HttpDeliveryMethods.GetRequest); + var target = new ServiceProviderHostDescription(); + var expected = new MessageReceivingEndpoint("http://localhost/requesttoken", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.RequestTokenEndpoint = expected; actual = target.RequestTokenEndpoint; @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test, ExpectedException(typeof(ArgumentException))] public void RequestTokenUriWithOAuthParametersTest() { - var target = new ServiceProviderDescription(); + var target = new ServiceProviderHostDescription(); target.RequestTokenEndpoint = new MessageReceivingEndpoint("http://localhost/requesttoken?oauth_token=something", HttpDeliveryMethods.GetRequest); } @@ -62,7 +62,7 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test] public void AccessTokenUriTest() { - var target = new ServiceProviderDescription(); + var target = new ServiceProviderHostDescription(); MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/accesstoken", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.AccessTokenEndpoint = expected; diff --git a/src/DotNetOpenAuth.Test/OAuth2/AuthorizationServerTests.cs b/src/DotNetOpenAuth.Test/OAuth2/AuthorizationServerTests.cs index e8f7172..8ec25b0 100644 --- a/src/DotNetOpenAuth.Test/OAuth2/AuthorizationServerTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth2/AuthorizationServerTests.cs @@ -8,7 +8,10 @@ namespace DotNetOpenAuth.Test.OAuth2 { using System; using System.Collections.Generic; using System.Linq; + using System.Net; + using System.Net.Http; using System.Text; + using System.Threading; using System.Threading.Tasks; using DotNetOpenAuth.OAuth2; using DotNetOpenAuth.OAuth2.ChannelElements; @@ -25,59 +28,66 @@ namespace DotNetOpenAuth.Test.OAuth2 { /// Verifies that authorization server responds with an appropriate error response. /// </summary> [Test] - public void ErrorResponseTest() { - var coordinator = new OAuth2Coordinator<UserAgentClient>( - AuthorizationServerDescription, - AuthorizationServerMock, - new UserAgentClient(AuthorizationServerDescription), - client => { - var request = new AccessTokenAuthorizationCodeRequestC(AuthorizationServerDescription) { ClientIdentifier = ClientId, ClientSecret = ClientSecret, AuthorizationCode = "foo" }; - - var response = client.Channel.Request<AccessTokenFailedResponse>(request); - Assert.That(response.Error, Is.Not.Null.And.Not.Empty); - Assert.That(response.Error, Is.EqualTo(Protocol.AccessTokenRequestErrorCodes.InvalidRequest)); - }, - server => { - server.HandleTokenRequest().Respond(); + public async Task ErrorResponseTest() { + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + var request = new AccessTokenAuthorizationCodeRequestC(AuthorizationServerDescription) { ClientIdentifier = ClientId, ClientSecret = ClientSecret, AuthorizationCode = "foo" }; + var client = new UserAgentClient(AuthorizationServerDescription, hostFactories: this.HostFactories); + var response = await client.Channel.RequestAsync<AccessTokenFailedResponse>(request, CancellationToken.None); + Assert.That(response.Error, Is.Not.Null.And.Not.Empty); + Assert.That(response.Error, Is.EqualTo(Protocol.AccessTokenRequestErrorCodes.InvalidRequest)); } [Test] - public void DecodeRefreshToken() { + public async Task DecodeRefreshToken() { var refreshTokenSource = new TaskCompletionSource<string>(); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - AuthorizationServerMock, - new WebServerClient(AuthorizationServerDescription), - client => { - try { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - client.PrepareRequestUserAuthorization(authState).Respond(); - var result = client.ProcessUserAuthorization(); - Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); - refreshTokenSource.SetResult(result.RefreshToken); - } catch { - refreshTokenSource.TrySetCanceled(); - } - }, - server => { - var request = server.ReadAuthorizationRequest(); + Handle(AuthorizationServerDescription.AuthorizationEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + var request = await server.ReadAuthorizationRequestAsync(req, ct); Assert.That(request, Is.Not.Null); - server.ApproveAuthorizationRequest(request, ResourceOwnerUsername); - server.HandleTokenRequest().Respond(); + var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername); + return await server.Channel.PrepareResponseAsync(response); + }); + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + var response = await server.HandleTokenRequestAsync(req, ct); var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result); Assert.That(authorization, Is.Not.Null); Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername)); + return response; }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription); + try { + var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, }; + var authRedirectResponse = await client.PrepareRequestUserAuthorizationAsync(authState); + this.HostFactories.CookieContainer.SetCookies(authRedirectResponse, ClientCallback); + Uri authCompleteUri; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(authRedirectResponse.Headers.Location)) { + response.EnsureSuccessStatusCode(); + authCompleteUri = response.Headers.Location; + } + } + + var authCompleteRequest = new HttpRequestMessage(HttpMethod.Get, authCompleteUri); + this.HostFactories.CookieContainer.ApplyCookies(authCompleteRequest); + var result = await client.ProcessUserAuthorizationAsync(authCompleteRequest); + Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); + refreshTokenSource.SetResult(result.RefreshToken); + } catch { + refreshTokenSource.TrySetCanceled(); + } } [Test] - public void ResourceOwnerScopeOverride() { + public async Task ResourceOwnerScopeOverride() { var clientRequestedScopes = new[] { "scope1", "scope2" }; var serverOverriddenScopes = new[] { "scope1", "differentScope" }; var authServerMock = CreateAuthorizationServerMock(); @@ -89,25 +99,20 @@ namespace DotNetOpenAuth.Test.OAuth2 { response.ApprovedScope.UnionWith(serverOverriddenScopes); return response; }); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServerMock.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - var result = client.ExchangeUserCredentialForToken(ResourceOwnerUsername, ResourceOwnerPassword, clientRequestedScopes); - Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes)); - }, - server => { - server.HandleTokenRequest().Respond(); + + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServerMock.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription, hostFactories: this.HostFactories); + var result = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, clientRequestedScopes); + Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes)); } [Test] - public void CreateAccessTokenSeesAuthorizingUserResourceOwnerGrant() { + public async Task CreateAccessTokenSeesAuthorizingUserResourceOwnerGrant() { var authServerMock = CreateAuthorizationServerMock(); authServerMock .Setup(a => a.CheckAuthorizeResourceOwnerCredentialGrant(ResourceOwnerUsername, ResourceOwnerPassword, It.IsAny<IAccessTokenRequest>())) @@ -116,25 +121,20 @@ namespace DotNetOpenAuth.Test.OAuth2 { Assert.That(req.UserName, Is.EqualTo(ResourceOwnerUsername)); return response; }); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServerMock.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - var result = client.ExchangeUserCredentialForToken(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes); - Assert.That(result.AccessToken, Is.Not.Null); - }, - server => { - server.HandleTokenRequest().Respond(); + + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServerMock.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription, hostFactories: this.HostFactories); + var result = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes); + Assert.That(result.AccessToken, Is.Not.Null); } [Test] - public void CreateAccessTokenSeesAuthorizingUserClientCredentialGrant() { + public async Task CreateAccessTokenSeesAuthorizingUserClientCredentialGrant() { var authServerMock = CreateAuthorizationServerMock(); authServerMock .Setup(a => a.CheckAuthorizeClientCredentialsGrant(It.IsAny<IAccessTokenRequest>())) @@ -142,25 +142,20 @@ namespace DotNetOpenAuth.Test.OAuth2 { Assert.That(req.UserName, Is.Null); return new AutomatedAuthorizationCheckResponse(req, true); }); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServerMock.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - var result = client.GetClientAccessToken(TestScopes); - Assert.That(result.AccessToken, Is.Not.Null); - }, - server => { - server.HandleTokenRequest().Respond(); + + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServerMock.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var result = await client.GetClientAccessTokenAsync(TestScopes); + Assert.That(result.AccessToken, Is.Not.Null); } [Test] - public void CreateAccessTokenSeesAuthorizingUserAuthorizationCodeGrant() { + public async Task CreateAccessTokenSeesAuthorizingUserAuthorizationCodeGrant() { var authServerMock = CreateAuthorizationServerMock(); authServerMock .Setup(a => a.IsAuthorizationValid(It.IsAny<IAuthorizationDescription>())) @@ -168,30 +163,45 @@ namespace DotNetOpenAuth.Test.OAuth2 { Assert.That(req.User, Is.EqualTo(ResourceOwnerUsername)); return true; }); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServerMock.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - client.PrepareRequestUserAuthorization(authState).Respond(); - var result = client.ProcessUserAuthorization(); - Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); - }, - server => { - var request = server.ReadAuthorizationRequest(); + + Handle(AuthorizationServerDescription.AuthorizationEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServerMock.Object); + var request = await server.ReadAuthorizationRequestAsync(req, ct); Assert.That(request, Is.Not.Null); - server.ApproveAuthorizationRequest(request, ResourceOwnerUsername); - server.HandleTokenRequest().Respond(); + var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername); + return await server.Channel.PrepareResponseAsync(response); + }); + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServerMock.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var authState = new AuthorizationState(TestScopes) { + Callback = ClientCallback, + }; + var authRedirectResponse = await client.PrepareRequestUserAuthorizationAsync(authState); + this.HostFactories.CookieContainer.SetCookies(authRedirectResponse, ClientCallback); + Uri authCompleteUri; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(authRedirectResponse.Headers.Location)) { + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); + authCompleteUri = response.Headers.Location; + } + } + + var authCompleteRequest = new HttpRequestMessage(HttpMethod.Get, authCompleteUri); + this.HostFactories.CookieContainer.ApplyCookies(authCompleteRequest); + var result = await client.ProcessUserAuthorizationAsync(authCompleteRequest); + Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); } [Test] - public void ClientCredentialScopeOverride() { + public async Task ClientCredentialScopeOverride() { var clientRequestedScopes = new[] { "scope1", "scope2" }; var serverOverriddenScopes = new[] { "scope1", "differentScope" }; var authServerMock = CreateAuthorizationServerMock(); @@ -203,21 +213,17 @@ namespace DotNetOpenAuth.Test.OAuth2 { response.ApprovedScope.UnionWith(serverOverriddenScopes); return response; }); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServerMock.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - var result = client.GetClientAccessToken(clientRequestedScopes); - Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes)); - }, - server => { - server.HandleTokenRequest().Respond(); + + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServerMock.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var result = await client.GetClientAccessTokenAsync(clientRequestedScopes); + Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes)); } } } diff --git a/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs index 52b5371..810d830 100644 --- a/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs @@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.OAuth2 { var authServerChannel = new OAuth2AuthorizationServerChannel(new Mock<IAuthorizationServerHost>().Object, new Mock<ClientAuthenticationModule>().Object); this.authServerMessageFactory = authServerChannel.MessageFactoryTestHook; - var clientChannel = new OAuth2ClientChannel(); + var clientChannel = new OAuth2ClientChannel(null); this.clientMessageFactory = clientChannel.MessageFactoryTestHook; } diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2Coordinator.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2Coordinator.cs deleted file mode 100644 index eeda125..0000000 --- a/src/DotNetOpenAuth.Test/OAuth2/OAuth2Coordinator.cs +++ /dev/null @@ -1,74 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OAuth2Coordinator.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.OAuth2 { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Text; - using DotNetOpenAuth.OAuth2; - using DotNetOpenAuth.Test.Mocks; - using Validation; - - internal class OAuth2Coordinator<TClient> : CoordinatorBase<TClient, AuthorizationServer> - where TClient : ClientBase { - private readonly AuthorizationServerDescription serverDescription; - private readonly IAuthorizationServerHost authServerHost; - private readonly TClient client; - - internal OAuth2Coordinator( - AuthorizationServerDescription serverDescription, - IAuthorizationServerHost authServerHost, - TClient client, - Action<TClient> clientAction, - Action<AuthorizationServer> authServerAction) - : base(clientAction, authServerAction) { - Requires.NotNull(serverDescription, "serverDescription"); - Requires.NotNull(authServerHost, "authServerHost"); - Requires.NotNull(client, "client"); - - this.serverDescription = serverDescription; - this.authServerHost = authServerHost; - this.client = client; - - this.client.ClientIdentifier = OAuth2TestBase.ClientId; - this.client.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(OAuth2TestBase.ClientSecret); - } - - internal override void Run() { - var authServer = new AuthorizationServer(this.authServerHost); - - var rpCoordinatingChannel = new CoordinatingOAuth2ClientChannel(this.client.Channel, this.IncomingMessageFilter, this.OutgoingMessageFilter); - var opCoordinatingChannel = new CoordinatingOAuth2AuthServerChannel(authServer.Channel, this.IncomingMessageFilter, this.OutgoingMessageFilter); - rpCoordinatingChannel.RemoteChannel = opCoordinatingChannel; - opCoordinatingChannel.RemoteChannel = rpCoordinatingChannel; - - this.client.Channel = rpCoordinatingChannel; - authServer.Channel = opCoordinatingChannel; - - this.RunCore(this.client, authServer); - } - - private static Action<WebServerClient> WrapAction(Action<WebServerClient> action) { - Requires.NotNull(action, "action"); - - return client => { - action(client); - ((CoordinatingChannel)client.Channel).Close(); - }; - } - - private static Action<AuthorizationServer> WrapAction(Action<AuthorizationServer> action) { - Requires.NotNull(action, "action"); - - return authServer => { - action(authServer); - ((CoordinatingChannel)authServer.Channel).Close(); - }; - } - } -} diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs index 395b18c..f01b5b7 100644 --- a/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs +++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs @@ -37,10 +37,7 @@ namespace DotNetOpenAuth.Test.OAuth2 { TokenEndpoint = new Uri("https://authserver/token"), }; - protected static readonly IClientDescription ClientDescription = new ClientDescription( - ClientSecret, - ClientCallback, - ClientType.Confidential); + protected static readonly IClientDescription ClientDescription = new ClientDescription(ClientSecret, ClientCallback); protected static readonly IAuthorizationServerHost AuthorizationServerMock = CreateAuthorizationServerMock().Object; diff --git a/src/DotNetOpenAuth.Test/OAuth2/ResourceServerTests.cs b/src/DotNetOpenAuth.Test/OAuth2/ResourceServerTests.cs index 80a8392..c232450 100644 --- a/src/DotNetOpenAuth.Test/OAuth2/ResourceServerTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth2/ResourceServerTests.cs @@ -11,6 +11,8 @@ namespace DotNetOpenAuth.Test.OAuth2 { using System.Linq; using System.Security.Cryptography; using System.Text; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using DotNetOpenAuth.OAuth2.ChannelElements; @@ -28,7 +30,7 @@ namespace DotNetOpenAuth.Test.OAuth2 { { "Authorization", "Bearer " }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); - Assert.That(() => resourceServer.GetAccessToken(request), Throws.InstanceOf<ProtocolException>()); + Assert.That(() => resourceServer.GetAccessTokenAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf<ProtocolException>()); } [Test] @@ -39,7 +41,7 @@ namespace DotNetOpenAuth.Test.OAuth2 { { "Authorization", "Bearer " }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); - Assert.That(() => resourceServer.GetPrincipal(request), Throws.InstanceOf<ProtocolException>()); + Assert.That(() => resourceServer.GetPrincipalAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf<ProtocolException>()); } [Test] @@ -50,12 +52,12 @@ namespace DotNetOpenAuth.Test.OAuth2 { { "Authorization", "Bearer foobar" }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); - Assert.That(() => resourceServer.GetAccessToken(request), Throws.InstanceOf<ProtocolException>()); + Assert.That(() => resourceServer.GetAccessTokenAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf<ProtocolException>()); } [Test] - public void GetAccessTokenWithCorruptedToken() { - var accessToken = this.ObtainValidAccessToken(); + public async Task GetAccessTokenWithCorruptedToken() { + var accessToken = await this.ObtainValidAccessTokenAsync(); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); @@ -63,12 +65,12 @@ namespace DotNetOpenAuth.Test.OAuth2 { { "Authorization", "Bearer " + accessToken.Substring(0, accessToken.Length - 1) + "zzz" }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); - Assert.That(() => resourceServer.GetAccessToken(request), Throws.InstanceOf<ProtocolException>()); + Assert.That(() => resourceServer.GetAccessTokenAsync(request).GetAwaiter().GetResult(), Throws.InstanceOf<ProtocolException>()); } [Test] - public void GetAccessTokenWithValidToken() { - var accessToken = this.ObtainValidAccessToken(); + public async Task GetAccessTokenWithValidToken() { + var accessToken = await this.ObtainValidAccessTokenAsync(); var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(AsymmetricKey, null)); @@ -76,11 +78,11 @@ namespace DotNetOpenAuth.Test.OAuth2 { { "Authorization", "Bearer " + accessToken }, }; var request = new HttpRequestInfo("GET", new Uri("http://localhost/resource"), headers: requestHeaders); - var resourceServerDecodedToken = resourceServer.GetAccessToken(request); + var resourceServerDecodedToken = await resourceServer.GetAccessTokenAsync(request); Assert.That(resourceServerDecodedToken, Is.Not.Null); } - private string ObtainValidAccessToken() { + private async Task<string> ObtainValidAccessTokenAsync() { string accessToken = null; var authServer = CreateAuthorizationServerMock(); authServer.Setup( @@ -89,20 +91,18 @@ namespace DotNetOpenAuth.Test.OAuth2 { authServer.Setup( a => a.CheckAuthorizeClientCredentialsGrant(It.Is<IAccessTokenRequest>(d => d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) .Returns<IAccessTokenRequest>(req => new AutomatedAuthorizationCheckResponse(req, true)); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServer.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = client.GetClientAccessToken(TestScopes); - Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(authState.RefreshToken, Is.Null); - accessToken = authState.AccessToken; - }, - server => { - server.HandleTokenRequest().Respond(); + + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServer.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var authState = await client.GetClientAccessTokenAsync(TestScopes); + Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(authState.RefreshToken, Is.Null); + accessToken = authState.AccessToken; return accessToken; } diff --git a/src/DotNetOpenAuth.Test/OAuth2/UserAgentClientAuthorizeTests.cs b/src/DotNetOpenAuth.Test/OAuth2/UserAgentClientAuthorizeTests.cs index ae03b0c..d0e9617 100644 --- a/src/DotNetOpenAuth.Test/OAuth2/UserAgentClientAuthorizeTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth2/UserAgentClientAuthorizeTests.cs @@ -8,7 +8,10 @@ namespace DotNetOpenAuth.Test.OAuth2 { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth2; @@ -20,61 +23,77 @@ namespace DotNetOpenAuth.Test.OAuth2 { [TestFixture] public class UserAgentClientAuthorizeTests : OAuth2TestBase { [Test] - public void AuthorizationCodeGrant() { - var coordinator = new OAuth2Coordinator<UserAgentClient>( - AuthorizationServerDescription, - AuthorizationServerMock, - new UserAgentClient(AuthorizationServerDescription), - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - var request = client.PrepareRequestUserAuthorization(authState); - Assert.AreEqual(EndUserAuthorizationResponseType.AuthorizationCode, request.ResponseType); - client.Channel.Respond(request); - var incoming = client.Channel.ReadFromRequest(); - var result = client.ProcessUserAuthorization(authState, incoming); - Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); - }, - server => { - var request = server.ReadAuthorizationRequest(); + public async Task AuthorizationCodeGrant() { + Handle(AuthorizationServerDescription.AuthorizationEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + var request = await server.ReadAuthorizationRequestAsync(req, ct); Assert.That(request, Is.Not.Null); - server.ApproveAuthorizationRequest(request, ResourceOwnerUsername); - server.HandleTokenRequest().Respond(); + var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername); + return await server.Channel.PrepareResponseAsync(response, ct); }); - coordinator.Run(); + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + return await server.HandleTokenRequestAsync(req, ct); + }); + { + var client = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, }; + var request = client.PrepareRequestUserAuthorization(authState); + Assert.AreEqual(EndUserAuthorizationResponseType.AuthorizationCode, request.ResponseType); + var authRequestRedirect = await client.Channel.PrepareResponseAsync(request); + Uri authRequestResponse; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) { + authRequestResponse = httpResponse.Headers.Location; + } + } + var incoming = + await + client.Channel.ReadFromRequestAsync( + new HttpRequestMessage(HttpMethod.Get, authRequestResponse), CancellationToken.None); + var result = await client.ProcessUserAuthorizationAsync(authState, incoming, CancellationToken.None); + Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); + } } [Test] - public void ImplicitGrant() { + public async Task ImplicitGrant() { var coordinatorClient = new UserAgentClient(AuthorizationServerDescription); - var coordinator = new OAuth2Coordinator<UserAgentClient>( - AuthorizationServerDescription, - AuthorizationServerMock, - coordinatorClient, - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true); - Assert.That(request.ResponseType, Is.EqualTo(EndUserAuthorizationResponseType.AccessToken)); - client.Channel.Respond(request); - var incoming = client.Channel.ReadFromRequest(); - var result = client.ProcessUserAuthorization(authState, incoming); - Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(result.RefreshToken, Is.Null); - }, - server => { - var request = server.ReadAuthorizationRequest(); + coordinatorClient.ClientCredentialApplicator = null; // implicit grant clients don't need a secret. + Handle(AuthorizationServerDescription.AuthorizationEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + var request = await server.ReadAuthorizationRequestAsync(req, ct); Assert.That(request, Is.Not.Null); IAccessTokenRequest accessTokenRequest = (EndUserAuthorizationImplicitRequest)request; Assert.That(accessTokenRequest.ClientAuthenticated, Is.False); - server.ApproveAuthorizationRequest(request, ResourceOwnerUsername); + var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername); + return await server.Channel.PrepareResponseAsync(response, ct); }); + { + var client = new UserAgentClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var authState = new AuthorizationState(TestScopes) { Callback = ClientCallback, }; + var request = client.PrepareRequestUserAuthorization(authState, implicitResponseType: true); + Assert.That(request.ResponseType, Is.EqualTo(EndUserAuthorizationResponseType.AccessToken)); + var authRequestRedirect = await client.Channel.PrepareResponseAsync(request); + Uri authRequestResponse; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) { + authRequestResponse = httpResponse.Headers.Location; + } + } - coordinatorClient.ClientCredentialApplicator = null; // implicit grant clients don't need a secret. - coordinator.Run(); + var incoming = + await client.Channel.ReadFromRequestAsync(new HttpRequestMessage(HttpMethod.Get, authRequestResponse), CancellationToken.None); + var result = await client.ProcessUserAuthorizationAsync(authState, incoming, CancellationToken.None); + Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(result.RefreshToken, Is.Null); + } } } } diff --git a/src/DotNetOpenAuth.Test/OAuth2/WebServerClientAuthorizeTests.cs b/src/DotNetOpenAuth.Test/OAuth2/WebServerClientAuthorizeTests.cs index 2a4241e..433cbf3 100644 --- a/src/DotNetOpenAuth.Test/OAuth2/WebServerClientAuthorizeTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth2/WebServerClientAuthorizeTests.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.Test.OAuth2 { using System.Net; using System.Net.Http; using System.Text; + using System.Threading; using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; @@ -22,31 +23,45 @@ namespace DotNetOpenAuth.Test.OAuth2 { [TestFixture] public class WebServerClientAuthorizeTests : OAuth2TestBase { [Test] - public void AuthorizationCodeGrant() { - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - AuthorizationServerMock, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = new AuthorizationState(TestScopes) { - Callback = ClientCallback, - }; - client.PrepareRequestUserAuthorization(authState).Respond(); - var result = client.ProcessUserAuthorization(); - Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); - }, - server => { - var request = server.ReadAuthorizationRequest(); + public async Task AuthorizationCodeGrant() { + Handle(AuthorizationServerDescription.AuthorizationEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + var request = await server.ReadAuthorizationRequestAsync(req, ct); Assert.That(request, Is.Not.Null); - server.ApproveAuthorizationRequest(request, ResourceOwnerUsername); - server.HandleTokenRequest().Respond(); + var response = server.PrepareApproveAuthorizationRequest(request, ResourceOwnerUsername); + return await server.Channel.PrepareResponseAsync(response, ct); }); - coordinator.Run(); + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(AuthorizationServerMock); + return await server.HandleTokenRequestAsync(req, ct); + }); + + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var authState = new AuthorizationState(TestScopes) { + Callback = ClientCallback, + }; + var authRequestRedirect = await client.PrepareRequestUserAuthorizationAsync(authState); + this.HostFactories.CookieContainer.SetCookies(authRequestRedirect, ClientCallback); + Uri authRequestResponse; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var httpResponse = await httpClient.GetAsync(authRequestRedirect.Headers.Location)) { + Assert.That(httpResponse.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); + authRequestResponse = httpResponse.Headers.Location; + } + } + + var authorizationResponse = new HttpRequestMessage(HttpMethod.Get, authRequestResponse); + this.HostFactories.CookieContainer.ApplyCookies(authorizationResponse); + var result = await client.ProcessUserAuthorizationAsync(authorizationResponse, CancellationToken.None); + Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty); } [Theory] - public void ResourceOwnerPasswordCredentialGrant(bool anonymousClient) { + public async Task ResourceOwnerPasswordCredentialGrant(bool anonymousClient) { var authHostMock = CreateAuthorizationServerMock(); if (anonymousClient) { authHostMock.Setup( @@ -58,27 +73,23 @@ namespace DotNetOpenAuth.Test.OAuth2 { MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))).Returns(true); } - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authHostMock.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - if (anonymousClient) { - client.ClientIdentifier = null; - } + Handle(AuthorizationServerDescription.TokenEndpoint).By(async (req, ct) => { + var server = new AuthorizationServer(authHostMock.Object); + return await server.HandleTokenRequestAsync(req, ct); + }); + + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + if (anonymousClient) { + client.ClientIdentifier = null; + } - var authState = client.ExchangeUserCredentialForToken(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes); - Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(authState.RefreshToken, Is.Not.Null.And.Not.Empty); - }, - server => { - server.HandleTokenRequest().Respond(); - }); - coordinator.Run(); + var authState = await client.ExchangeUserCredentialForTokenAsync(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes); + Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(authState.RefreshToken, Is.Not.Null.And.Not.Empty); } [Test] - public void ClientCredentialGrant() { + public async Task ClientCredentialGrant() { var authServer = CreateAuthorizationServerMock(); authServer.Setup( a => a.IsAuthorizationValid(It.Is<IAuthorizationDescription>(d => d.User == null && d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) @@ -86,23 +97,19 @@ namespace DotNetOpenAuth.Test.OAuth2 { authServer.Setup( a => a.CheckAuthorizeClientCredentialsGrant(It.Is<IAccessTokenRequest>(d => d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) .Returns<IAccessTokenRequest>(req => new AutomatedAuthorizationCheckResponse(req, true)); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServer.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = client.GetClientAccessToken(TestScopes); - Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); - Assert.That(authState.RefreshToken, Is.Null); - }, - server => { - server.HandleTokenRequest().Respond(); + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServer.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var authState = await client.GetClientAccessTokenAsync(TestScopes); + Assert.That(authState.AccessToken, Is.Not.Null.And.Not.Empty); + Assert.That(authState.RefreshToken, Is.Null); } [Test] - public void GetClientAccessTokenReturnsApprovedScope() { + public async Task GetClientAccessTokenReturnsApprovedScope() { string[] approvedScopes = new[] { "Scope2", "Scope3" }; var authServer = CreateAuthorizationServerMock(); authServer.Setup( @@ -111,22 +118,19 @@ namespace DotNetOpenAuth.Test.OAuth2 { authServer.Setup( a => a.CheckAuthorizeClientCredentialsGrant(It.Is<IAccessTokenRequest>(d => d.ClientIdentifier == ClientId && MessagingUtilities.AreEquivalent(d.Scope, TestScopes)))) .Returns<IAccessTokenRequest>(req => { - var response = new AutomatedAuthorizationCheckResponse(req, true); - response.ApprovedScope.ResetContents(approvedScopes); - return response; - }); - var coordinator = new OAuth2Coordinator<WebServerClient>( - AuthorizationServerDescription, - authServer.Object, - new WebServerClient(AuthorizationServerDescription), - client => { - var authState = client.GetClientAccessToken(TestScopes); - Assert.That(authState.Scope, Is.EquivalentTo(approvedScopes)); - }, - server => { - server.HandleTokenRequest().Respond(); + var response = new AutomatedAuthorizationCheckResponse(req, true); + response.ApprovedScope.ResetContents(approvedScopes); + return response; + }); + Handle(AuthorizationServerDescription.TokenEndpoint).By( + async (req, ct) => { + var server = new AuthorizationServer(authServer.Object); + return await server.HandleTokenRequestAsync(req, ct); }); - coordinator.Run(); + + var client = new WebServerClient(AuthorizationServerDescription, ClientId, ClientSecret, this.HostFactories); + var authState = await client.GetClientAccessTokenAsync(TestScopes); + Assert.That(authState.Scope, Is.EquivalentTo(approvedScopes)); } [Test] diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs index 029447d..6e3d7dc 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.Test.OpenId { using System; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; @@ -22,13 +24,13 @@ namespace DotNetOpenAuth.Test.OpenId { } [Test] - public void AssociateUnencrypted() { - this.ParameterizedAssociationTest(new Uri("https://host")); + public async Task AssociateUnencrypted() { + await this.ParameterizedAssociationTestAsync(OPUriSsl); } [Test] - public void AssociateDiffieHellmanOverHttp() { - this.ParameterizedAssociationTest(new Uri("http://host")); + public async Task AssociateDiffieHellmanOverHttp() { + await this.ParameterizedAssociationTestAsync(OPUri); } /// <summary> @@ -39,23 +41,22 @@ namespace DotNetOpenAuth.Test.OpenId { /// putting the two together, so we verify that DNOI can handle it. /// </remarks> [Test] - public void AssociateDiffieHellmanOverHttps() { + public async Task AssociateDiffieHellmanOverHttps() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - // We have to formulate the associate request manually, - // since the DNOI RP won't voluntarily use DH on HTTPS. - AssociateDiffieHellmanRequest request = new AssociateDiffieHellmanRequest(protocol.Version, new Uri("https://Provider")); - request.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; - request.SessionType = protocol.Args.SessionType.DH_SHA256; - request.InitializeRequest(); - var response = rp.Channel.Request<AssociateSuccessfulResponse>(request); - Assert.IsNotNull(response); - Assert.AreEqual(request.AssociationType, response.AssociationType); - Assert.AreEqual(request.SessionType, response.SessionType); - }, - AutoProvider); - coordinator.Run(); + this.RegisterAutoProvider(); + var rp = this.CreateRelyingParty(); + + // We have to formulate the associate request manually, + // since the DNOI RP won't voluntarily use DH on HTTPS. + var request = new AssociateDiffieHellmanRequest(protocol.Version, OPUri) { + AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256, + SessionType = protocol.Args.SessionType.DH_SHA256 + }; + request.InitializeRequest(); + var response = await rp.Channel.RequestAsync<AssociateSuccessfulResponse>(request, CancellationToken.None); + Assert.IsNotNull(response); + Assert.AreEqual(request.AssociationType, response.AssociationType); + Assert.AreEqual(request.SessionType, response.SessionType); } /// <summary> @@ -63,44 +64,52 @@ namespace DotNetOpenAuth.Test.OpenId { /// initial request for an association is for a type the OP doesn't support. /// </summary> [Test] - public void AssociateRenegotiateBitLength() { + public async Task AssociateRenegotiateBitLength() { Protocol protocol = Protocol.V20; // The strategy is to make a simple request of the RP to establish an association, // and to more carefully observe the Provider-side of things to make sure that both // the OP and RP are behaving as expected. - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - var opDescription = new ProviderEndpointDescription(OPUri, protocol.Version); - Association association = rp.AssociationManager.GetOrCreateAssociation(opDescription); - Assert.IsNotNull(association, "Association failed to be created."); - Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, association.GetAssociationType(protocol)); - }, - op => { + int providerAttemptCount = 0; + HandleProvider( + async (op, request) => { op.SecuritySettings.MaximumHashBitLength = 160; // Force OP to reject HMAC-SHA256 - // Receive initial request for an HMAC-SHA256 association. - AutoResponsiveRequest req = (AutoResponsiveRequest)op.GetRequest(); - AssociateRequest associateRequest = (AssociateRequest)req.RequestMessage; - Assert.That(associateRequest, Is.Not.Null); - Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA256, associateRequest.AssociationType); - - // Ensure that the response is a suggestion that the RP try again with HMAC-SHA1 - AssociateUnsuccessfulResponse renegotiateResponse = (AssociateUnsuccessfulResponse)req.ResponseMessageTestHook; - Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, renegotiateResponse.AssociationType); - op.Respond(req); - - // Receive second attempt request for an HMAC-SHA1 association. - req = (AutoResponsiveRequest)op.GetRequest(); - associateRequest = (AssociateRequest)req.RequestMessage; - Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, associateRequest.AssociationType); - - // Ensure that the response is a success response. - AssociateSuccessfulResponse successResponse = (AssociateSuccessfulResponse)req.ResponseMessageTestHook; - Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, successResponse.AssociationType); - op.Respond(req); + switch (++providerAttemptCount) { + case 1: + // Receive initial request for an HMAC-SHA256 association. + var req = (AutoResponsiveRequest)await op.GetRequestAsync(request); + var associateRequest = (AssociateRequest)req.RequestMessage; + Assert.That(associateRequest, Is.Not.Null); + Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA256, associateRequest.AssociationType); + + // Ensure that the response is a suggestion that the RP try again with HMAC-SHA1 + var renegotiateResponse = + (AssociateUnsuccessfulResponse)await req.GetResponseMessageAsyncTestHook(CancellationToken.None); + Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, renegotiateResponse.AssociationType); + return await op.PrepareResponseAsync(req); + + case 2: + // Receive second attempt request for an HMAC-SHA1 association. + req = (AutoResponsiveRequest)await op.GetRequestAsync(request); + associateRequest = (AssociateRequest)req.RequestMessage; + Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, associateRequest.AssociationType); + + // Ensure that the response is a success response. + var successResponse = + (AssociateSuccessfulResponse)await req.GetResponseMessageAsyncTestHook(CancellationToken.None); + Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, successResponse.AssociationType); + return await op.PrepareResponseAsync(req); + + default: + throw Assumes.NotReachable(); + } }); - coordinator.Run(); + var rp = this.CreateRelyingParty(); + var opDescription = new ProviderEndpointDescription(OPUri, protocol.Version); + Association association = await rp.AssociationManager.GetOrCreateAssociationAsync(opDescription, CancellationToken.None); + Assert.IsNotNull(association, "Association failed to be created."); + Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, association.GetAssociationType(protocol)); } /// <summary> @@ -110,20 +119,18 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies OP's compliance with OpenID 2.0 section 8.4.1. /// </remarks> [Test] - public void OPRejectsHttpNoEncryptionAssociateRequests() { + public async Task OPRejectsHttpNoEncryptionAssociateRequests() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - // We have to formulate the associate request manually, - // since the DNOI RP won't voluntarily suggest no encryption at all. - var request = new AssociateUnencryptedRequestNoSslCheck(protocol.Version, OPUri); - request.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; - request.SessionType = protocol.Args.SessionType.NoEncryption; - var response = rp.Channel.Request<DirectErrorResponse>(request); - Assert.IsNotNull(response); - }, - AutoProvider); - coordinator.Run(); + this.RegisterAutoProvider(); + var rp = this.CreateRelyingParty(); + + // We have to formulate the associate request manually, + // since the DNOA RP won't voluntarily suggest no encryption at all. + var request = new AssociateUnencryptedRequestNoSslCheck(protocol.Version, OPUri); + request.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; + request.SessionType = protocol.Args.SessionType.NoEncryption; + var response = await rp.Channel.RequestAsync<DirectErrorResponse>(request, CancellationToken.None); + Assert.IsNotNull(response); } /// <summary> @@ -131,47 +138,43 @@ namespace DotNetOpenAuth.Test.OpenId { /// when the HMAC and DH bit lengths do not match. /// </summary> [Test] - public void OPRejectsMismatchingAssociationAndSessionTypes() { + public async Task OPRejectsMismatchingAssociationAndSessionTypes() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - // We have to formulate the associate request manually, - // since the DNOI RP won't voluntarily mismatch the association and session types. - AssociateDiffieHellmanRequest request = new AssociateDiffieHellmanRequest(protocol.Version, new Uri("https://Provider")); - request.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; - request.SessionType = protocol.Args.SessionType.DH_SHA1; - request.InitializeRequest(); - var response = rp.Channel.Request<AssociateUnsuccessfulResponse>(request); - Assert.IsNotNull(response); - Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, response.AssociationType); - Assert.AreEqual(protocol.Args.SessionType.DH_SHA1, response.SessionType); - }, - AutoProvider); - coordinator.Run(); + this.RegisterAutoProvider(); + var rp = this.CreateRelyingParty(); + + // We have to formulate the associate request manually, + // since the DNOI RP won't voluntarily mismatch the association and session types. + var request = new AssociateDiffieHellmanRequest(protocol.Version, OPUri); + request.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; + request.SessionType = protocol.Args.SessionType.DH_SHA1; + request.InitializeRequest(); + var response = await rp.Channel.RequestAsync<AssociateUnsuccessfulResponse>(request, CancellationToken.None); + Assert.IsNotNull(response); + Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, response.AssociationType); + Assert.AreEqual(protocol.Args.SessionType.DH_SHA1, response.SessionType); } /// <summary> /// Verifies that the RP quietly rejects an OP that suggests an unknown association type. /// </summary> [Test] - public void RPRejectsUnrecognizedAssociationType() { + public async Task RPRejectsUnrecognizedAssociationType() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - var association = rp.AssociationManager.GetOrCreateAssociation(new ProviderEndpointDescription(OPUri, protocol.Version)); - Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); - }, - op => { + HandleProvider( + async (op, req) => { // Receive initial request. - var request = op.Channel.ReadFromRequest<AssociateRequest>(); + var request = await op.Channel.ReadFromRequestAsync<AssociateRequest>(req, CancellationToken.None); // Send a response that suggests a foreign association type. - AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); + var renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); renegotiateResponse.AssociationType = "HMAC-UNKNOWN"; renegotiateResponse.SessionType = "DH-UNKNOWN"; - op.Channel.Respond(renegotiateResponse); + return await op.Channel.PrepareResponseAsync(renegotiateResponse); }); - coordinator.Run(); + var rp = this.CreateRelyingParty(); + var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, protocol.Version), CancellationToken.None); + Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); } /// <summary> @@ -181,24 +184,23 @@ namespace DotNetOpenAuth.Test.OpenId { /// Verifies RP's compliance with OpenID 2.0 section 8.4.1. /// </remarks> [Test] - public void RPRejectsUnencryptedSuggestion() { + public async Task RPRejectsUnencryptedSuggestion() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - var association = rp.AssociationManager.GetOrCreateAssociation(new ProviderEndpointDescription(OPUri, protocol.Version)); - Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); - }, - op => { + this.HandleProvider( + async (op, req) => { // Receive initial request. - var request = op.Channel.ReadFromRequest<AssociateRequest>(); + var request = await op.Channel.ReadFromRequestAsync<AssociateRequest>(req, CancellationToken.None); // Send a response that suggests a no encryption. - AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); + var renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1; renegotiateResponse.SessionType = protocol.Args.SessionType.NoEncryption; - op.Channel.Respond(renegotiateResponse); + return await op.Channel.PrepareResponseAsync(renegotiateResponse); }); - coordinator.Run(); + + var rp = this.CreateRelyingParty(); + var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, protocol.Version), CancellationToken.None); + Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); } /// <summary> @@ -206,24 +208,22 @@ namespace DotNetOpenAuth.Test.OpenId { /// when the HMAC and DH bit lengths do not match. /// </summary> [Test] - public void RPRejectsMismatchingAssociationAndSessionBitLengths() { + public async Task RPRejectsMismatchingAssociationAndSessionBitLengths() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - var association = rp.AssociationManager.GetOrCreateAssociation(new ProviderEndpointDescription(OPUri, protocol.Version)); - Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); - }, - op => { + this.HandleProvider( + async (op, req) => { // Receive initial request. - var request = op.Channel.ReadFromRequest<AssociateRequest>(); + var request = await op.Channel.ReadFromRequestAsync<AssociateRequest>(req, CancellationToken.None); // Send a mismatched response AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1; renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256; - op.Channel.Respond(renegotiateResponse); + return await op.Channel.PrepareResponseAsync(renegotiateResponse); }); - coordinator.Run(); + var rp = this.CreateRelyingParty(); + var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, protocol.Version), CancellationToken.None); + Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); } /// <summary> @@ -231,52 +231,56 @@ namespace DotNetOpenAuth.Test.OpenId { /// keeps sending it association retry messages. /// </summary> [Test] - public void RPOnlyRenegotiatesOnce() { + public async Task RPOnlyRenegotiatesOnce() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - var association = rp.AssociationManager.GetOrCreateAssociation(new ProviderEndpointDescription(OPUri, protocol.Version)); - Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); - }, - op => { - // Receive initial request. - var request = op.Channel.ReadFromRequest<AssociateRequest>(); + int opStep = 0; + HandleProvider( + async (op, req) => { + switch (++opStep) { + case 1: + // Receive initial request. + var request = await op.Channel.ReadFromRequestAsync<AssociateRequest>(req, CancellationToken.None); - // Send a renegotiate response - AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); - renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1; - renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA1; - op.Channel.Respond(renegotiateResponse); + // Send a renegotiate response + var renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); + renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1; + renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA1; + return await op.Channel.PrepareResponseAsync(renegotiateResponse, CancellationToken.None); - // Receive second-try - request = op.Channel.ReadFromRequest<AssociateRequest>(); + case 2: + // Receive second-try + request = await op.Channel.ReadFromRequestAsync<AssociateRequest>(req, CancellationToken.None); - // Send ANOTHER renegotiate response, at which point the DNOI RP should give up. - renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); - renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; - renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256; - op.Channel.Respond(renegotiateResponse); + // Send ANOTHER renegotiate response, at which point the DNOI RP should give up. + renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request); + renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256; + renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256; + return await op.Channel.PrepareResponseAsync(renegotiateResponse, CancellationToken.None); + + default: + throw Assumes.NotReachable(); + } }); - coordinator.Run(); + var rp = this.CreateRelyingParty(); + var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, protocol.Version), CancellationToken.None); + Assert.IsNull(association, "The RP should quietly give up when the OP misbehaves."); } /// <summary> /// Verifies security settings limit RP's acceptance of OP's counter-suggestion /// </summary> [Test] - public void AssociateRenegotiateLimitedByRPSecuritySettings() { + public async Task AssociateRenegotiateLimitedByRPSecuritySettings() { Protocol protocol = Protocol.V20; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - rp.SecuritySettings.MinimumHashBitLength = 256; - var association = rp.AssociationManager.GetOrCreateAssociation(new ProviderEndpointDescription(OPUri, protocol.Version)); - Assert.IsNull(association, "No association should have been created when RP and OP could not agree on association strength."); - }, - op => { + HandleProvider( + async (op, req) => { op.SecuritySettings.MaximumHashBitLength = 160; - AutoProvider(op); + return await AutoProviderActionAsync(op, req, CancellationToken.None); }); - coordinator.Run(); + var rp = this.CreateRelyingParty(); + rp.SecuritySettings.MinimumHashBitLength = 256; + var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, protocol.Version), CancellationToken.None); + Assert.IsNull(association, "No association should have been created when RP and OP could not agree on association strength."); } /// <summary> @@ -284,10 +288,10 @@ namespace DotNetOpenAuth.Test.OpenId { /// response from the OP, for example in the HTTP timeout case. /// </summary> [Test] - public void AssociateQuietlyFailsAfterHttpError() { - this.MockResponder.RegisterMockNotFound(OPUri); + public async Task AssociateQuietlyFailsAfterHttpError() { + // Without wiring up a mock HTTP handler, the RP will get a 404 Not Found error. var rp = this.CreateRelyingParty(); - var association = rp.AssociationManager.GetOrCreateAssociation(new ProviderEndpointDescription(OPUri, Protocol.V20.Version)); + var association = await rp.AssociationManager.GetOrCreateAssociationAsync(new ProviderEndpointDescription(OPUri, Protocol.V20.Version), CancellationToken.None); Assert.IsNull(association); } @@ -295,11 +299,11 @@ namespace DotNetOpenAuth.Test.OpenId { /// Runs a parameterized association flow test using all supported OpenID versions. /// </summary> /// <param name="opEndpoint">The OP endpoint to simulate using.</param> - private void ParameterizedAssociationTest(Uri opEndpoint) { + private async Task ParameterizedAssociationTestAsync(Uri opEndpoint) { foreach (Protocol protocol in Protocol.AllPracticalVersions) { var endpoint = new ProviderEndpointDescription(opEndpoint, protocol.Version); var associationType = protocol.Version.Major < 2 ? protocol.Args.SignatureAlgorithm.HMAC_SHA1 : protocol.Args.SignatureAlgorithm.HMAC_SHA256; - this.ParameterizedAssociationTest(endpoint, associationType); + await this.ParameterizedAssociationTestAsync(endpoint, associationType); } } @@ -314,7 +318,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// The value of the openid.assoc_type parameter expected, /// or null if a failure is anticipated. /// </param> - private void ParameterizedAssociationTest( + private async Task ParameterizedAssociationTestAsync( ProviderEndpointDescription opDescription, string expectedAssociationType) { Protocol protocol = Protocol.Lookup(Protocol.Lookup(opDescription.Version).ProtocolVersion); @@ -323,19 +327,18 @@ namespace DotNetOpenAuth.Test.OpenId { Association rpAssociation = null, opAssociation; AssociateSuccessfulResponse associateSuccessfulResponse = null; AssociateUnsuccessfulResponse associateUnsuccessfulResponse = null; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - rp.SecuritySettings = this.RelyingPartySecuritySettings; - rpAssociation = rp.AssociationManager.GetOrCreateAssociation(opDescription); - }, - op => { - op.SecuritySettings = this.ProviderSecuritySettings; - IRequest req = op.GetRequest(); + var relyingParty = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore(), this.HostFactories); + var provider = new OpenIdProvider(new StandardProviderApplicationStore(), this.HostFactories) { + SecuritySettings = this.ProviderSecuritySettings + }; + Handle(opDescription.Uri).By( + async (request, ct) => { + IRequest req = await provider.GetRequestAsync(request, ct); Assert.IsNotNull(req, "Expected incoming request but did not receive it."); Assert.IsTrue(req.IsResponseReady); - op.Respond(req); + return await provider.PrepareResponseAsync(req, ct); }); - coordinator.IncomingMessageFilter = message => { + relyingParty.Channel.IncomingMessageFilter = message => { Assert.AreSame(opDescription.Version, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, Protocol.Lookup(opDescription.Version).ProtocolVersion); var associateSuccess = message as AssociateSuccessfulResponse; var associateFailed = message as AssociateUnsuccessfulResponse; @@ -346,16 +349,18 @@ namespace DotNetOpenAuth.Test.OpenId { associateUnsuccessfulResponse = associateFailed; } }; - coordinator.OutgoingMessageFilter = message => { + relyingParty.Channel.OutgoingMessageFilter = message => { Assert.AreEqual(opDescription.Version, message.Version, "The message was for version {0} but was expected to be for {1}.", message.Version, opDescription.Version); }; - coordinator.Run(); + + relyingParty.SecuritySettings = this.RelyingPartySecuritySettings; + rpAssociation = await relyingParty.AssociationManager.GetOrCreateAssociationAsync(opDescription, CancellationToken.None); if (expectSuccess) { Assert.IsNotNull(rpAssociation); - Association actual = coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle); + Association actual = relyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle); Assert.AreEqual(rpAssociation, actual); - opAssociation = coordinator.Provider.AssociationStore.Deserialize(new TestSignedDirectedMessage(), false, rpAssociation.Handle); + opAssociation = provider.AssociationStore.Deserialize(new TestSignedDirectedMessage(), false, rpAssociation.Handle); Assert.IsNotNull(opAssociation, "The Provider could not decode the association handle."); Assert.AreEqual(opAssociation.Handle, rpAssociation.Handle); @@ -373,7 +378,7 @@ namespace DotNetOpenAuth.Test.OpenId { var unencryptedResponse = (AssociateUnencryptedResponse)associateSuccessfulResponse; } } else { - Assert.IsNull(coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings())); + Assert.IsNull(relyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings())); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs index 14bcaec..1bc65e5 100644 --- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs @@ -6,6 +6,11 @@ namespace DotNetOpenAuth.Test.OpenId { using System; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId; @@ -24,76 +29,101 @@ namespace DotNetOpenAuth.Test.OpenId { } [Test] - public void SharedAssociationPositive() { - this.ParameterizedAuthenticationTest(true, true, false); + public async Task SharedAssociationPositive() { + await this.ParameterizedAuthenticationTestAsync(true, true, false); } /// <summary> /// Verifies that a shared association protects against tampering. /// </summary> [Test] - public void SharedAssociationTampered() { - this.ParameterizedAuthenticationTest(true, true, true); + public async Task SharedAssociationTampered() { + await this.ParameterizedAuthenticationTestAsync(true, true, true); } [Test] - public void SharedAssociationNegative() { - this.ParameterizedAuthenticationTest(true, false, false); + public async Task SharedAssociationNegative() { + await this.ParameterizedAuthenticationTestAsync(true, false, false); } [Test] - public void PrivateAssociationPositive() { - this.ParameterizedAuthenticationTest(false, true, false); + public async Task PrivateAssociationPositive() { + await this.ParameterizedAuthenticationTestAsync(false, true, false); } /// <summary> /// Verifies that a private association protects against tampering. /// </summary> [Test] - public void PrivateAssociationTampered() { - this.ParameterizedAuthenticationTest(false, true, true); + public async Task PrivateAssociationTampered() { + await this.ParameterizedAuthenticationTestAsync(false, true, true); } [Test] - public void NoAssociationNegative() { - this.ParameterizedAuthenticationTest(false, false, false); + public async Task NoAssociationNegative() { + await this.ParameterizedAuthenticationTestAsync(false, false, false); } [Test] - public void UnsolicitedAssertion() { - this.MockResponder.RegisterMockRPDiscovery(); - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - IAuthenticationResponse response = rp.GetResponse(); + public async Task UnsolicitedAssertion() { + var opStore = new StandardProviderApplicationStore(); + Handle(RPUri).By( + async req => { + var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore(), this.HostFactories); + IAuthenticationResponse response = await rp.GetResponseAsync(req); + Assert.That(response, Is.Not.Null); Assert.AreEqual(AuthenticationStatus.Authenticated, response.Status); - }, - op => { - op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - Identifier id = GetMockIdentifier(ProtocolVersion.V20); - op.SendUnsolicitedAssertion(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); - AutoProvider(op); // handle check_auth + return new HttpResponseMessage(); + }); + Handle(OPUri).By( + async (req, ct) => { + var op = new OpenIdProvider(opStore, this.HostFactories); + return await this.AutoProviderActionAsync(op, req, ct); }); - coordinator.Run(); + this.RegisterMockRPDiscovery(ssl: false); + + { + var op = new OpenIdProvider(opStore, this.HostFactories); + Identifier id = GetMockIdentifier(ProtocolVersion.V20); + var assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); + + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(assertion.Headers.Location)) { + response.EnsureSuccessStatusCode(); + } + } + } } [Test] - public void UnsolicitedAssertionRejected() { - this.MockResponder.RegisterMockRPDiscovery(); - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + public async Task UnsolicitedAssertionRejected() { + var opStore = new StandardProviderApplicationStore(); + Handle(RPUri).By( + async req => { + var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore(), this.HostFactories); rp.SecuritySettings.RejectUnsolicitedAssertions = true; - IAuthenticationResponse response = rp.GetResponse(); + IAuthenticationResponse response = await rp.GetResponseAsync(req); + Assert.That(response, Is.Not.Null); Assert.AreEqual(AuthenticationStatus.Failed, response.Status); - }, - op => { - op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - Identifier id = GetMockIdentifier(ProtocolVersion.V20); - op.SendUnsolicitedAssertion(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); - AutoProvider(op); // handle check_auth + return new HttpResponseMessage(); + }); + Handle(OPUri).By( + async req => { + var op = new OpenIdProvider(opStore, this.HostFactories); + return await this.AutoProviderActionAsync(op, req, CancellationToken.None); }); - coordinator.Run(); + this.RegisterMockRPDiscovery(ssl: false); + + { + var op = new OpenIdProvider(opStore, this.HostFactories); + Identifier id = GetMockIdentifier(ProtocolVersion.V20); + var assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(assertion.Headers.Location)) { + response.EnsureSuccessStatusCode(); + } + } + } } /// <summary> @@ -101,25 +131,37 @@ namespace DotNetOpenAuth.Test.OpenId { /// when the appropriate security setting is set. /// </summary> [Test] - public void UnsolicitedDelegatingIdentifierRejection() { - this.MockResponder.RegisterMockRPDiscovery(); - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + public async Task UnsolicitedDelegatingIdentifierRejection() { + var opStore = new StandardProviderApplicationStore(); + Handle(RPUri).By( + async req => { + var rp = this.CreateRelyingParty(); rp.SecuritySettings.RejectDelegatingIdentifiers = true; - IAuthenticationResponse response = rp.GetResponse(); + IAuthenticationResponse response = await rp.GetResponseAsync(req); + Assert.That(response, Is.Not.Null); Assert.AreEqual(AuthenticationStatus.Failed, response.Status); - }, - op => { - op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true); - op.SendUnsolicitedAssertion(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); - AutoProvider(op); // handle check_auth + return new HttpResponseMessage(); }); - coordinator.Run(); + Handle(OPUri).By( + async req => { + var op = new OpenIdProvider(opStore, this.HostFactories); + return await this.AutoProviderActionAsync(op, req, CancellationToken.None); + }); + this.RegisterMockRPDiscovery(ssl: false); + + { + var op = new OpenIdProvider(opStore, this.HostFactories); + Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true); + var assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]); + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(assertion.Headers.Location)) { + response.EnsureSuccessStatusCode(); + } + } + } } - private void ParameterizedAuthenticationTest(bool sharedAssociation, bool positive, bool tamper) { + private async Task ParameterizedAuthenticationTestAsync(bool sharedAssociation, bool positive, bool tamper) { foreach (Protocol protocol in Protocol.AllPracticalVersions) { foreach (bool statelessRP in new[] { false, true }) { if (sharedAssociation && statelessRP) { @@ -129,121 +171,154 @@ namespace DotNetOpenAuth.Test.OpenId { foreach (bool immediate in new[] { false, true }) { TestLogger.InfoFormat("Beginning authentication test scenario. OpenID: {0}, Shared: {1}, positive: {2}, tamper: {3}, stateless: {4}, immediate: {5}", protocol.Version, sharedAssociation, positive, tamper, statelessRP, immediate); - this.ParameterizedAuthenticationTest(protocol, statelessRP, sharedAssociation, positive, immediate, tamper); + await this.ParameterizedAuthenticationTestAsync(protocol, statelessRP, sharedAssociation, positive, immediate, tamper); } } } } - private void ParameterizedAuthenticationTest(Protocol protocol, bool statelessRP, bool sharedAssociation, bool positive, bool immediate, bool tamper) { + private async Task ParameterizedAuthenticationTestAsync(Protocol protocol, bool statelessRP, bool sharedAssociation, bool positive, bool immediate, bool tamper) { Requires.That(!statelessRP || !sharedAssociation, null, "The RP cannot be stateless while sharing an association with the OP."); Requires.That(positive || !tamper, null, "Cannot tamper with a negative response."); var securitySettings = new ProviderSecuritySettings(); var cryptoKeyStore = new MemoryCryptoKeyStore(); var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore); Association association = sharedAssociation ? HmacShaAssociationProvider.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings) : null; - var coordinator = new OpenIdCoordinator( - rp => { - var request = new CheckIdRequest(protocol.Version, OPUri, immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup); - + int opStep = 0; + HandleProvider( + async (op, req) => { if (association != null) { - StoreAssociation(rp, OPUri, association); - request.AssociationHandle = association.Handle; + var key = cryptoKeyStore.GetCurrentKey( + ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1)); + op.CryptoKeyStore.StoreKey( + ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value); } - request.ClaimedIdentifier = "http://claimedid"; - request.LocalIdentifier = "http://localid"; - request.ReturnTo = RPUri; - request.Realm = RPUri; - rp.Channel.Respond(request); - if (positive) { - if (tamper) { - try { - rp.Channel.ReadFromRequest<PositiveAssertionResponse>(); - Assert.Fail("Expected exception {0} not thrown.", typeof(InvalidSignatureException).Name); - } catch (InvalidSignatureException) { - TestLogger.InfoFormat("Caught expected {0} exception after tampering with signed data.", typeof(InvalidSignatureException).Name); + switch (++opStep) { + case 1: + var request = await op.Channel.ReadFromRequestAsync<CheckIdRequest>(req, CancellationToken.None); + Assert.IsNotNull(request); + IProtocolMessage response; + if (positive) { + response = new PositiveAssertionResponse(request); + } else { + response = await NegativeAssertionResponse.CreateAsync(request, CancellationToken.None, op.Channel); } - } else { - var response = rp.Channel.ReadFromRequest<PositiveAssertionResponse>(); - Assert.IsNotNull(response); - Assert.AreEqual(request.ClaimedIdentifier, response.ClaimedIdentifier); - Assert.AreEqual(request.LocalIdentifier, response.LocalIdentifier); - Assert.AreEqual(request.ReturnTo, response.ReturnTo); - - // Attempt to replay the message and verify that it fails. - // Because in various scenarios and protocol versions different components - // notice the replay, we can get one of two exceptions thrown. - // When the OP notices the replay we get a generic InvalidSignatureException. - // When the RP notices the replay we get a specific ReplayMessageException. - try { - CoordinatingChannel channel = (CoordinatingChannel)rp.Channel; - channel.Replay(response); - Assert.Fail("Expected ProtocolException was not thrown."); - } catch (ProtocolException ex) { - Assert.IsTrue(ex is ReplayedMessageException || ex is InvalidSignatureException, "A {0} exception was thrown instead of the expected {1} or {2}.", ex.GetType(), typeof(ReplayedMessageException).Name, typeof(InvalidSignatureException).Name); + + return await op.Channel.PrepareResponseAsync(response); + case 2: + if (positive && (statelessRP || !sharedAssociation)) { + var checkauthRequest = + await op.Channel.ReadFromRequestAsync<CheckAuthenticationRequest>(req, CancellationToken.None); + var checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest); + checkauthResponse.IsValid = checkauthRequest.IsValid; + return await op.Channel.PrepareResponseAsync(checkauthResponse); } - } - } else { - var response = rp.Channel.ReadFromRequest<NegativeAssertionResponse>(); - Assert.IsNotNull(response); - if (immediate) { - // Only 1.1 was required to include user_setup_url - if (protocol.Version.Major < 2) { - Assert.IsNotNull(response.UserSetupUrl); + + throw Assumes.NotReachable(); + case 3: + if (positive && (statelessRP || !sharedAssociation)) { + if (!tamper) { + // Respond to the replay attack. + var checkauthRequest = + await op.Channel.ReadFromRequestAsync<CheckAuthenticationRequest>(req, CancellationToken.None); + var checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest); + checkauthResponse.IsValid = checkauthRequest.IsValid; + return await op.Channel.PrepareResponseAsync(checkauthResponse); + } } - } else { - Assert.IsNull(response.UserSetupUrl); - } + + throw Assumes.NotReachable(); + default: + throw Assumes.NotReachable(); } - }, - op => { - if (association != null) { - var key = cryptoKeyStore.GetCurrentKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1)); - op.CryptoKeyStore.StoreKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value); + }); + + { + var rp = this.CreateRelyingParty(statelessRP); + if (tamper) { + rp.Channel.IncomingMessageFilter = message => { + var assertion = message as PositiveAssertionResponse; + if (assertion != null) { + // Alter the Local Identifier between the Provider and the Relying Party. + // If the signature binding element does its job, this should cause the RP + // to throw. + assertion.LocalIdentifier = "http://victim"; + } + }; + } + + var request = new CheckIdRequest( + protocol.Version, OPUri, immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup); + + if (association != null) { + StoreAssociation(rp, OPUri, association); + request.AssociationHandle = association.Handle; + } + + request.ClaimedIdentifier = "http://claimedid"; + request.LocalIdentifier = "http://localid"; + request.ReturnTo = RPUri; + request.Realm = RPUri; + var redirectRequest = await rp.Channel.PrepareResponseAsync(request); + Uri redirectResponse; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = rp.Channel.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(redirectRequest.Headers.Location)) { + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); + redirectResponse = response.Headers.Location; } + } - var request = op.Channel.ReadFromRequest<CheckIdRequest>(); - Assert.IsNotNull(request); - IProtocolMessage response; - if (positive) { - response = new PositiveAssertionResponse(request); + var assertionMessage = new HttpRequestMessage(HttpMethod.Get, redirectResponse); + if (positive) { + if (tamper) { + try { + await rp.Channel.ReadFromRequestAsync<PositiveAssertionResponse>(assertionMessage, CancellationToken.None); + Assert.Fail("Expected exception {0} not thrown.", typeof(InvalidSignatureException).Name); + } catch (InvalidSignatureException) { + TestLogger.InfoFormat( + "Caught expected {0} exception after tampering with signed data.", typeof(InvalidSignatureException).Name); + } } else { - response = new NegativeAssertionResponse(request, op.Channel); - } - op.Channel.Respond(response); - - if (positive && (statelessRP || !sharedAssociation)) { - var checkauthRequest = op.Channel.ReadFromRequest<CheckAuthenticationRequest>(); - var checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest); - checkauthResponse.IsValid = checkauthRequest.IsValid; - op.Channel.Respond(checkauthResponse); - - if (!tamper) { - // Respond to the replay attack. - checkauthRequest = op.Channel.ReadFromRequest<CheckAuthenticationRequest>(); - checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest); - checkauthResponse.IsValid = checkauthRequest.IsValid; - op.Channel.Respond(checkauthResponse); + var response = + await rp.Channel.ReadFromRequestAsync<PositiveAssertionResponse>(assertionMessage, CancellationToken.None); + Assert.IsNotNull(response); + Assert.AreEqual(request.ClaimedIdentifier, response.ClaimedIdentifier); + Assert.AreEqual(request.LocalIdentifier, response.LocalIdentifier); + Assert.AreEqual(request.ReturnTo, response.ReturnTo); + + // Attempt to replay the message and verify that it fails. + // Because in various scenarios and protocol versions different components + // notice the replay, we can get one of two exceptions thrown. + // When the OP notices the replay we get a generic InvalidSignatureException. + // When the RP notices the replay we get a specific ReplayMessageException. + try { + await rp.Channel.ReadFromRequestAsync<PositiveAssertionResponse>(assertionMessage, CancellationToken.None); + Assert.Fail("Expected ProtocolException was not thrown."); + } catch (ProtocolException ex) { + Assert.IsTrue( + ex is ReplayedMessageException || ex is InvalidSignatureException, + "A {0} exception was thrown instead of the expected {1} or {2}.", + ex.GetType(), + typeof(ReplayedMessageException).Name, + typeof(InvalidSignatureException).Name); } } - }); - if (tamper) { - coordinator.IncomingMessageFilter = message => { - var assertion = message as PositiveAssertionResponse; - if (assertion != null) { - // Alter the Local Identifier between the Provider and the Relying Party. - // If the signature binding element does its job, this should cause the RP - // to throw. - assertion.LocalIdentifier = "http://victim"; + } else { + var response = + await rp.Channel.ReadFromRequestAsync<NegativeAssertionResponse>(assertionMessage, CancellationToken.None); + Assert.IsNotNull(response); + if (immediate) { + // Only 1.1 was required to include user_setup_url + if (protocol.Version.Major < 2) { + Assert.IsNotNull(response.UserSetupUrl); + } + } else { + Assert.IsNull(response.UserSetupUrl); } - }; - } - if (statelessRP) { - coordinator.RelyingParty = new OpenIdRelyingParty(null); + } } - - coordinator.Run(); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs index dd47782..1a1307d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs @@ -8,12 +8,17 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.ChannelElements; using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using DotNetOpenAuth.Test.Mocks; using DotNetOpenAuth.Test.OpenId.Extensions; @@ -38,10 +43,10 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } [Test] - public void RoundTripFullStackTest() { + public async Task RoundTripFullStackTest() { IOpenIdMessageExtension request = new MockOpenIdExtension("requestPart", "requestData"); IOpenIdMessageExtension response = new MockOpenIdExtension("responsePart", "responseData"); - ExtensionTestUtilities.Roundtrip( + await this.RoundtripAsync( Protocol.Default, new IOpenIdMessageExtension[] { request }, new IOpenIdMessageExtension[] { response }); @@ -53,23 +58,23 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } [Test] - public void PrepareMessageForSendingNull() { - Assert.IsNull(this.rpElement.ProcessOutgoingMessage(null)); + public async Task PrepareMessageForSendingNull() { + Assert.IsNull(await this.rpElement.ProcessOutgoingMessageAsync(null, CancellationToken.None)); } /// <summary> /// Verifies that false is returned when a non-extendable message is sent. /// </summary> [Test] - public void PrepareMessageForSendingNonExtendableMessage() { + public async Task PrepareMessageForSendingNonExtendableMessage() { IProtocolMessage request = new AssociateDiffieHellmanRequest(Protocol.Default.Version, OpenIdTestBase.OPUri); - Assert.IsNull(this.rpElement.ProcessOutgoingMessage(request)); + Assert.IsNull(await this.rpElement.ProcessOutgoingMessageAsync(request, CancellationToken.None)); } [Test] - public void PrepareMessageForSending() { + public async Task PrepareMessageForSending() { this.request.Extensions.Add(new MockOpenIdExtension("part", "extra")); - Assert.IsNotNull(this.rpElement.ProcessOutgoingMessage(this.request)); + Assert.IsNotNull(await this.rpElement.ProcessOutgoingMessageAsync(this.request, CancellationToken.None)); string alias = GetAliases(this.request.ExtraData).Single(); Assert.AreEqual(MockOpenIdExtension.MockTypeUri, this.request.ExtraData["openid.ns." + alias]); @@ -78,11 +83,11 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } [Test] - public void PrepareMessageForReceiving() { + public async Task PrepareMessageForReceiving() { this.request.ExtraData["openid.ns.mock"] = MockOpenIdExtension.MockTypeUri; this.request.ExtraData["openid.mock.Part"] = "part"; this.request.ExtraData["openid.mock.data"] = "extra"; - Assert.IsNotNull(this.rpElement.ProcessIncomingMessage(this.request)); + Assert.IsNotNull(await this.rpElement.ProcessIncomingMessageAsync(this.request, CancellationToken.None)); MockOpenIdExtension ext = this.request.Extensions.OfType<MockOpenIdExtension>().Single(); Assert.AreEqual("part", ext.Part); Assert.AreEqual("extra", ext.Data); @@ -92,12 +97,12 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that extension responses are included in the OP's signature. /// </summary> [Test] - public void ExtensionResponsesAreSigned() { + public async Task ExtensionResponsesAreSigned() { Protocol protocol = Protocol.Default; var op = this.CreateProvider(); IndirectSignedResponse response = this.CreateResponseWithExtensions(protocol); - op.Channel.PrepareResponse(response); - ITamperResistantOpenIdMessage signedResponse = (ITamperResistantOpenIdMessage)response; + await op.Channel.PrepareResponseAsync(response); + ITamperResistantOpenIdMessage signedResponse = response; string extensionAliasKey = signedResponse.ExtraData.Single(kv => kv.Value == MockOpenIdExtension.MockTypeUri).Key; Assert.IsTrue(extensionAliasKey.StartsWith("openid.ns.")); string extensionAlias = extensionAliasKey.Substring("openid.ns.".Length); @@ -114,27 +119,59 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that unsigned extension responses (where any or all fields are unsigned) are ignored. /// </summary> [Test] - public void ExtensionsAreIdentifiedAsSignedOrUnsigned() { + public async Task ExtensionsAreIdentifiedAsSignedOrUnsigned() { Protocol protocol = Protocol.Default; - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { + var opStore = new StandardProviderApplicationStore(); + int rpStep = 0; + + + Handle(RPUri).By( + async req => { + var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore(), this.HostFactories); RegisterMockExtension(rp.Channel); - var response = rp.Channel.ReadFromRequest<IndirectSignedResponse>(); - Assert.AreEqual(1, response.SignedExtensions.Count(), "Signed extension should have been received."); - Assert.AreEqual(0, response.UnsignedExtensions.Count(), "No unsigned extension should be present."); - response = rp.Channel.ReadFromRequest<IndirectSignedResponse>(); - Assert.AreEqual(0, response.SignedExtensions.Count(), "No signed extension should have been received."); - Assert.AreEqual(1, response.UnsignedExtensions.Count(), "Unsigned extension should have been received."); - }, - op => { - RegisterMockExtension(op.Channel); - op.Channel.Respond(CreateResponseWithExtensions(protocol)); - op.Respond(op.GetRequest()); // check_auth - op.SecuritySettings.SignOutgoingExtensions = false; - op.Channel.Respond(CreateResponseWithExtensions(protocol)); - op.Respond(op.GetRequest()); // check_auth + + switch (++rpStep) { + case 1: + var response = await rp.Channel.ReadFromRequestAsync<IndirectSignedResponse>(req, CancellationToken.None); + Assert.AreEqual(1, response.SignedExtensions.Count(), "Signed extension should have been received."); + Assert.AreEqual(0, response.UnsignedExtensions.Count(), "No unsigned extension should be present."); + break; + case 2: + response = await rp.Channel.ReadFromRequestAsync<IndirectSignedResponse>(req, CancellationToken.None); + Assert.AreEqual(0, response.SignedExtensions.Count(), "No signed extension should have been received."); + Assert.AreEqual(1, response.UnsignedExtensions.Count(), "Unsigned extension should have been received."); + break; + + default: + throw Assumes.NotReachable(); + } + + return new HttpResponseMessage(); }); - coordinator.Run(); + Handle(OPUri).By( + async req => { + var op = new OpenIdProvider(opStore, this.HostFactories); + return await AutoProviderActionAsync(op, req, CancellationToken.None); + }); + + { + var op = new OpenIdProvider(opStore, this.HostFactories); + RegisterMockExtension(op.Channel); + var redirectingResponse = await op.Channel.PrepareResponseAsync(CreateResponseWithExtensions(protocol)); + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(redirectingResponse.Headers.Location)) { + response.EnsureSuccessStatusCode(); + } + } + + op.SecuritySettings.SignOutgoingExtensions = false; + redirectingResponse = await op.Channel.PrepareResponseAsync(CreateResponseWithExtensions(protocol)); + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(redirectingResponse.Headers.Location)) { + response.EnsureSuccessStatusCode(); + } + } + } } /// <summary> @@ -145,17 +182,17 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// "A namespace MUST NOT be assigned more than one alias in the same message". /// </remarks> [Test] - public void TwoExtensionsSameTypeUri() { + public async Task TwoExtensionsSameTypeUri() { IOpenIdMessageExtension request1 = new MockOpenIdExtension("requestPart1", "requestData1"); IOpenIdMessageExtension request2 = new MockOpenIdExtension("requestPart2", "requestData2"); try { - ExtensionTestUtilities.Roundtrip( + await this.RoundtripAsync( Protocol.Default, new IOpenIdMessageExtension[] { request1, request2 }, new IOpenIdMessageExtension[0]); Assert.Fail("Expected ProtocolException not thrown."); - } catch (AssertionException ex) { - Assert.IsInstanceOf<ProtocolException>(ex.InnerException); + } catch (ProtocolException) { + // success } } @@ -181,7 +218,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { private IndirectSignedResponse CreateResponseWithExtensions(Protocol protocol) { Requires.NotNull(protocol, "protocol"); - IndirectSignedResponse response = new IndirectSignedResponse(protocol.Version, RPUri); + var response = new IndirectSignedResponse(protocol.Version, RPUri); response.ProviderEndpoint = OPUri; response.Extensions.Add(new MockOpenIdExtension("pv", "ev")); return response; diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs index 93ad028..b64701d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/KeyValueFormEncodingTests.cs @@ -11,6 +11,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using System.Linq; using System.Net; using System.Text; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OpenId.ChannelElements; @@ -56,9 +59,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { Assert.AreEqual(this.sampleData.Count, count); } - public void KVDictTest(byte[] kvform, IDictionary<string, string> dict, TestMode mode) { + public async Task KVDictTestAsync(byte[] kvform, IDictionary<string, string> dict, TestMode mode) { if ((mode & TestMode.Decoder) == TestMode.Decoder) { - var d = this.keyValueForm.GetDictionary(new MemoryStream(kvform)); + var d = await this.keyValueForm.GetDictionaryAsync(new MemoryStream(kvform), CancellationToken.None); foreach (string key in dict.Keys) { Assert.AreEqual(d[key], dict[key], "Decoder fault: " + d[key] + " and " + dict[key] + " do not match."); } @@ -70,91 +73,91 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { } [Test] - public void EncodeDecode() { - this.KVDictTest(UTF8Encoding.UTF8.GetBytes(string.Empty), new Dictionary<string, string>(), TestMode.Both); + public async Task EncodeDecode() { + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes(string.Empty), new Dictionary<string, string>(), TestMode.Both); Dictionary<string, string> d1 = new Dictionary<string, string>(); d1.Add("college", "harvey mudd"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes("college:harvey mudd\n"), d1, TestMode.Both); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes("college:harvey mudd\n"), d1, TestMode.Both); Dictionary<string, string> d2 = new Dictionary<string, string>(); d2.Add("city", "claremont"); d2.Add("state", "CA"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes("city:claremont\nstate:CA\n"), d2, TestMode.Both); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes("city:claremont\nstate:CA\n"), d2, TestMode.Both); Dictionary<string, string> d3 = new Dictionary<string, string>(); d3.Add("is_valid", "true"); d3.Add("invalidate_handle", "{HMAC-SHA1:2398410938412093}"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes("is_valid:true\ninvalidate_handle:{HMAC-SHA1:2398410938412093}\n"), d3, TestMode.Both); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes("is_valid:true\ninvalidate_handle:{HMAC-SHA1:2398410938412093}\n"), d3, TestMode.Both); Dictionary<string, string> d4 = new Dictionary<string, string>(); d4.Add(string.Empty, string.Empty); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes(":\n"), d4, TestMode.Both); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes(":\n"), d4, TestMode.Both); Dictionary<string, string> d5 = new Dictionary<string, string>(); d5.Add(string.Empty, "missingkey"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes(":missingkey\n"), d5, TestMode.Both); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes(":missingkey\n"), d5, TestMode.Both); Dictionary<string, string> d6 = new Dictionary<string, string>(); d6.Add("street", "foothill blvd"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes("street:foothill blvd\n"), d6, TestMode.Both); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes("street:foothill blvd\n"), d6, TestMode.Both); Dictionary<string, string> d7 = new Dictionary<string, string>(); d7.Add("major", "computer science"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes("major:computer science\n"), d7, TestMode.Both); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes("major:computer science\n"), d7, TestMode.Both); Dictionary<string, string> d8 = new Dictionary<string, string>(); d8.Add("dorm", "east"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes(" dorm : east \n"), d8, TestMode.Decoder); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes(" dorm : east \n"), d8, TestMode.Decoder); Dictionary<string, string> d9 = new Dictionary<string, string>(); d9.Add("e^(i*pi)+1", "0"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes("e^(i*pi)+1:0"), d9, TestMode.Decoder); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes("e^(i*pi)+1:0"), d9, TestMode.Decoder); Dictionary<string, string> d10 = new Dictionary<string, string>(); d10.Add("east", "west"); d10.Add("north", "south"); - this.KVDictTest(UTF8Encoding.UTF8.GetBytes("east:west\nnorth:south"), d10, TestMode.Decoder); + await this.KVDictTestAsync(UTF8Encoding.UTF8.GetBytes("east:west\nnorth:south"), d10, TestMode.Decoder); } [Test, ExpectedException(typeof(FormatException))] - public void NoValue() { - this.Illegal("x\n", KeyValueFormConformanceLevel.OpenId11); + public async Task NoValue() { + await this.IllegalAsync("x\n", KeyValueFormConformanceLevel.OpenId11); } [Test, ExpectedException(typeof(FormatException))] - public void NoValueLoose() { + public async Task NoValueLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); - this.KVDictTest(Encoding.UTF8.GetBytes("x\n"), d, TestMode.Decoder); + await this.KVDictTestAsync(Encoding.UTF8.GetBytes("x\n"), d, TestMode.Decoder); } [Test, ExpectedException(typeof(FormatException))] - public void EmptyLine() { - this.Illegal("x:b\n\n", KeyValueFormConformanceLevel.OpenId20); + public async Task EmptyLine() { + await this.IllegalAsync("x:b\n\n", KeyValueFormConformanceLevel.OpenId20); } [Test] - public void EmptyLineLoose() { + public async Task EmptyLineLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("x", "b"); - this.KVDictTest(Encoding.UTF8.GetBytes("x:b\n\n"), d, TestMode.Decoder); + await this.KVDictTestAsync(Encoding.UTF8.GetBytes("x:b\n\n"), d, TestMode.Decoder); } [Test, ExpectedException(typeof(FormatException))] - public void LastLineNotTerminated() { - this.Illegal("x:y\na:b", KeyValueFormConformanceLevel.OpenId11); + public async Task LastLineNotTerminated() { + await this.IllegalAsync("x:y\na:b", KeyValueFormConformanceLevel.OpenId11); } [Test] - public void LastLineNotTerminatedLoose() { + public async Task LastLineNotTerminatedLoose() { Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("x", "y"); d.Add("a", "b"); - this.KVDictTest(Encoding.UTF8.GetBytes("x:y\na:b"), d, TestMode.Decoder); + await this.KVDictTestAsync(Encoding.UTF8.GetBytes("x:y\na:b"), d, TestMode.Decoder); } - private void Illegal(string s, KeyValueFormConformanceLevel level) { - new KeyValueFormEncoding(level).GetDictionary(new MemoryStream(Encoding.UTF8.GetBytes(s))); + private async Task IllegalAsync(string s, KeyValueFormConformanceLevel level) { + await new KeyValueFormEncoding(level).GetDictionaryAsync(new MemoryStream(Encoding.UTF8.GetBytes(s)), CancellationToken.None); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs index f50137d..c9cd52c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs @@ -10,7 +10,10 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using System.IO; using System.Linq; using System.Net; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.Messaging.Reflection; @@ -21,16 +24,13 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using NUnit.Framework; [TestFixture] - public class OpenIdChannelTests : TestBase { + public class OpenIdChannelTests : OpenIdTestBase { private static readonly TimeSpan maximumMessageAge = TimeSpan.FromHours(3); // good for tests, too long for production private OpenIdChannel channel; - private Mocks.TestWebRequestHandler webHandler; [SetUp] public void Setup() { - this.webHandler = new Mocks.TestWebRequestHandler(); - this.channel = new OpenIdRelyingPartyChannel(new MemoryCryptoKeyStore(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings()); - this.channel.WebRequestHandler = this.webHandler; + this.channel = new OpenIdRelyingPartyChannel(new MemoryCryptoKeyStore(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings(), this.HostFactories); } [Test] @@ -52,14 +52,14 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that the channel sends direct message requests as HTTP POST requests. /// </summary> [Test] - public void DirectRequestsUsePost() { + public async Task DirectRequestsUsePost() { IDirectedProtocolMessage requestMessage = new Mocks.TestDirectedMessage(MessageTransport.Direct) { Recipient = new Uri("http://host"), Name = "Andrew", }; - HttpWebRequest httpRequest = this.channel.CreateHttpRequestTestHook(requestMessage); - Assert.AreEqual("POST", httpRequest.Method); - StringAssert.Contains("Name=Andrew", this.webHandler.RequestEntityAsString); + var httpRequest = this.channel.CreateHttpRequestTestHook(requestMessage); + Assert.AreEqual(HttpMethod.Post, httpRequest.Method); + StringAssert.Contains("Name=Andrew", await httpRequest.Content.ReadAsStringAsync()); } /// <summary> @@ -72,16 +72,15 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// <see cref="OpenIdChannel.SendDirectMessageResponse"/> method. /// </remarks> [Test] - public void DirectResponsesSentUsingKeyValueForm() { + public async Task DirectResponsesSentUsingKeyValueForm() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); MessageDictionary messageFields = this.MessageDescriptions.GetAccessor(message); byte[] expectedBytes = KeyValueFormEncoding.GetBytes(messageFields); string expectedContentType = OpenIdChannel.KeyValueFormContentType; - OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message); - Assert.AreEqual(expectedContentType, directResponse.Headers[HttpResponseHeader.ContentType]); - byte[] actualBytes = new byte[directResponse.ResponseStream.Length]; - directResponse.ResponseStream.Read(actualBytes, 0, actualBytes.Length); + var directResponse = this.channel.PrepareDirectResponseTestHook(message); + Assert.AreEqual(expectedContentType, directResponse.Content.Headers.ContentType.MediaType); + byte[] actualBytes = await directResponse.Content.ReadAsByteArrayAsync(); Assert.IsTrue(MessagingUtilities.AreEquivalent(expectedBytes, actualBytes)); } @@ -89,15 +88,15 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that direct message responses are read in using the Key Value Form decoder. /// </summary> [Test] - public void DirectResponsesReceivedAsKeyValueForm() { + public async Task DirectResponsesReceivedAsKeyValueForm() { var fields = new Dictionary<string, string> { { "var1", "value1" }, { "var2", "value2" }, }; - var response = new CachedDirectWebResponse { - CachedResponseStream = new MemoryStream(KeyValueFormEncoding.GetBytes(fields)), + var response = new HttpResponseMessage { + Content = new StreamContent(new MemoryStream(KeyValueFormEncoding.GetBytes(fields))), }; - Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.channel.ReadFromResponseCoreTestHook(response))); + Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, await this.channel.ReadFromResponseCoreAsyncTestHook(response, CancellationToken.None))); } /// <summary> @@ -106,14 +105,14 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { [Test] public void SendDirectMessageResponseHonorsHttpStatusCodes() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); - OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message); - Assert.AreEqual(HttpStatusCode.OK, directResponse.Status); + var directResponse = this.channel.PrepareDirectResponseTestHook(message); + Assert.AreEqual(HttpStatusCode.OK, directResponse.StatusCode); var httpMessage = new TestDirectResponseMessageWithHttpStatus(); MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, httpMessage); httpMessage.HttpStatusCode = HttpStatusCode.NotAcceptable; directResponse = this.channel.PrepareDirectResponseTestHook(httpMessage); - Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.Status); + Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.StatusCode); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs index f7722e3..42b447e 100644 --- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs @@ -8,6 +8,9 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { using System; using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId; @@ -24,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that the signatures generated match Known Good signatures. /// </summary> [Test] - public void SignaturesMatchKnownGood() { + public async Task SignaturesMatchKnownGood() { Protocol protocol = Protocol.V20; var settings = new ProviderSecuritySettings(); var cryptoStore = new MemoryCryptoKeyStore(); @@ -41,7 +44,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { message.ProviderEndpoint = new Uri("http://provider"); signedMessage.UtcCreationDate = DateTime.Parse("1/1/2009"); signedMessage.AssociationHandle = handle; - Assert.IsNotNull(signer.ProcessOutgoingMessage(message)); + Assert.IsNotNull(await signer.ProcessOutgoingMessageAsync(message, CancellationToken.None)); Assert.AreEqual("o9+uN7qTaUS9v0otbHTuNAtbkpBm14+es9QnNo6IHD4=", signedMessage.Signature); } @@ -49,7 +52,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Verifies that all parameters in ExtraData in signed responses are signed. /// </summary> [Test] - public void SignedResponsesIncludeExtraDataInSignature() { + public async Task SignedResponsesIncludeExtraDataInSignature() { Protocol protocol = Protocol.Default; SigningBindingElement sbe = new ProviderSigningBindingElement(new ProviderAssociationHandleEncoder(new MemoryCryptoKeyStore()), new ProviderSecuritySettings()); sbe.Channel = new TestChannel(this.MessageDescriptions); @@ -60,7 +63,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { response.ExtraData["someunsigned"] = "value"; response.ExtraData["openid.somesigned"] = "value"; - Assert.IsNotNull(sbe.ProcessOutgoingMessage(response)); + Assert.IsNotNull(await sbe.ProcessOutgoingMessageAsync(response, CancellationToken.None)); ITamperResistantOpenIdMessage signedResponse = (ITamperResistantOpenIdMessage)response; // Make sure that the extra parameters are signed. @@ -76,14 +79,14 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { /// Regression test for bug #45 (https://github.com/AArnott/dotnetopenid/issues/45) /// </summary> [Test, ExpectedException(typeof(ProtocolException))] - public void MissingSignedParameter() { + public async Task MissingSignedParameter() { var cryptoStore = new MemoryCryptoKeyStore(); byte[] associationSecret = Convert.FromBase64String("rsSwv1zPWfjPRQU80hciu8FPDC+GONAMJQ/AvSo1a2M="); string handle = "{634477555066085461}{TTYcIg==}{32}"; cryptoStore.StoreKey(ProviderAssociationKeyStorage.PrivateAssociationBucket, handle, new CryptoKey(associationSecret, DateTime.UtcNow.AddDays(1))); var signer = new ProviderSigningBindingElement(new ProviderAssociationKeyStorage(cryptoStore), new ProviderSecuritySettings()); - var testChannel = new TestChannel(new OpenIdProviderMessageFactory()); + var testChannel = new TestChannel(new OpenIdProviderMessageFactory(), new IChannelBindingElement[0], this.HostFactories); signer.Channel = testChannel; var buggyRPMessage = new Dictionary<string, string>() { @@ -101,7 +104,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements { }; var message = (CheckAuthenticationRequest)testChannel.Receive(buggyRPMessage, new MessageReceivingEndpoint(OPUri, HttpDeliveryMethods.PostRequest)); var originalResponse = new IndirectSignedResponse(message, signer.Channel); - signer.ProcessIncomingMessage(originalResponse); + await signer.ProcessIncomingMessageAsync(originalResponse, CancellationToken.None); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs index 88ad208..3c54d98 100644 --- a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/UriDiscoveryServiceTests.cs @@ -9,48 +9,55 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { using System.Collections.Generic; using System.Linq; using System.Net; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Mocks; + using NUnit.Framework; [TestFixture] public class UriDiscoveryServiceTests : OpenIdTestBase { [Test] - public void DiscoveryWithRedirects() { + public async Task DiscoveryWithRedirects() { Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, false); // Add a couple of chained redirect pages that lead to the claimedId. Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); - this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); + this.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); + this.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); // don't require secure SSL discovery for this test. Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, false); - Assert.AreEqual(1, this.Discover(userSuppliedIdentifier).Count()); + var discoveryResult = await this.DiscoverAsync(userSuppliedIdentifier); + Assert.AreEqual(1, discoveryResult.Count()); } [Test] - public void DiscoverRequireSslWithSecureRedirects() { + public async Task DiscoverRequireSslWithSecureRedirects() { Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); // Add a couple of chained redirect pages that lead to the claimedId. // All redirects should be secure. Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); Uri secureMidpointUri = new Uri("https://localhost/secureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, secureMidpointUri); - this.MockResponder.RegisterMockRedirect(secureMidpointUri, new Uri(claimedId.ToString())); + this.RegisterMockRedirect(userSuppliedUri, secureMidpointUri); + this.RegisterMockRedirect(secureMidpointUri, new Uri(claimedId.ToString())); Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); - Assert.AreEqual(1, this.Discover(userSuppliedIdentifier).Count()); + var discoveryResult = await this.DiscoverAsync(userSuppliedIdentifier); + Assert.AreEqual(1, discoveryResult.Count()); } [Test, ExpectedException(typeof(ProtocolException))] - public void DiscoverRequireSslWithInsecureRedirect() { + public async Task DiscoverRequireSslWithInsecureRedirect() { Identifier claimedId = this.GetMockIdentifier(ProtocolVersion.V20, true); // Add a couple of chained redirect pages that lead to the claimedId. @@ -58,41 +65,43 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { // the ultimate endpoint is never found as a result of high security profile. Uri userSuppliedUri = new Uri("https://localhost/someSecurePage"); Uri insecureMidpointUri = new Uri("http://localhost/insecureStop"); - this.MockResponder.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); - this.MockResponder.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); + this.RegisterMockRedirect(userSuppliedUri, insecureMidpointUri); + this.RegisterMockRedirect(insecureMidpointUri, new Uri(claimedId.ToString())); Identifier userSuppliedIdentifier = new UriIdentifier(userSuppliedUri, true); - this.Discover(userSuppliedIdentifier); + await this.DiscoverAsync(userSuppliedIdentifier); } [Test] - public void DiscoveryRequireSslWithInsecureXrdsInSecureHtmlHead() { + public async Task DiscoveryRequireSslWithInsecureXrdsInSecureHtmlHead() { var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); Uri secureClaimedUri = new Uri("https://localhost/secureId"); string html = string.Format("<html><head><meta http-equiv='X-XRDS-Location' content='{0}'/></head><body></body></html>", insecureXrdsSource); - this.MockResponder.RegisterMockResponse(secureClaimedUri, "text/html", html); + this.RegisterMockResponse(secureClaimedUri, "text/html", html); Identifier userSuppliedIdentifier = new UriIdentifier(secureClaimedUri, true); - Assert.AreEqual(0, this.Discover(userSuppliedIdentifier).Count()); + var discoveryResult = await this.DiscoverAsync(userSuppliedIdentifier); + Assert.AreEqual(0, discoveryResult.Count()); } [Test] - public void DiscoveryRequireSslWithInsecureXrdsInSecureHttpHeader() { + public async Task DiscoveryRequireSslWithInsecureXrdsInSecureHttpHeader() { var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); string html = "<html><head></head><body></body></html>"; WebHeaderCollection headers = new WebHeaderCollection { { "X-XRDS-Location", insecureXrdsSource } }; - this.MockResponder.RegisterMockResponse(VanityUriSsl, VanityUriSsl, "text/html", headers, html); + this.RegisterMockResponse(VanityUriSsl, VanityUriSsl, "text/html", headers, html); Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); - Assert.AreEqual(0, this.Discover(userSuppliedIdentifier).Count()); + var discoveryResult = await this.DiscoverAsync(userSuppliedIdentifier); + Assert.AreEqual(0, discoveryResult.Count()); } [Test] - public void DiscoveryRequireSslWithInsecureXrdsButSecureLinkTags() { + public async Task DiscoveryRequireSslWithInsecureXrdsButSecureLinkTags() { var insecureXrdsSource = this.GetMockIdentifier(ProtocolVersion.V20, false); string html = string.Format( @" @@ -104,104 +113,109 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { HttpUtility.HtmlEncode(insecureXrdsSource), HttpUtility.HtmlEncode(OPUriSsl.AbsoluteUri), HttpUtility.HtmlEncode(OPLocalIdentifiersSsl[1].AbsoluteUri)); - this.MockResponder.RegisterMockResponse(VanityUriSsl, "text/html", html); + this.Handle(VanityUriSsl).By(html, "text/html"); Identifier userSuppliedIdentifier = new UriIdentifier(VanityUriSsl, true); // We verify that the XRDS was ignored and the LINK tags were used // because the XRDS OP-LocalIdentifier uses different local identifiers. - Assert.AreEqual(OPLocalIdentifiersSsl[1].AbsoluteUri, this.Discover(userSuppliedIdentifier).Single().ProviderLocalIdentifier.ToString()); + var discoveryResult = await this.DiscoverAsync(userSuppliedIdentifier); + Assert.AreEqual(OPLocalIdentifiersSsl[1].AbsoluteUri, discoveryResult.Single().ProviderLocalIdentifier.ToString()); } [Test] - public void DiscoveryRequiresSslIgnoresInsecureEndpointsInXrds() { + public async Task DiscoveryRequiresSslIgnoresInsecureEndpointsInXrds() { var insecureEndpoint = GetServiceEndpoint(0, ProtocolVersion.V20, 10, false); var secureEndpoint = GetServiceEndpoint(1, ProtocolVersion.V20, 20, true); UriIdentifier secureClaimedId = new UriIdentifier(VanityUriSsl, true); - this.MockResponder.RegisterMockXrdsResponse(secureClaimedId, new IdentifierDiscoveryResult[] { insecureEndpoint, secureEndpoint }); - Assert.AreEqual(secureEndpoint.ProviderLocalIdentifier, this.Discover(secureClaimedId).Single().ProviderLocalIdentifier); + this.RegisterMockXrdsResponse(secureClaimedId, new[] { insecureEndpoint, secureEndpoint }); + var discoverResult = await this.DiscoverAsync(secureClaimedId); + Assert.AreEqual(secureEndpoint.ProviderLocalIdentifier, discoverResult.Single().ProviderLocalIdentifier); } [Test] - public void XrdsDirectDiscovery_10() { - this.FailDiscoverXrds("xrds-irrelevant"); - this.DiscoverXrds("xrds10", ProtocolVersion.V10, null, "http://a/b"); - this.DiscoverXrds("xrds11", ProtocolVersion.V11, null, "http://a/b"); - this.DiscoverXrds("xrds1020", ProtocolVersion.V10, null, "http://a/b"); + public async Task XrdsDirectDiscovery_10() { + await this.FailDiscoverXrdsAsync("xrds-irrelevant"); + await this.DiscoverXrdsAsync("xrds10", ProtocolVersion.V10, null, "http://a/b"); + await this.DiscoverXrdsAsync("xrds11", ProtocolVersion.V11, null, "http://a/b"); + await this.DiscoverXrdsAsync("xrds1020", ProtocolVersion.V10, null, "http://a/b"); } [Test] - public void XrdsDirectDiscovery_20() { - this.DiscoverXrds("xrds20", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverXrds("xrds2010a", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverXrds("xrds2010b", ProtocolVersion.V20, null, "http://a/b"); + public async Task XrdsDirectDiscovery_20() { + await this.DiscoverXrdsAsync("xrds20", ProtocolVersion.V20, null, "http://a/b"); + await this.DiscoverXrdsAsync("xrds2010a", ProtocolVersion.V20, null, "http://a/b"); + await this.DiscoverXrdsAsync("xrds2010b", ProtocolVersion.V20, null, "http://a/b"); } [Test] - public void HtmlDiscover_11() { - this.DiscoverHtml("html10prov", ProtocolVersion.V11, null, "http://a/b"); - this.DiscoverHtml("html10both", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html10del"); + public async Task HtmlDiscover_11() { + await this.DiscoverHtmlAsync("html10prov", ProtocolVersion.V11, null, "http://a/b"); + await this.DiscoverHtmlAsync("html10both", ProtocolVersion.V11, "http://c/d", "http://a/b"); + await this.FailDiscoverHtmlAsync("html10del"); // Verify that HTML discovery generates the 1.x endpoints when appropriate - this.DiscoverHtml("html2010", ProtocolVersion.V11, "http://g/h", "http://e/f"); - this.DiscoverHtml("html1020", ProtocolVersion.V11, "http://g/h", "http://e/f"); - this.DiscoverHtml("html2010combinedA", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedB", ProtocolVersion.V11, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedC", ProtocolVersion.V11, "http://c/d", "http://a/b"); + await this.DiscoverHtmlAsync("html2010", ProtocolVersion.V11, "http://g/h", "http://e/f"); + await this.DiscoverHtmlAsync("html1020", ProtocolVersion.V11, "http://g/h", "http://e/f"); + await this.DiscoverHtmlAsync("html2010combinedA", ProtocolVersion.V11, "http://c/d", "http://a/b"); + await this.DiscoverHtmlAsync("html2010combinedB", ProtocolVersion.V11, "http://c/d", "http://a/b"); + await this.DiscoverHtmlAsync("html2010combinedC", ProtocolVersion.V11, "http://c/d", "http://a/b"); } [Test] - public void HtmlDiscover_20() { - this.DiscoverHtml("html20prov", ProtocolVersion.V20, null, "http://a/b"); - this.DiscoverHtml("html20both", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html20del"); - this.DiscoverHtml("html2010", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html1020", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedA", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedB", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.DiscoverHtml("html2010combinedC", ProtocolVersion.V20, "http://c/d", "http://a/b"); - this.FailDiscoverHtml("html20relative"); + public async Task HtmlDiscover_20() { + await this.DiscoverHtmlAsync("html20prov", ProtocolVersion.V20, null, "http://a/b"); + await this.DiscoverHtmlAsync("html20both", ProtocolVersion.V20, "http://c/d", "http://a/b"); + await this.FailDiscoverHtmlAsync("html20del"); + await this.DiscoverHtmlAsync("html2010", ProtocolVersion.V20, "http://c/d", "http://a/b"); + await this.DiscoverHtmlAsync("html1020", ProtocolVersion.V20, "http://c/d", "http://a/b"); + await this.DiscoverHtmlAsync("html2010combinedA", ProtocolVersion.V20, "http://c/d", "http://a/b"); + await this.DiscoverHtmlAsync("html2010combinedB", ProtocolVersion.V20, "http://c/d", "http://a/b"); + await this.DiscoverHtmlAsync("html2010combinedC", ProtocolVersion.V20, "http://c/d", "http://a/b"); + await this.FailDiscoverHtmlAsync("html20relative"); } [Test] - public void XrdsDiscoveryFromHead() { - this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); - this.DiscoverXrds("XrdsReferencedInHead.html", ProtocolVersion.V10, null, "http://a/b"); + public async Task XrdsDiscoveryFromHead() { + this.RegisterMockResponse( + new Uri("http://localhost/xrds1020.xml"), + "application/xrds+xml", + LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); + await this.DiscoverXrdsAsync("XrdsReferencedInHead.html", ProtocolVersion.V10, null, "http://a/b"); } [Test] - public void XrdsDiscoveryFromHttpHeader() { + public async Task XrdsDiscoveryFromHttpHeader() { WebHeaderCollection headers = new WebHeaderCollection(); headers.Add("X-XRDS-Location", new Uri("http://localhost/xrds1020.xml").AbsoluteUri); - this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); - this.DiscoverXrds("XrdsReferencedInHttpHeader.html", ProtocolVersion.V10, null, "http://a/b", headers); + this.RegisterMockResponse(new Uri("http://localhost/xrds1020.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds1020.xml")); + await this.DiscoverXrdsAsync("XrdsReferencedInHttpHeader.html", ProtocolVersion.V10, null, "http://a/b", headers); } /// <summary> /// Verifies HTML discovery proceeds if an XRDS document is referenced that doesn't contain OpenID endpoints. /// </summary> [Test] - public void HtmlDiscoveryProceedsIfXrdsIsEmpty() { - this.MockResponder.RegisterMockResponse(new Uri("http://localhost/xrds-irrelevant.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds-irrelevant.xml")); - this.DiscoverHtml("html20provWithEmptyXrds", ProtocolVersion.V20, null, "http://a/b"); + public async Task HtmlDiscoveryProceedsIfXrdsIsEmpty() { + this.RegisterMockResponse(new Uri("http://localhost/xrds-irrelevant.xml"), "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds-irrelevant.xml")); + await this.DiscoverHtmlAsync("html20provWithEmptyXrds", ProtocolVersion.V20, null, "http://a/b"); } /// <summary> /// Verifies HTML discovery proceeds if the XRDS that is referenced cannot be found. /// </summary> [Test] - public void HtmlDiscoveryProceedsIfXrdsIsBadOrMissing() { - this.DiscoverHtml("html20provWithBadXrds", ProtocolVersion.V20, null, "http://a/b"); + public async Task HtmlDiscoveryProceedsIfXrdsIsBadOrMissing() { + await this.DiscoverHtmlAsync("html20provWithBadXrds", ProtocolVersion.V20, null, "http://a/b"); } /// <summary> /// Verifies that a dual identifier yields only one service endpoint by default. /// </summary> [Test] - public void DualIdentifierOffByDefault() { - this.MockResponder.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); - var results = this.Discover(VanityUri).ToList(); + public async Task DualIdentifierOffByDefault() { + this.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); + var results = (await this.DiscoverAsync(VanityUri)).ToList(); Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == r.Protocol.ClaimedIdentifierForOPIdentifier), "OP Identifier missing from discovery results."); Assert.AreEqual(1, results.Count, "Unexpected additional services discovered."); } @@ -210,26 +224,39 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { /// Verifies that a dual identifier yields two service endpoints when that feature is turned on. /// </summary> [Test] - public void DualIdentifier() { - this.MockResponder.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); + public async Task DualIdentifier() { + this.RegisterMockResponse(VanityUri, "application/xrds+xml", LoadEmbeddedFile("/Discovery/xrdsdiscovery/xrds20dual.xml")); var rp = this.CreateRelyingParty(true); - rp.Channel.WebRequestHandler = this.RequestHandler; rp.SecuritySettings.AllowDualPurposeIdentifiers = true; - var results = rp.Discover(VanityUri).ToList(); + var results = (await rp.DiscoverAsync(VanityUri, CancellationToken.None)).ToList(); Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == r.Protocol.ClaimedIdentifierForOPIdentifier), "OP Identifier missing from discovery results."); Assert.AreEqual(1, results.Count(r => r.ClaimedIdentifier == VanityUri), "Claimed identifier missing from discovery results."); Assert.AreEqual(2, results.Count, "Unexpected additional services discovered."); } - private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect) { - this.Discover(url, version, expectedLocalId, providerEndpoint, expectSreg, useRedirect, null); + private async Task DiscoverAsync(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect) { + await this.DiscoverAsync(url, version, expectedLocalId, providerEndpoint, expectSreg, useRedirect, null); + } + + private string RegisterDiscoveryRedirector(Uri baseUrl) { + var redirectorUrl = new Uri(baseUrl, "Discovery/htmldiscovery/redirect.aspx"); + this.Handle(redirectorUrl).By(req => { + string redirectTarget = HttpUtility.ParseQueryString(req.RequestUri.Query)["target"]; + var response = new HttpResponseMessage(HttpStatusCode.Redirect); + response.Headers.Location = new Uri(redirectTarget, UriKind.RelativeOrAbsolute); + response.RequestMessage = req; + return response; + }); + + return redirectorUrl.AbsoluteUri + "?target="; } - private void Discover(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect, WebHeaderCollection headers) { + private async Task DiscoverAsync(string url, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool expectSreg, bool useRedirect, WebHeaderCollection headers) { Protocol protocol = Protocol.Lookup(version); Uri baseUrl = new Uri("http://localhost/"); + string redirectBase = this.RegisterDiscoveryRedirector(baseUrl); UriIdentifier claimedId = new Uri(baseUrl, url); - UriIdentifier userSuppliedIdentifier = new Uri(baseUrl, "Discovery/htmldiscovery/redirect.aspx?target=" + url); + UriIdentifier userSuppliedIdentifier = new Uri(redirectBase + Uri.EscapeDataString(url)); if (expectedLocalId == null) { expectedLocalId = claimedId; } @@ -243,7 +270,7 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { } else { throw new InvalidOperationException(); } - this.MockResponder.RegisterMockResponse(new Uri(idToDiscover), claimedId, contentType, headers ?? new WebHeaderCollection(), LoadEmbeddedFile(url)); + this.RegisterMockResponse(claimedId, claimedId, contentType, headers ?? new WebHeaderCollection(), LoadEmbeddedFile(url)); IdentifierDiscoveryResult expected = IdentifierDiscoveryResult.CreateForClaimedIdentifier( claimedId, @@ -252,7 +279,8 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { null, null); - IdentifierDiscoveryResult se = this.Discover(idToDiscover).FirstOrDefault(ep => ep.Equals(expected)); + var discoveryResult = await this.DiscoverAsync(idToDiscover); + IdentifierDiscoveryResult se = discoveryResult.FirstOrDefault(ep => ep.Equals(expected)); Assert.IsNotNull(se, url + " failed to be discovered."); // Do extra checking of service type URIs, which aren't included in @@ -262,42 +290,43 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { Assert.AreEqual(expectSreg, se.IsExtensionSupported<ClaimsRequest>()); } - private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { - this.DiscoverXrds(page, version, expectedLocalId, providerEndpoint, null); + private async Task DiscoverXrdsAsync(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { + await this.DiscoverXrdsAsync(page, version, expectedLocalId, providerEndpoint, null); } - private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, WebHeaderCollection headers) { + private async Task DiscoverXrdsAsync(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, WebHeaderCollection headers) { if (!page.Contains(".")) { page += ".xml"; } - this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, false, headers); - this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, true, headers); + await this.DiscoverAsync("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, false, headers); + await this.DiscoverAsync("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, true, headers); } - private void DiscoverHtml(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool useRedirect) { - this.Discover("/Discovery/htmldiscovery/" + page, version, expectedLocalId, providerEndpoint, false, useRedirect); + private async Task DiscoverHtmlAsync(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool useRedirect) { + await this.DiscoverAsync("/Discovery/htmldiscovery/" + page, version, expectedLocalId, providerEndpoint, false, useRedirect); } - private void DiscoverHtml(string scenario, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { + private async Task DiscoverHtmlAsync(string scenario, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) { string page = scenario + ".html"; - this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, false); - this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, true); + await this.DiscoverHtmlAsync(page, version, expectedLocalId, providerEndpoint, false); + await this.DiscoverHtmlAsync(page, version, expectedLocalId, providerEndpoint, true); } - private void FailDiscover(string url) { + private async Task FailDiscoverAsync(string url) { UriIdentifier userSuppliedId = new Uri(new Uri("http://localhost"), url); - this.MockResponder.RegisterMockResponse(new Uri(userSuppliedId), userSuppliedId, "text/html", LoadEmbeddedFile(url)); + this.RegisterMockResponse(new Uri(userSuppliedId), userSuppliedId, "text/html", LoadEmbeddedFile(url)); - Assert.AreEqual(0, this.Discover(userSuppliedId).Count()); // ... but that no endpoint info is discoverable + var discoveryResult = await this.DiscoverAsync(userSuppliedId); + Assert.AreEqual(0, discoveryResult.Count()); // ... but that no endpoint info is discoverable } - private void FailDiscoverHtml(string scenario) { - this.FailDiscover("/Discovery/htmldiscovery/" + scenario + ".html"); + private async Task FailDiscoverHtmlAsync(string scenario) { + await this.FailDiscoverAsync("/Discovery/htmldiscovery/" + scenario + ".html"); } - private void FailDiscoverXrds(string scenario) { - this.FailDiscover("/Discovery/xrdsdiscovery/" + scenario + ".xml"); + private async Task FailDiscoverXrdsAsync(string scenario) { + await this.FailDiscoverAsync("/Discovery/xrdsdiscovery/" + scenario + ".xml"); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs index fe767ea..23ddbfe 100644 --- a/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/DiscoveryServices/XriDiscoveryProxyServiceTests.cs @@ -9,14 +9,16 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { using System.Collections.Generic; using System.Linq; using System.Text; + using System.Threading.Tasks; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Mocks; using NUnit.Framework; [TestFixture] public class XriDiscoveryProxyServiceTests : OpenIdTestBase { [Test] - public void Discover() { + public async Task Discover() { string xrds = @"<?xml version='1.0' encoding='UTF-8'?> <XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> <Query>*Arnott</Query> @@ -48,14 +50,14 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { <URI append='none' priority='10'>http://1id.com/sso</URI> </Service> </XRD>"; - Dictionary<string, string> mocks = new Dictionary<string, string> { + var mocks = new Dictionary<string, string> { { "https://xri.net/=Arnott?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, { "https://xri.net/=!9B72.7DD1.50A9.5CCD?_xrd_r=application/xrd%2Bxml;sep=false", xrds }, }; - this.MockResponder.RegisterMockXrdsResponses(mocks); + this.RegisterMockXrdsResponses(mocks); string expectedCanonicalId = "=!9B72.7DD1.50A9.5CCD"; - IdentifierDiscoveryResult se = this.VerifyCanonicalId("=Arnott", expectedCanonicalId); + IdentifierDiscoveryResult se = await this.VerifyCanonicalIdAsync("=Arnott", expectedCanonicalId); Assert.AreEqual(Protocol.V10, Protocol.Lookup(se.Version)); Assert.AreEqual("http://1id.com/sso", se.ProviderEndpoint.ToString()); Assert.AreEqual(se.ClaimedIdentifier, se.ProviderLocalIdentifier); @@ -63,7 +65,7 @@ namespace DotNetOpenAuth.Test.OpenId.DiscoveryServices { } [Test] - public void DiscoverCommunityInameCanonicalIDs() { + public async Task DiscoverCommunityInameCanonicalIDs() { string llliResponse = @"<?xml version='1.0' encoding='UTF-8'?> <XRD version='2.0' xmlns='xri://$xrd*($v*2.0)'> <Query>*llli</Query> @@ -278,23 +280,23 @@ uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy </X509Data> </KeyInfo> </XRD>"; - this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { + this.RegisterMockXrdsResponses(new Dictionary<string, string> { { "https://xri.net/@llli?_xrd_r=application/xrd%2Bxml;sep=false", llliResponse }, { "https://xri.net/@llli*area?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaResponse }, { "https://xri.net/@llli*area*canada.unattached?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedResponse }, { "https://xri.net/@llli*area*canada.unattached*ada?_xrd_r=application/xrd%2Bxml;sep=false", llliAreaCanadaUnattachedAdaResponse }, { "https://xri.net/=Web?_xrd_r=application/xrd%2Bxml;sep=false", webResponse }, }); - this.VerifyCanonicalId("@llli", "@!72CD.A072.157E.A9C6"); - this.VerifyCanonicalId("@llli*area", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C"); - this.VerifyCanonicalId("@llli*area*canada.unattached", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41"); - this.VerifyCanonicalId("@llli*area*canada.unattached*ada", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01"); - this.VerifyCanonicalId("=Web", "=!91F2.8153.F600.AE24"); + await this.VerifyCanonicalIdAsync("@llli", "@!72CD.A072.157E.A9C6"); + await this.VerifyCanonicalIdAsync("@llli*area", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C"); + await this.VerifyCanonicalIdAsync("@llli*area*canada.unattached", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41"); + await this.VerifyCanonicalIdAsync("@llli*area*canada.unattached*ada", "@!72CD.A072.157E.A9C6!0000.0000.3B9A.CA0C!0000.0000.3B9A.CA41!0000.0000.3B9A.CA01"); + await this.VerifyCanonicalIdAsync("=Web", "=!91F2.8153.F600.AE24"); } [Test] - public void DiscoveryCommunityInameDelegateWithoutCanonicalID() { - this.MockResponder.RegisterMockXrdsResponses(new Dictionary<string, string> { + public async Task DiscoveryCommunityInameDelegateWithoutCanonicalID() { + this.RegisterMockXrdsResponses(new Dictionary<string, string> { { "https://xri.net/=Web*andrew.arnott?_xrd_r=application/xrd%2Bxml;sep=false", @"<?xml version='1.0' encoding='UTF-8'?> <XRD xmlns='xri://$xrd*($v*2.0)'> <Query>*andrew.arnott</Query> @@ -375,12 +377,12 @@ uEyb50RJ7DWmXctSC0b3eymZ2lSXxAWNOsNy }); // Consistent with spec section 7.3.2.3, we do not permit // delegation on XRI discovery when there is no CanonicalID present. - this.VerifyCanonicalId("=Web*andrew.arnott", null); - this.VerifyCanonicalId("@id*andrewarnott", null); + await this.VerifyCanonicalIdAsync("=Web*andrew.arnott", null); + await this.VerifyCanonicalIdAsync("@id*andrewarnott", null); } - private IdentifierDiscoveryResult VerifyCanonicalId(Identifier iname, string expectedClaimedIdentifier) { - var se = this.Discover(iname).FirstOrDefault(); + private async Task<IdentifierDiscoveryResult> VerifyCanonicalIdAsync(Identifier iname, string expectedClaimedIdentifier) { + var se = (await this.DiscoverAsync(iname)).FirstOrDefault(); if (expectedClaimedIdentifier != null) { Assert.IsNotNull(se); Assert.AreEqual(expectedClaimedIdentifier, se.ClaimedIdentifier.ToString(), "i-name {0} discovery resulted in unexpected CanonicalId", iname); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs index ab0a10b..0d0d36c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/AttributeExchange/AttributeExchangeRoundtripTests.cs @@ -5,6 +5,8 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OpenId.Extensions { + using System.Threading.Tasks; + using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; using NUnit.Framework; @@ -17,7 +19,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { private int incrementingAttributeValue = 1; [Test] - public void Fetch() { + public async Task Fetch() { var request = new FetchRequest(); request.Attributes.Add(new AttributeRequest(NicknameTypeUri)); request.Attributes.Add(new AttributeRequest(EmailTypeUri, false, int.MaxValue)); @@ -26,11 +28,11 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { response.Attributes.Add(new AttributeValues(NicknameTypeUri, "Andrew")); response.Attributes.Add(new AttributeValues(EmailTypeUri, "a@a.com", "b@b.com")); - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await this.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } [Test] - public void Store() { + public async Task Store() { var request = new StoreRequest(); var newAttribute = new AttributeValues( IncrementingAttribute, @@ -41,13 +43,13 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var successResponse = new StoreResponse(); successResponse.Succeeded = true; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { successResponse }); + await this.RoundtripAsync(Protocol.Default, new[] { request }, new[] { successResponse }); var failureResponse = new StoreResponse(); failureResponse.Succeeded = false; failureResponse.FailureReason = "Some error"; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { failureResponse }); + await this.RoundtripAsync(Protocol.Default, new[] { request }, new[] { failureResponse }); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs index 8d0e6ff..fd53fd1 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs @@ -8,6 +8,10 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System; using System.Collections.Generic; using System.Linq; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId; @@ -20,62 +24,6 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using Validation; public static class ExtensionTestUtilities { - /// <summary> - /// Simulates an extension request and response. - /// </summary> - /// <param name="protocol">The protocol to use in the roundtripping.</param> - /// <param name="requests">The extensions to add to the request message.</param> - /// <param name="responses">The extensions to add to the response message.</param> - /// <remarks> - /// This method relies on the extension objects' Equals methods to verify - /// accurate transport. The Equals methods should be verified by separate tests. - /// </remarks> - internal static void Roundtrip( - Protocol protocol, - IEnumerable<IOpenIdMessageExtension> requests, - IEnumerable<IOpenIdMessageExtension> responses) { - var securitySettings = new ProviderSecuritySettings(); - var cryptoKeyStore = new MemoryCryptoKeyStore(); - var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore); - Association association = HmacShaAssociationProvider.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings); - var coordinator = new OpenIdCoordinator( - rp => { - RegisterExtension(rp.Channel, Mocks.MockOpenIdExtension.Factory); - var requestBase = new CheckIdRequest(protocol.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate); - OpenIdTestBase.StoreAssociation(rp, OpenIdTestBase.OPUri, association); - requestBase.AssociationHandle = association.Handle; - requestBase.ClaimedIdentifier = "http://claimedid"; - requestBase.LocalIdentifier = "http://localid"; - requestBase.ReturnTo = OpenIdTestBase.RPUri; - - foreach (IOpenIdMessageExtension extension in requests) { - requestBase.Extensions.Add(extension); - } - - rp.Channel.Respond(requestBase); - var response = rp.Channel.ReadFromRequest<PositiveAssertionResponse>(); - - var receivedResponses = response.Extensions.Cast<IOpenIdMessageExtension>(); - CollectionAssert<IOpenIdMessageExtension>.AreEquivalentByEquality(responses.ToArray(), receivedResponses.ToArray()); - }, - op => { - RegisterExtension(op.Channel, Mocks.MockOpenIdExtension.Factory); - var key = cryptoKeyStore.GetCurrentKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1)); - op.CryptoKeyStore.StoreKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value); - var request = op.Channel.ReadFromRequest<CheckIdRequest>(); - var response = new PositiveAssertionResponse(request); - var receivedRequests = request.Extensions.Cast<IOpenIdMessageExtension>(); - CollectionAssert<IOpenIdMessageExtension>.AreEquivalentByEquality(requests.ToArray(), receivedRequests.ToArray()); - - foreach (var extensionResponse in responses) { - response.Extensions.Add(extensionResponse); - } - - op.Channel.Respond(response); - }); - coordinator.Run(); - } - internal static void RegisterExtension(Channel channel, StandardOpenIdExtensionFactory.CreateDelegate extensionFactory) { Requires.NotNull(channel, "channel"); diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs index e9ff7a4..60075f3 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperOPTests.cs @@ -7,6 +7,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.Collections.Generic; using System.Linq; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions; @@ -38,7 +40,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// Verifies no extensions appear as no extensions /// </summary> [Test] - public void NoRequestedExtensions() { + public async Task NoRequestedExtensions() { var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request); Assert.IsNull(sreg); @@ -47,22 +49,22 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { // to directly create a response without a request. var sregResponse = new ClaimsResponse(); this.request.AddResponseExtension(sregResponse); - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); - var extensions = this.GetResponseExtensions(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); Assert.AreSame(sregResponse, extensions.Single()); } [Test] - public void NegativeResponse() { + public async Task NegativeResponse() { this.request.IsAuthenticated = false; - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); } /// <summary> /// Verifies sreg coming in is seen as sreg. /// </summary> [Test] - public void UnifyExtensionsAsSregWithSreg() { + public async Task UnifyExtensionsAsSregWithSreg() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.TypeUris.Standard) { Nickname = DemandLevel.Request, }; @@ -74,8 +76,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var sregResponse = sreg.CreateResponse(); this.request.AddResponseExtension(sregResponse); - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); - var extensions = this.GetResponseExtensions(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); Assert.AreSame(sregResponse, extensions.Single()); } @@ -83,23 +85,23 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { /// Verifies AX coming in looks like sreg. /// </summary> [Test] - public void UnifyExtensionsAsSregWithAX() { - this.ParameterizedAXTest(AXAttributeFormats.AXSchemaOrg); + public async Task UnifyExtensionsAsSregWithAX() { + await this.ParameterizedAXTestAsync(AXAttributeFormats.AXSchemaOrg); } /// <summary> /// Verifies AX coming in looks like sreg. /// </summary> [Test] - public void UnifyExtensionsAsSregWithAXSchemaOpenIdNet() { - this.ParameterizedAXTest(AXAttributeFormats.SchemaOpenIdNet); + public async Task UnifyExtensionsAsSregWithAXSchemaOpenIdNet() { + await this.ParameterizedAXTestAsync(AXAttributeFormats.SchemaOpenIdNet); } /// <summary> /// Verifies sreg and AX in one request has a preserved sreg request. /// </summary> [Test] - public void UnifyExtensionsAsSregWithBothSregAndAX() { + public async Task UnifyExtensionsAsSregWithBothSregAndAX() { var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.TypeUris.Standard) { Nickname = DemandLevel.Request, }; @@ -118,20 +120,20 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var axResponseInjected = new FetchResponse(); axResponseInjected.Attributes.Add(WellKnownAttributes.Contact.Email, "a@b.com"); this.request.AddResponseExtension(axResponseInjected); - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); - var extensions = this.GetResponseExtensions(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); var sregResponse = extensions.OfType<ClaimsResponse>().Single(); Assert.AreEqual("andy", sregResponse.Nickname); var axResponse = extensions.OfType<FetchResponse>().Single(); Assert.AreEqual("a@b.com", axResponse.GetAttributeValue(WellKnownAttributes.Contact.Email)); } - private IList<IExtensionMessage> GetResponseExtensions() { - IProtocolMessageWithExtensions response = (IProtocolMessageWithExtensions)this.request.Response; + private async Task<IList<IExtensionMessage>> GetResponseExtensionsAsync() { + var response = (IProtocolMessageWithExtensions)await this.request.GetResponseAsync(CancellationToken.None); return response.Extensions; } - private void ParameterizedAXTest(AXAttributeFormats format) { + private async Task ParameterizedAXTestAsync(AXAttributeFormats format) { var axInjected = new FetchRequest(); axInjected.Attributes.AddOptional(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, format)); axInjected.Attributes.AddRequired(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.FullName, format)); @@ -145,8 +147,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var sregResponse = sreg.CreateResponse(); sregResponse.Nickname = "andy"; this.request.AddResponseExtension(sregResponse); - ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request); - var extensions = this.GetResponseExtensions(); + await ExtensionsInteropHelper.ConvertSregToMatchRequestAsync(this.request, CancellationToken.None); + var extensions = await this.GetResponseExtensionsAsync(); var axResponse = extensions.OfType<FetchResponse>().Single(); Assert.AreEqual("andy", axResponse.GetAttributeValue(ExtensionsInteropHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, format))); } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs index 05ba3ad..055cf8c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionsInteropHelperRPRequestTests.cs @@ -27,7 +27,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { var rp = CreateRelyingParty(true); Identifier identifier = this.GetMockIdentifier(ProtocolVersion.V20); - this.authReq = (AuthenticationRequest)rp.CreateRequest(identifier, RPRealmUri, RPUri); + this.authReq = (AuthenticationRequest)rp.CreateRequestAsync(identifier, RPRealmUri, RPUri).Result; this.sreg = new ClaimsRequest { Nickname = DemandLevel.Request, FullName = DemandLevel.Request, diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs index cba54bf..3cb3028 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ProviderAuthenticationPolicy/PapeRoundTripTests.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { using System; + using System.Threading.Tasks; + using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; using DotNetOpenAuth.Test.OpenId.Extensions; @@ -14,14 +16,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { [TestFixture] public class PapeRoundTripTests : OpenIdTestBase { [Test] - public void Trivial() { + public async Task Trivial() { var request = new PolicyRequest(); var response = new PolicyResponse(); - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await this.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } [Test] - public void Full() { + public async Task Full() { var request = new PolicyRequest(); request.MaximumAuthenticationAge = TimeSpan.FromMinutes(10); request.PreferredAuthLevelTypes.Add(Constants.AssuranceLevels.NistTypeUri); @@ -37,7 +39,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions.ProviderAuthenticationPolicy { response.AssuranceLevels["customlevel"] = "ABC"; response.NistAssuranceLevel = NistAssuranceLevel.Level2; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await this.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs index f898511..1aa6e33 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/SimpleRegistration/ClaimsResponseTests.cs @@ -10,13 +10,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; + using System.Threading.Tasks; using System.Xml.Serialization; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using NUnit.Framework; [TestFixture] - public class ClaimsResponseTests { + public class ClaimsResponseTests : OpenIdTestBase { [Test] public void EmptyMailAddress() { ClaimsResponse response = new ClaimsResponse(Constants.TypeUris.Standard); @@ -132,14 +133,14 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions { } [Test] - public void ResponseAlternateTypeUriTests() { + public async Task ResponseAlternateTypeUriTests() { var request = new ClaimsRequest(Constants.TypeUris.Variant10); request.Email = DemandLevel.Require; var response = new ClaimsResponse(Constants.TypeUris.Variant10); response.Email = "a@b.com"; - ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response }); + await this.RoundtripAsync(Protocol.Default, new[] { request }, new[] { response }); } private ClaimsResponse GetFilledData() { diff --git a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs index 393239b..11463c7 100644 --- a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs @@ -5,53 +5,84 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OpenId { + using System; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; using NUnit.Framework; + using System.Net; [TestFixture] public class NonIdentityTests : OpenIdTestBase { [Test] - public void ExtensionOnlyChannelLevel() { + public async Task ExtensionOnlyChannelLevel() { Protocol protocol = Protocol.V20; - AuthenticationRequestMode mode = AuthenticationRequestMode.Setup; - - var coordinator = new OpenIdCoordinator( - rp => { - var request = new SignedResponseRequest(protocol.Version, OPUri, mode); - rp.Channel.Respond(request); - }, - op => { - var request = op.Channel.ReadFromRequest<SignedResponseRequest>(); + var mode = AuthenticationRequestMode.Setup; + + HandleProvider( + async (op, req) => { + var request = await op.Channel.ReadFromRequestAsync<SignedResponseRequest>(req, CancellationToken.None); Assert.IsNotInstanceOf<CheckIdRequest>(request); + return new HttpResponseMessage(); }); - coordinator.Run(); + + { + var rp = this.CreateRelyingParty(); + var request = new SignedResponseRequest(protocol.Version, OPUri, mode); + var authRequest = await rp.Channel.PrepareResponseAsync(request); + using (var httpClient = rp.Channel.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(authRequest.Headers.Location)) { + response.EnsureSuccessStatusCode(); + } + } + } } [Test] - public void ExtensionOnlyFacadeLevel() { + public async Task ExtensionOnlyFacadeLevel() { Protocol protocol = Protocol.V20; - var coordinator = new OpenIdCoordinator( - rp => { - var request = rp.CreateRequest(GetMockIdentifier(protocol.ProtocolVersion), RPRealmUri, RPUri); - - request.IsExtensionOnly = true; - rp.Channel.Respond(request.RedirectingResponse.OriginalMessage); - IAuthenticationResponse response = rp.GetResponse(); - Assert.AreEqual(AuthenticationStatus.ExtensionsOnly, response.Status); - }, - op => { - var assocRequest = op.GetRequest(); - op.Respond(assocRequest); - - var request = (IAnonymousRequest)op.GetRequest(); - request.IsApproved = true; - Assert.IsNotInstanceOf<CheckIdRequest>(request); - op.Respond(request); + int opStep = 0; + HandleProvider( + async (op, req) => { + switch (++opStep) { + case 1: + var assocRequest = await op.GetRequestAsync(req); + return await op.PrepareResponseAsync(assocRequest); + case 2: + var request = (IAnonymousRequest)await op.GetRequestAsync(req); + request.IsApproved = true; + Assert.IsNotInstanceOf<CheckIdRequest>(request); + return await op.PrepareResponseAsync(request); + default: + throw Assumes.NotReachable(); + } }); - coordinator.Run(); + + { + var rp = this.CreateRelyingParty(); + var request = await rp.CreateRequestAsync(GetMockIdentifier(protocol.ProtocolVersion), RPRealmUri, RPUri); + + request.IsExtensionOnly = true; + var redirectRequest = await request.GetRedirectingResponseAsync(); + Uri redirectResponseUrl; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var redirectResponse = await httpClient.GetAsync(redirectRequest.Headers.Location)) { + Assert.That(redirectResponse.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); + redirectResponseUrl = redirectResponse.Headers.Location; + } + } + + IAuthenticationResponse response = + await rp.GetResponseAsync(new HttpRequestMessage(HttpMethod.Get, redirectResponseUrl)); + Assert.AreEqual(AuthenticationStatus.ExtensionsOnly, response.Status); + } } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs deleted file mode 100644 index 5000833..0000000 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdCoordinator.cs +++ /dev/null @@ -1,69 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OpenIdCoordinator.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.OpenId { - using System; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Bindings; - using DotNetOpenAuth.OpenId; - using DotNetOpenAuth.OpenId.Provider; - using DotNetOpenAuth.OpenId.RelyingParty; - using DotNetOpenAuth.Test.Mocks; - using Validation; - - internal class OpenIdCoordinator : CoordinatorBase<OpenIdRelyingParty, OpenIdProvider> { - internal OpenIdCoordinator(Action<OpenIdRelyingParty> rpAction, Action<OpenIdProvider> opAction) - : base(WrapAction(rpAction), WrapAction(opAction)) { - } - - internal OpenIdProvider Provider { get; set; } - - internal OpenIdRelyingParty RelyingParty { get; set; } - - internal override void Run() { - this.EnsurePartiesAreInitialized(); - var rpCoordinatingChannel = new CoordinatingChannel(this.RelyingParty.Channel, this.IncomingMessageFilter, this.OutgoingMessageFilter); - var opCoordinatingChannel = new CoordinatingChannel(this.Provider.Channel, this.IncomingMessageFilter, this.OutgoingMessageFilter); - rpCoordinatingChannel.RemoteChannel = opCoordinatingChannel; - opCoordinatingChannel.RemoteChannel = rpCoordinatingChannel; - - this.RelyingParty.Channel = rpCoordinatingChannel; - this.Provider.Channel = opCoordinatingChannel; - - RunCore(this.RelyingParty, this.Provider); - } - - private static Action<OpenIdRelyingParty> WrapAction(Action<OpenIdRelyingParty> action) { - Requires.NotNull(action, "action"); - - return rp => { - action(rp); - ((CoordinatingChannel)rp.Channel).Close(); - }; - } - - private static Action<OpenIdProvider> WrapAction(Action<OpenIdProvider> action) { - Requires.NotNull(action, "action"); - - return op => { - action(op); - ((CoordinatingChannel)op.Channel).Close(); - }; - } - - private void EnsurePartiesAreInitialized() { - if (this.RelyingParty == null) { - this.RelyingParty = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore()); - this.RelyingParty.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); - } - - if (this.Provider == null) { - this.Provider = new OpenIdProvider(new StandardProviderApplicationStore()); - this.Provider.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); - } - } - } -} diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs index 3a27e96..ea2867c 100644 --- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs +++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs @@ -8,21 +8,29 @@ namespace DotNetOpenAuth.Test.OpenId { using System; using System.Collections.Generic; using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; using System.Reflection; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Configuration; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Messaging; using DotNetOpenAuth.Test.Mocks; - using NUnit.Framework; + using DotNetOpenAuth.Test.OpenId.Extensions; - public class OpenIdTestBase : TestBase { - internal IDirectWebRequestHandler RequestHandler; + using NUnit.Framework; - internal MockHttpRequest MockResponder; + using IAuthenticationRequest = DotNetOpenAuth.OpenId.Provider.IAuthenticationRequest; + public class OpenIdTestBase : TestBase { protected internal const string IdentifierSelect = "http://specs.openid.net/auth/2.0/identifier_select"; protected internal static readonly Uri BaseMockUri = new Uri("http://localhost/"); @@ -69,10 +77,9 @@ namespace DotNetOpenAuth.Test.OpenId { this.RelyingPartySecuritySettings = OpenIdElement.Configuration.RelyingParty.SecuritySettings.CreateSecuritySettings(); this.ProviderSecuritySettings = OpenIdElement.Configuration.Provider.SecuritySettings.CreateSecuritySettings(); - this.MockResponder = MockHttpRequest.CreateUntrustedMockHttpHandler(); - this.RequestHandler = this.MockResponder.MockWebRequestHandler; this.AutoProviderScenario = Scenarios.AutoApproval; Identifier.EqualityOnStrings = true; + this.HostFactories.InstallUntrustedWebReqestHandler = true; } [TearDown] @@ -121,7 +128,7 @@ namespace DotNetOpenAuth.Test.OpenId { internal static IdentifierDiscoveryResult GetServiceEndpoint(int user, ProtocolVersion providerVersion, int servicePriority, bool useSsl, bool delegating) { var providerEndpoint = new ProviderEndpointDescription( - useSsl ? OpenIdTestBase.OPUriSsl : OpenIdTestBase.OPUri, + useSsl ? OPUriSsl : OPUri, new string[] { Protocol.Lookup(providerVersion).ClaimedIdentifierServiceTypeURI }); var local_id = useSsl ? OPLocalIdentifiersSsl[user] : OPLocalIdentifiers[user]; var claimed_id = delegating ? (useSsl ? VanityUriSsl : VanityUri) : local_id; @@ -135,50 +142,59 @@ namespace DotNetOpenAuth.Test.OpenId { } /// <summary> - /// A default implementation of a simple provider that responds to authentication requests + /// Gets a default implementation of a simple provider that responds to authentication requests /// per the scenario that is being simulated. /// </summary> - /// <param name="provider">The OpenIdProvider on which the process messages.</param> /// <remarks> /// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument. /// </remarks> - internal void AutoProvider(OpenIdProvider provider) { - while (!((CoordinatingChannel)provider.Channel).RemoteChannel.IsDisposed) { - IRequest request = provider.GetRequest(); - if (request == null) { - continue; - } + internal void RegisterAutoProvider() { + this.Handle(OPUri).By( + async (req, ct) => { + var provider = new OpenIdProvider(new StandardProviderApplicationStore(), this.HostFactories); + return await this.AutoProviderActionAsync(provider, req, ct); + }); + } - if (!request.IsResponseReady) { - var authRequest = (DotNetOpenAuth.OpenId.Provider.IAuthenticationRequest)request; - switch (this.AutoProviderScenario) { - case Scenarios.AutoApproval: - authRequest.IsAuthenticated = true; - break; - case Scenarios.AutoApprovalAddFragment: - authRequest.SetClaimedIdentifierFragment("frag"); - authRequest.IsAuthenticated = true; - break; - case Scenarios.ApproveOnSetup: - authRequest.IsAuthenticated = !authRequest.Immediate; - break; - case Scenarios.AlwaysDeny: - authRequest.IsAuthenticated = false; - break; - default: - // All other scenarios are done programmatically only. - throw new InvalidOperationException("Unrecognized scenario"); - } + /// <summary> + /// Gets a default implementation of a simple provider that responds to authentication requests + /// per the scenario that is being simulated. + /// </summary> + /// <remarks> + /// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument. + /// </remarks> + internal async Task<HttpResponseMessage> AutoProviderActionAsync(OpenIdProvider provider, HttpRequestMessage req, CancellationToken ct) { + IRequest request = await provider.GetRequestAsync(req, ct); + Assert.That(request, Is.Not.Null); + + if (!request.IsResponseReady) { + var authRequest = (IAuthenticationRequest)request; + switch (this.AutoProviderScenario) { + case Scenarios.AutoApproval: + authRequest.IsAuthenticated = true; + break; + case Scenarios.AutoApprovalAddFragment: + authRequest.SetClaimedIdentifierFragment("frag"); + authRequest.IsAuthenticated = true; + break; + case Scenarios.ApproveOnSetup: + authRequest.IsAuthenticated = !authRequest.Immediate; + break; + case Scenarios.AlwaysDeny: + authRequest.IsAuthenticated = false; + break; + default: + // All other scenarios are done programmatically only. + throw new InvalidOperationException("Unrecognized scenario"); } - - provider.Respond(request); } + + return await provider.PrepareResponseAsync(request, ct); } - internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) { + internal Task<IEnumerable<IdentifierDiscoveryResult>> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken = default(CancellationToken)) { var rp = this.CreateRelyingParty(true); - rp.Channel.WebRequestHandler = this.RequestHandler; - return rp.Discover(identifier); + return rp.DiscoverAsync(identifier, cancellationToken); } protected Realm GetMockRealm(bool useSsl) { @@ -196,8 +212,8 @@ namespace DotNetOpenAuth.Test.OpenId { protected Identifier GetMockIdentifier(ProtocolVersion providerVersion, bool useSsl, bool delegating) { var se = GetServiceEndpoint(0, providerVersion, 10, useSsl, delegating); - UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; - return new MockIdentifier(identityUri, this.MockResponder, new IdentifierDiscoveryResult[] { se }); + this.RegisterMockXrdsResponse(se); + return se.ClaimedIdentifier; } protected Identifier GetMockDualIdentifier() { @@ -208,8 +224,8 @@ namespace DotNetOpenAuth.Test.OpenId { IdentifierDiscoveryResult.CreateForProviderIdentifier(protocol.ClaimedIdentifierForOPIdentifier, opDesc, 20, 20), }; - Identifier dualId = new MockIdentifier(VanityUri, this.MockResponder, dualResults); - return dualId; + this.RegisterMockXrdsResponse(VanityUri, dualResults); + return VanityUri; } /// <summary> @@ -226,9 +242,7 @@ namespace DotNetOpenAuth.Test.OpenId { /// <param name="stateless">if set to <c>true</c> a stateless RP is created.</param> /// <returns>The new instance.</returns> protected OpenIdRelyingParty CreateRelyingParty(bool stateless) { - var rp = new OpenIdRelyingParty(stateless ? null : new StandardRelyingPartyApplicationStore()); - rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - rp.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); + var rp = new OpenIdRelyingParty(stateless ? null : new StandardRelyingPartyApplicationStore(), this.HostFactories); return rp; } @@ -237,10 +251,89 @@ namespace DotNetOpenAuth.Test.OpenId { /// </summary> /// <returns>The new instance.</returns> protected OpenIdProvider CreateProvider() { - var op = new OpenIdProvider(new StandardProviderApplicationStore()); - op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; - op.DiscoveryServices.Add(new MockIdentifierDiscoveryService()); + var op = new OpenIdProvider(new StandardProviderApplicationStore(), this.HostFactories); return op; } + + protected internal void HandleProvider(Func<OpenIdProvider, HttpRequestMessage, Task<HttpResponseMessage>> provider) { + var op = this.CreateProvider(); + this.Handle(OPUri).By(async req => { + return await provider(op, req); + }); + } + + /// <summary> + /// Simulates an extension request and response. + /// </summary> + /// <param name="protocol">The protocol to use in the roundtripping.</param> + /// <param name="requests">The extensions to add to the request message.</param> + /// <param name="responses">The extensions to add to the response message.</param> + /// <remarks> + /// This method relies on the extension objects' Equals methods to verify + /// accurate transport. The Equals methods should be verified by separate tests. + /// </remarks> + internal async Task RoundtripAsync( + Protocol protocol, IEnumerable<IOpenIdMessageExtension> requests, IEnumerable<IOpenIdMessageExtension> responses) { + var securitySettings = new ProviderSecuritySettings(); + var cryptoKeyStore = new MemoryCryptoKeyStore(); + var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore); + Association association = HmacShaAssociationProvider.Create( + protocol, + protocol.Args.SignatureAlgorithm.Best, + AssociationRelyingPartyType.Smart, + associationStore, + securitySettings); + + this.HandleProvider( + async (op, req) => { + ExtensionTestUtilities.RegisterExtension(op.Channel, Mocks.MockOpenIdExtension.Factory); + var key = cryptoKeyStore.GetCurrentKey( + ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1)); + op.CryptoKeyStore.StoreKey( + ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value); + var request = await op.Channel.ReadFromRequestAsync<CheckIdRequest>(req, CancellationToken.None); + var response = new PositiveAssertionResponse(request); + var receivedRequests = request.Extensions.Cast<IOpenIdMessageExtension>(); + CollectionAssert<IOpenIdMessageExtension>.AreEquivalentByEquality(requests.ToArray(), receivedRequests.ToArray()); + + foreach (var extensionResponse in responses) { + response.Extensions.Add(extensionResponse); + } + + return await op.Channel.PrepareResponseAsync(response); + }); + + { + var rp = this.CreateRelyingParty(); + ExtensionTestUtilities.RegisterExtension(rp.Channel, Mocks.MockOpenIdExtension.Factory); + var requestBase = new CheckIdRequest(protocol.Version, OpenIdTestBase.OPUri, AuthenticationRequestMode.Immediate); + OpenIdTestBase.StoreAssociation(rp, OpenIdTestBase.OPUri, association); + requestBase.AssociationHandle = association.Handle; + requestBase.ClaimedIdentifier = "http://claimedid"; + requestBase.LocalIdentifier = "http://localid"; + requestBase.ReturnTo = OpenIdTestBase.RPUri; + + foreach (IOpenIdMessageExtension extension in requests) { + requestBase.Extensions.Add(extension); + } + + var redirectingRequest = await rp.Channel.PrepareResponseAsync(requestBase); + Uri redirectingResponseUri; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = rp.Channel.HostFactories.CreateHttpClient()) { + using (var redirectingResponse = await httpClient.GetAsync(redirectingRequest.Headers.Location)) { + Assert.AreEqual(HttpStatusCode.Found, redirectingResponse.StatusCode); + redirectingResponseUri = redirectingResponse.Headers.Location; + } + } + + var response = + await + rp.Channel.ReadFromRequestAsync<PositiveAssertionResponse>( + new HttpRequestMessage(HttpMethod.Get, redirectingResponseUri), CancellationToken.None); + var receivedResponses = response.Extensions.Cast<IOpenIdMessageExtension>(); + CollectionAssert<IOpenIdMessageExtension>.AreEquivalentByEquality(responses.ToArray(), receivedResponses.ToArray()); + } + } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs index 7310eb3..8657910 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AnonymousRequestTests.cs @@ -8,6 +8,9 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; @@ -20,7 +23,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// Verifies that IsApproved controls which response message is returned. /// </summary> [Test] - public void IsApprovedDeterminesReturnedMessage() { + public async Task IsApprovedDeterminesReturnedMessage() { var op = CreateProvider(); Protocol protocol = Protocol.V20; var req = new SignedResponseRequest(protocol.Version, OPUri, AuthenticationRequestMode.Setup); @@ -30,15 +33,15 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { Assert.IsFalse(anonReq.IsApproved.HasValue); anonReq.IsApproved = false; - Assert.IsInstanceOf<NegativeAssertionResponse>(anonReq.Response); + Assert.IsInstanceOf<NegativeAssertionResponse>(await anonReq.GetResponseAsync(CancellationToken.None)); anonReq.IsApproved = true; - Assert.IsInstanceOf<IndirectSignedResponse>(anonReq.Response); - Assert.IsNotInstanceOf<PositiveAssertionResponse>(anonReq.Response); + Assert.IsInstanceOf<IndirectSignedResponse>(await anonReq.GetResponseAsync(CancellationToken.None)); + Assert.IsNotInstanceOf<PositiveAssertionResponse>(await anonReq.GetResponseAsync(CancellationToken.None)); } /// <summary> - /// Verifies that the AuthenticationRequest method is serializable. + /// Verifies that the AnonymousRequest type is serializable. /// </summary> [Test] public void Serializable() { diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs index baf5377..e9c5465 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/AuthenticationRequestTest.cs @@ -7,8 +7,12 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using System; using System.IO; + using System.Net.Http; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; @@ -21,24 +25,24 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// Verifies the user_setup_url is set properly for immediate negative responses. /// </summary> [Test] - public void UserSetupUrl() { + public async Task UserSetupUrl() { // Construct a V1 immediate request Protocol protocol = Protocol.V11; OpenIdProvider provider = this.CreateProvider(); - CheckIdRequest immediateRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Immediate); + var immediateRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Immediate); immediateRequest.Realm = RPRealmUri; immediateRequest.ReturnTo = RPUri; immediateRequest.LocalIdentifier = "http://somebody"; - AuthenticationRequest request = new AuthenticationRequest(provider, immediateRequest); + var request = new AuthenticationRequest(provider, immediateRequest); // Now simulate the request being rejected and extract the user_setup_url request.IsAuthenticated = false; - Uri userSetupUrl = ((NegativeAssertionResponse)request.Response).UserSetupUrl; + Uri userSetupUrl = ((NegativeAssertionResponse)await request.GetResponseAsync(CancellationToken.None)).UserSetupUrl; Assert.IsNotNull(userSetupUrl); // Now construct a new request as if it had just come in. - HttpRequestInfo httpRequest = new HttpRequestInfo("GET", userSetupUrl); - var setupRequest = (AuthenticationRequest)provider.GetRequest(httpRequest); + var httpRequest = new HttpRequestMessage(HttpMethod.Get, userSetupUrl); + var setupRequest = (AuthenticationRequest)await provider.GetRequestAsync(httpRequest); var setupRequestMessage = (CheckIdRequest)setupRequest.RequestMessage; // And make sure all the right properties are set. diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs index 2e3e7ec..ce5f417 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/HostProcessedRequestTests.cs @@ -6,9 +6,13 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using System; + using System.Threading; + using System.Threading.Tasks; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Messages; using DotNetOpenAuth.OpenId.Provider; + using DotNetOpenAuth.Test.Mocks; + using NUnit.Framework; [TestFixture] @@ -24,22 +28,23 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { this.protocol = Protocol.Default; this.provider = this.CreateProvider(); - this.checkIdRequest = new CheckIdRequest(this.protocol.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Setup); + this.checkIdRequest = new CheckIdRequest(this.protocol.Version, OPUri, AuthenticationRequestMode.Setup); this.checkIdRequest.Realm = RPRealmUri; this.checkIdRequest.ReturnTo = RPUri; this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); } [Test] - public void IsReturnUrlDiscoverableNoResponse() { - Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler)); + public async Task IsReturnUrlDiscoverableNoResponse() { + Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, await this.request.IsReturnUrlDiscoverableAsync(this.provider.Channel.HostFactories, CancellationToken.None)); } [Test] - public void IsReturnUrlDiscoverableValidResponse() { - this.MockResponder.RegisterMockRPDiscovery(); + public async Task IsReturnUrlDiscoverableValidResponse() { + this.RegisterMockRPDiscovery(false); + this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); - Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler)); + Assert.AreEqual(RelyingPartyDiscoveryResult.Success, await this.request.IsReturnUrlDiscoverableAsync(this.provider.Channel.HostFactories, CancellationToken.None)); } /// <summary> @@ -47,39 +52,42 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// is set, that discovery fails. /// </summary> [Test] - public void IsReturnUrlDiscoverableNotSsl() { + public async Task IsReturnUrlDiscoverableNotSsl() { + this.RegisterMockRPDiscovery(false); this.provider.SecuritySettings.RequireSsl = true; - this.MockResponder.RegisterMockRPDiscovery(); - Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler)); + Assert.AreEqual(RelyingPartyDiscoveryResult.NoServiceDocument, await this.request.IsReturnUrlDiscoverableAsync(this.provider.Channel.HostFactories, CancellationToken.None)); } /// <summary> /// Verifies that when discovery would be performed over HTTPS that discovery succeeds. /// </summary> [Test] - public void IsReturnUrlDiscoverableRequireSsl() { - this.MockResponder.RegisterMockRPDiscovery(); + public async Task IsReturnUrlDiscoverableRequireSsl() { + this.RegisterMockRPDiscovery(ssl: false); + this.RegisterMockRPDiscovery(ssl: true); this.checkIdRequest.Realm = RPRealmUriSsl; this.checkIdRequest.ReturnTo = RPUriSsl; // Try once with RequireSsl this.provider.SecuritySettings.RequireSsl = true; this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); - Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler)); + Assert.AreEqual(RelyingPartyDiscoveryResult.Success, await this.request.IsReturnUrlDiscoverableAsync(this.HostFactories, CancellationToken.None)); // And again without RequireSsl this.provider.SecuritySettings.RequireSsl = false; this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); - Assert.AreEqual(RelyingPartyDiscoveryResult.Success, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler)); + Assert.AreEqual(RelyingPartyDiscoveryResult.Success, await this.request.IsReturnUrlDiscoverableAsync(this.HostFactories, CancellationToken.None)); } [Test] - public void IsReturnUrlDiscoverableValidButNoMatch() { - this.MockResponder.RegisterMockRPDiscovery(); + public async Task IsReturnUrlDiscoverableValidButNoMatch() { + this.RegisterMockRPDiscovery(false); this.provider.SecuritySettings.RequireSsl = false; // reset for another failure test case this.checkIdRequest.ReturnTo = new Uri("http://somerandom/host"); this.request = new AuthenticationRequest(this.provider, this.checkIdRequest); - Assert.AreEqual(RelyingPartyDiscoveryResult.NoMatchingReturnTo, this.request.IsReturnUrlDiscoverable(this.provider.Channel.WebRequestHandler)); + Assert.AreEqual( + RelyingPartyDiscoveryResult.NoMatchingReturnTo, + await this.request.IsReturnUrlDiscoverableAsync(this.provider.Channel.HostFactories, CancellationToken.None)); } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs index c15f5b8..4780e37 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs @@ -7,6 +7,9 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { using System; using System.IO; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; @@ -74,60 +77,55 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { /// Verifies the GetRequest method throws outside an HttpContext. /// </summary> [Test, ExpectedException(typeof(InvalidOperationException))] - public void GetRequestNoContext() { + public async Task GetRequestNoContext() { HttpContext.Current = null; - this.provider.GetRequest(); + await this.provider.GetRequestAsync(); } /// <summary> /// Verifies GetRequest throws on null input. /// </summary> [Test, ExpectedException(typeof(ArgumentNullException))] - public void GetRequestNull() { - this.provider.GetRequest(null); + public async Task GetRequestNull() { + await this.provider.GetRequestAsync((HttpRequestMessage)null); } /// <summary> /// Verifies that GetRequest correctly returns the right messages. /// </summary> [Test] - public void GetRequest() { - var httpInfo = new HttpRequestInfo("GET", new Uri("http://someUri")); - Assert.IsNull(this.provider.GetRequest(httpInfo), "An irrelevant request should return null."); + public async Task GetRequest() { + var httpInfo = new HttpRequestMessage(HttpMethod.Get, "http://someUri"); + Assert.IsNull(await this.provider.GetRequestAsync(httpInfo), "An irrelevant request should return null."); var providerDescription = new ProviderEndpointDescription(OPUri, Protocol.Default.Version); // Test some non-empty request scenario. - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - rp.Channel.Request(AssociateRequestRelyingParty.Create(rp.SecuritySettings, providerDescription)); - }, - op => { - IRequest request = op.GetRequest(); + HandleProvider( + async (op, req) => { + IRequest request = await op.GetRequestAsync(req); Assert.IsInstanceOf<AutoResponsiveRequest>(request); - op.Respond(request); + return await op.PrepareResponseAsync(request); }); - coordinator.Run(); + var rp = this.CreateRelyingParty(); + await rp.Channel.RequestAsync(AssociateRequestRelyingParty.Create(rp.SecuritySettings, providerDescription), CancellationToken.None); } [Test] - public void BadRequestsGenerateValidErrorResponses() { - var coordinator = new OpenIdCoordinator( - rp => { - var nonOpenIdMessage = new Mocks.TestDirectedMessage(); - nonOpenIdMessage.Recipient = OPUri; - nonOpenIdMessage.HttpMethods = HttpDeliveryMethods.PostRequest; - MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, nonOpenIdMessage); - var response = rp.Channel.Request<DirectErrorResponse>(nonOpenIdMessage); - Assert.IsNotNull(response.ErrorMessage); - Assert.AreEqual(Protocol.Default.Version, response.Version); - }, - AutoProvider); - - coordinator.Run(); + public async Task BadRequestsGenerateValidErrorResponses() { + this.RegisterAutoProvider(); + var rp = this.CreateRelyingParty(); + var nonOpenIdMessage = new Mocks.TestDirectedMessage { + Recipient = OPUri, + HttpMethods = HttpDeliveryMethods.PostRequest + }; + MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, nonOpenIdMessage); + var response = await rp.Channel.RequestAsync<DirectErrorResponse>(nonOpenIdMessage, CancellationToken.None); + Assert.IsNotNull(response.ErrorMessage); + Assert.AreEqual(Protocol.Default.Version, response.Version); } [Test, Category("HostASPNET")] - public void BadRequestsGenerateValidErrorResponsesHosted() { + public async Task BadRequestsGenerateValidErrorResponsesHosted() { try { using (AspNetHost host = AspNetHost.CreateHost(TestWebDirectory)) { Uri opEndpoint = new Uri(host.BaseUri, "/OpenIdProviderEndpoint.ashx"); @@ -136,7 +134,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { nonOpenIdMessage.Recipient = opEndpoint; nonOpenIdMessage.HttpMethods = HttpDeliveryMethods.PostRequest; MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, nonOpenIdMessage); - var response = rp.Channel.Request<DirectErrorResponse>(nonOpenIdMessage); + var response = await rp.Channel.RequestAsync<DirectErrorResponse>(nonOpenIdMessage, CancellationToken.None); Assert.IsNotNull(response.ErrorMessage); } } catch (FileNotFoundException ex) { diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs index e2c719d..1501150 100644 --- a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs @@ -37,10 +37,10 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { public void AssociateDH() { var associateRequest = this.CreateAssociateRequest(OPUri); MeasurePerformance( - () => { - IRequest request = this.provider.GetRequest(associateRequest); - var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOf<AssociateSuccessfulResponse>(response.OriginalMessage); + async delegate { + IRequest request = await this.provider.GetRequestAsync(associateRequest); + var response = await this.provider.PrepareResponseAsync(request); + Assert.IsInstanceOf<AssociateSuccessfulResponse>(((HttpResponseMessageWithOriginal)response).OriginalMessage); }, maximumAllowedUnitTime: 3.5e6f, iterations: 1); @@ -50,10 +50,10 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { public void AssociateClearText() { var associateRequest = this.CreateAssociateRequest(OPUriSsl); // SSL will cause a plaintext association MeasurePerformance( - () => { - IRequest request = this.provider.GetRequest(associateRequest); - var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOf<AssociateSuccessfulResponse>(response.OriginalMessage); + async delegate { + IRequest request = await this.provider.GetRequestAsync(associateRequest); + var response = await this.provider.PrepareResponseAsync(request); + Assert.IsInstanceOf<AssociateSuccessfulResponse>(((HttpResponseMessageWithOriginal)response).OriginalMessage); }, maximumAllowedUnitTime: 1.5e4f, iterations: 1000); @@ -82,11 +82,11 @@ namespace DotNetOpenAuth.Test.OpenId.Provider { this.provider.SecuritySettings); var checkidRequest = this.CreateCheckIdRequest(true); MeasurePerformance( - () => { - var request = (IAuthenticationRequest)this.provider.GetRequest(checkidRequest); + async delegate { + var request = (IAuthenticationRequest)await this.provider.GetRequestAsync(checkidRequest); request.IsAuthenticated = true; - var response = this.provider.PrepareResponse(request); - Assert.IsInstanceOf<PositiveAssertionResponse>(response.OriginalMessage); + var response = await this.provider.PrepareResponseAsync(request); + Assert.IsInstanceOf<PositiveAssertionResponse>(((HttpResponseMessageWithOriginal)response).OriginalMessage); }, maximumAllowedUnitTime: 6.8e4f); } diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs index cd72fdb..333169f 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AuthenticationRequestTests.cs @@ -10,6 +10,8 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using System.Collections.Specialized; using System.Linq; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; @@ -70,54 +72,51 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies RedirectingResponse. /// </summary> [Test] - public void CreateRequestMessage() { - OpenIdCoordinator coordinator = new OpenIdCoordinator( - rp => { - Identifier id = this.GetMockIdentifier(ProtocolVersion.V20); - IAuthenticationRequest authRequest = rp.CreateRequest(id, this.realm, this.returnTo); - - // Add some callback arguments - authRequest.AddCallbackArguments("a", "b"); - authRequest.AddCallbackArguments(new Dictionary<string, string> { { "c", "d" }, { "e", "f" } }); - - // Assembly an extension request. - ClaimsRequest sregRequest = new ClaimsRequest(); - sregRequest.Nickname = DemandLevel.Request; - authRequest.AddExtension(sregRequest); - - // Construct the actual authentication request message. - var authRequestAccessor = (AuthenticationRequest)authRequest; - var req = authRequestAccessor.CreateRequestMessageTestHook(); - Assert.IsNotNull(req); - - // Verify that callback arguments were included. - NameValueCollection callbackArguments = HttpUtility.ParseQueryString(req.ReturnTo.Query); - Assert.AreEqual("b", callbackArguments["a"]); - Assert.AreEqual("d", callbackArguments["c"]); - Assert.AreEqual("f", callbackArguments["e"]); - - // Verify that extensions were included. - Assert.AreEqual(1, req.Extensions.Count); - Assert.IsTrue(req.Extensions.Contains(sregRequest)); - }, - AutoProvider); - coordinator.Run(); + public async Task CreateRequestMessage() { + this.RegisterAutoProvider(); + var rp = this.CreateRelyingParty(); + Identifier id = this.GetMockIdentifier(ProtocolVersion.V20); + IAuthenticationRequest authRequest = await rp.CreateRequestAsync(id, this.realm, this.returnTo); + + // Add some callback arguments + authRequest.AddCallbackArguments("a", "b"); + authRequest.AddCallbackArguments(new Dictionary<string, string> { { "c", "d" }, { "e", "f" } }); + + // Assembly an extension request. + var sregRequest = new ClaimsRequest(); + sregRequest.Nickname = DemandLevel.Request; + authRequest.AddExtension(sregRequest); + + // Construct the actual authentication request message. + var authRequestAccessor = (AuthenticationRequest)authRequest; + var req = await authRequestAccessor.CreateRequestMessageTestHookAsync(CancellationToken.None); + Assert.IsNotNull(req); + + // Verify that callback arguments were included. + NameValueCollection callbackArguments = HttpUtility.ParseQueryString(req.ReturnTo.Query); + Assert.AreEqual("b", callbackArguments["a"]); + Assert.AreEqual("d", callbackArguments["c"]); + Assert.AreEqual("f", callbackArguments["e"]); + + // Verify that extensions were included. + Assert.AreEqual(1, req.Extensions.Count); + Assert.IsTrue(req.Extensions.Contains(sregRequest)); } /// <summary> /// Verifies that delegating authentication requests are filtered out when configured to do so. /// </summary> [Test] - public void CreateFiltersDelegatingIdentifiers() { + public async Task CreateFiltersDelegatingIdentifiers() { Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true); var rp = CreateRelyingParty(); // First verify that delegating identifiers work - Assert.IsTrue(AuthenticationRequest.Create(id, rp, this.realm, this.returnTo, false).Any(), "The delegating identifier should have not generated any results."); + Assert.IsTrue((await AuthenticationRequest.CreateAsync(id, rp, this.realm, this.returnTo, false, CancellationToken.None)).Any(), "The delegating identifier should have not generated any results."); // Now disable them and try again. rp.SecuritySettings.RejectDelegatingIdentifiers = true; - Assert.IsFalse(AuthenticationRequest.Create(id, rp, this.realm, this.returnTo, false).Any(), "The delegating identifier should have not generated any results."); + Assert.IsFalse((await AuthenticationRequest.CreateAsync(id, rp, this.realm, this.returnTo, false, CancellationToken.None)).Any(), "The delegating identifier should have not generated any results."); } /// <summary> @@ -135,11 +134,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that AddCallbackArguments adds query arguments to the return_to URL of the message. /// </summary> [Test] - public void AddCallbackArgument() { + public async Task AddCallbackArgument() { var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); Assert.AreEqual(this.returnTo, authRequest.ReturnToUrl); authRequest.AddCallbackArguments("p1", "v1"); - var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; + var response = (HttpResponseMessageWithOriginal)await authRequest.GetRedirectingResponseAsync(CancellationToken.None); + var req = (SignedResponseRequest)response.OriginalMessage; NameValueCollection query = HttpUtility.ParseQueryString(req.ReturnTo.Query); Assert.AreEqual("v1", query["p1"]); } @@ -149,13 +149,14 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// rather than appending them. /// </summary> [Test] - public void AddCallbackArgumentClearsPreviousArgument() { + public async Task AddCallbackArgumentClearsPreviousArgument() { UriBuilder returnToWithArgs = new UriBuilder(this.returnTo); returnToWithArgs.AppendQueryArgs(new Dictionary<string, string> { { "p1", "v1" } }); this.returnTo = returnToWithArgs.Uri; var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); authRequest.AddCallbackArguments("p1", "v2"); - var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; + var response = (HttpResponseMessageWithOriginal)await authRequest.GetRedirectingResponseAsync(CancellationToken.None); + var req = (SignedResponseRequest)response.OriginalMessage; NameValueCollection query = HttpUtility.ParseQueryString(req.ReturnTo.Query); Assert.AreEqual("v2", query["p1"]); } @@ -164,11 +165,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies identity-less checkid_* request behavior. /// </summary> [Test] - public void NonIdentityRequest() { + public async Task NonIdentityRequest() { var authRequest = this.CreateAuthenticationRequest(this.claimedId, this.claimedId); authRequest.IsExtensionOnly = true; Assert.IsTrue(authRequest.IsExtensionOnly); - var req = (SignedResponseRequest)authRequest.RedirectingResponse.OriginalMessage; + var response = (HttpResponseMessageWithOriginal)await authRequest.GetRedirectingResponseAsync(CancellationToken.None); + var req = (SignedResponseRequest)response.OriginalMessage; Assert.IsNotInstanceOf<CheckIdRequest>(req, "An unexpected SignedResponseRequest derived type was generated."); } @@ -177,15 +179,15 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// only generate OP Identifier auth requests. /// </summary> [Test] - public void DualIdentifierUsedOnlyAsOPIdentifierForAuthRequest() { + public async Task DualIdentifierUsedOnlyAsOPIdentifierForAuthRequest() { var rp = this.CreateRelyingParty(true); - var results = AuthenticationRequest.Create(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false).ToList(); + var results = (await AuthenticationRequest.CreateAsync(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false, CancellationToken.None)).ToList(); Assert.AreEqual(1, results.Count); Assert.IsTrue(results[0].IsDirectedIdentity); // Also test when dual identiifer support is turned on. rp.SecuritySettings.AllowDualPurposeIdentifiers = true; - results = AuthenticationRequest.Create(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false).ToList(); + results = (await AuthenticationRequest.CreateAsync(GetMockDualIdentifier(), rp, this.realm, this.returnTo, false, CancellationToken.None)).ToList(); Assert.AreEqual(1, results.Count); Assert.IsTrue(results[0].IsDirectedIdentity); } diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs index a2a4efa..2d9413d 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/OpenIdRelyingPartyTests.cs @@ -7,11 +7,18 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using System; using System.Linq; + using System.Net.Http; + using System.Threading.Tasks; + using System.Web; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions; using DotNetOpenAuth.OpenId.Messages; + using DotNetOpenAuth.OpenId.Provider; using DotNetOpenAuth.OpenId.RelyingParty; + using DotNetOpenAuth.Test.Mocks; + using NUnit.Framework; [TestFixture] @@ -22,12 +29,13 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { } [Test] - public void CreateRequestDumbMode() { + public async Task CreateRequestDumbMode() { var rp = this.CreateRelyingParty(true); Identifier id = this.GetMockIdentifier(ProtocolVersion.V20); - var authReq = rp.CreateRequest(id, RPRealmUri, RPUri); - CheckIdRequest requestMessage = (CheckIdRequest)authReq.RedirectingResponse.OriginalMessage; - Assert.IsNull(requestMessage.AssociationHandle); + var authReq = await rp.CreateRequestAsync(id, RPRealmUri, RPUri); + var httpMessage = await authReq.GetRedirectingResponseAsync(); + var data = HttpUtility.ParseQueryString(httpMessage.GetDirectUriRequest().Query); + Assert.IsNull(data[Protocol.Default.openid.assoc_handle]); } [Test, ExpectedException(typeof(ArgumentNullException))] @@ -46,52 +54,52 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { } [Test] - public void CreateRequest() { + public async Task CreateRequest() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); Identifier id = Identifier.Parse(GetMockIdentifier(ProtocolVersion.V20)); - var req = rp.CreateRequest(id, RPRealmUri, RPUri); + var req = await rp.CreateRequestAsync(id, RPRealmUri, RPUri); Assert.IsNotNull(req); } [Test] - public void CreateRequests() { + public async Task CreateRequests() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); Identifier id = Identifier.Parse(GetMockIdentifier(ProtocolVersion.V20)); - var requests = rp.CreateRequests(id, RPRealmUri, RPUri); + var requests = await rp.CreateRequestsAsync(id, RPRealmUri, RPUri); Assert.AreEqual(1, requests.Count()); } [Test] - public void CreateRequestsWithEndpointFilter() { + public async Task CreateRequestsWithEndpointFilter() { var rp = this.CreateRelyingParty(); StoreAssociation(rp, OPUri, HmacShaAssociation.Create("somehandle", new byte[20], TimeSpan.FromDays(1))); Identifier id = Identifier.Parse(GetMockIdentifier(ProtocolVersion.V20)); rp.EndpointFilter = opendpoint => true; - var requests = rp.CreateRequests(id, RPRealmUri, RPUri); + var requests = await rp.CreateRequestsAsync(id, RPRealmUri, RPUri); Assert.AreEqual(1, requests.Count()); rp.EndpointFilter = opendpoint => false; - requests = rp.CreateRequests(id, RPRealmUri, RPUri); + requests = await rp.CreateRequestsAsync(id, RPRealmUri, RPUri); Assert.AreEqual(0, requests.Count()); } [Test, ExpectedException(typeof(ProtocolException))] - public void CreateRequestOnNonOpenID() { - Uri nonOpenId = new Uri("http://www.microsoft.com/"); + public async Task CreateRequestOnNonOpenID() { + var nonOpenId = new Uri("http://www.microsoft.com/"); + Handle(nonOpenId).By("<html/>", "text/html"); var rp = this.CreateRelyingParty(); - this.MockResponder.RegisterMockResponse(nonOpenId, "text/html", "<html/>"); - rp.CreateRequest(nonOpenId, RPRealmUri, RPUri); + await rp.CreateRequestAsync(nonOpenId, RPRealmUri, RPUri); } [Test] - public void CreateRequestsOnNonOpenID() { - Uri nonOpenId = new Uri("http://www.microsoft.com/"); + public async Task CreateRequestsOnNonOpenID() { + var nonOpenId = new Uri("http://www.microsoft.com/"); + Handle(nonOpenId).By("<html/>", "text/html"); var rp = this.CreateRelyingParty(); - this.MockResponder.RegisterMockResponse(nonOpenId, "text/html", "<html/>"); - var requests = rp.CreateRequests(nonOpenId, RPRealmUri, RPUri); + var requests = await rp.CreateRequestsAsync(nonOpenId, RPRealmUri, RPUri); Assert.AreEqual(0, requests.Count()); } @@ -100,25 +108,32 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// OPs that are not approved by <see cref="OpenIdRelyingParty.EndpointFilter"/>. /// </summary> [Test] - public void AssertionWithEndpointFilter() { - var coordinator = new OpenIdCoordinator( - rp => { - // register with RP so that id discovery passes - rp.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler; + public async Task AssertionWithEndpointFilter() { + var opStore = new StandardProviderApplicationStore(); + Handle(RPUri).By( + async req => { + var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore(), this.HostFactories); // Rig it to always deny the incoming OP rp.EndpointFilter = op => false; // Receive the unsolicited assertion - var response = rp.GetResponse(); + var response = await rp.GetResponseAsync(req); + Assert.That(response, Is.Not.Null); Assert.AreEqual(AuthenticationStatus.Failed, response.Status); - }, - op => { - Identifier id = GetMockIdentifier(ProtocolVersion.V20); - op.SendUnsolicitedAssertion(OPUri, GetMockRealm(false), id, id); - AutoProvider(op); + return new HttpResponseMessage(); }); - coordinator.Run(); + this.RegisterAutoProvider(); + { + var op = new OpenIdProvider(opStore, this.HostFactories); + Identifier id = GetMockIdentifier(ProtocolVersion.V20); + var assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, GetMockRealm(false), id, id); + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(assertion.Headers.Location)) { + response.EnsureSuccessStatusCode(); + } + } + } } } } diff --git a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs index 91318f5..6ce74fd 100644 --- a/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/PositiveAuthenticationResponseTests.cs @@ -7,6 +7,9 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { using System; using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; @@ -29,12 +32,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies good, positive assertions are accepted. /// </summary> [Test] - public void Valid() { + public async Task Valid() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); ClaimsResponse extension = new ClaimsResponse(); assertion.Extensions.Add(extension); var rp = CreateRelyingParty(); - var authResponse = new PositiveAuthenticationResponse(assertion, rp); + var authResponse = await PositiveAuthenticationResponse.CreateAsync(assertion, rp, CancellationToken.None); Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status); Assert.IsNull(authResponse.Exception); Assert.AreEqual((string)assertion.ClaimedIdentifier, (string)authResponse.ClaimedIdentifier); @@ -49,13 +52,13 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that discovery verification of a positive assertion can match a dual identifier. /// </summary> [Test] - public void DualIdentifierMatchesInAssertionVerification() { + public async Task DualIdentifierMatchesInAssertionVerification() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(true); ClaimsResponse extension = new ClaimsResponse(); assertion.Extensions.Add(extension); var rp = CreateRelyingParty(); rp.SecuritySettings.AllowDualPurposeIdentifiers = true; - new PositiveAuthenticationResponse(assertion, rp); // this will throw if it fails to find a match + await PositiveAuthenticationResponse.CreateAsync(assertion, rp, CancellationToken.None); // this will throw if it fails to find a match } /// <summary> @@ -63,12 +66,12 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// if the default settings are in place. /// </summary> [Test, ExpectedException(typeof(ProtocolException))] - public void DualIdentifierNoMatchInAssertionVerificationByDefault() { + public async Task DualIdentifierNoMatchInAssertionVerificationByDefault() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(true); ClaimsResponse extension = new ClaimsResponse(); assertion.Extensions.Add(extension); var rp = CreateRelyingParty(); - new PositiveAuthenticationResponse(assertion, rp); // this will throw if it fails to find a match + await PositiveAuthenticationResponse.CreateAsync(assertion, rp, CancellationToken.None); // this will throw if it fails to find a match } /// <summary> @@ -77,11 +80,11 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// that the OP has no authority to assert positively regarding. /// </summary> [Test, ExpectedException(typeof(ProtocolException))] - public void SpoofedClaimedIdDetectionSolicited() { + public async Task SpoofedClaimedIdDetectionSolicited() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); assertion.ProviderEndpoint = new Uri("http://rogueOP"); var rp = CreateRelyingParty(); - var authResponse = new PositiveAuthenticationResponse(assertion, rp); + var authResponse = await PositiveAuthenticationResponse.CreateAsync(assertion, rp, CancellationToken.None); Assert.AreEqual(AuthenticationStatus.Failed, authResponse.Status); } @@ -90,22 +93,22 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Cdentifiers when RequireSsl is set to true. /// </summary> [Test, ExpectedException(typeof(ProtocolException))] - public void InsecureIdentifiersRejectedWithRequireSsl() { + public async Task InsecureIdentifiersRejectedWithRequireSsl() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); var rp = CreateRelyingParty(); rp.SecuritySettings.RequireSsl = true; - var authResponse = new PositiveAuthenticationResponse(assertion, rp); + var authResponse = await PositiveAuthenticationResponse.CreateAsync(assertion, rp, CancellationToken.None); } [Test] - public void GetCallbackArguments() { + public async Task GetCallbackArguments() { PositiveAssertionResponse assertion = this.GetPositiveAssertion(); var rp = CreateRelyingParty(); UriBuilder returnToBuilder = new UriBuilder(assertion.ReturnTo); returnToBuilder.AppendQueryArgs(new Dictionary<string, string> { { "a", "b" } }); assertion.ReturnTo = returnToBuilder.Uri; - var authResponse = new PositiveAuthenticationResponse(assertion, rp); + var authResponse = await PositiveAuthenticationResponse.CreateAsync(assertion, rp, CancellationToken.None); // First pretend that the return_to args were signed. assertion.ReturnToParametersSignatureValidated = true; @@ -124,18 +127,18 @@ namespace DotNetOpenAuth.Test.OpenId.RelyingParty { /// Verifies that certain problematic claimed identifiers pass through to the RP response correctly. /// </summary> [Test] - public void ProblematicClaimedId() { + public async Task ProblematicClaimedId() { var providerEndpoint = new ProviderEndpointDescription(OpenIdTestBase.OPUri, Protocol.Default.Version); string claimed_id = BaseMockUri + "a./b."; var se = IdentifierDiscoveryResult.CreateForClaimedIdentifier(claimed_id, claimed_id, providerEndpoint, null, null); - UriIdentifier identityUri = (UriIdentifier)se.ClaimedIdentifier; - var mockId = new MockIdentifier(identityUri, this.MockResponder, new IdentifierDiscoveryResult[] { se }); + var identityUri = (UriIdentifier)se.ClaimedIdentifier; + this.RegisterMockXrdsResponse(se); + var rp = this.CreateRelyingParty(); var positiveAssertion = this.GetPositiveAssertion(); - positiveAssertion.ClaimedIdentifier = mockId; - positiveAssertion.LocalIdentifier = mockId; - var rp = CreateRelyingParty(); - var authResponse = new PositiveAuthenticationResponse(positiveAssertion, rp); + positiveAssertion.ClaimedIdentifier = claimed_id; + positiveAssertion.LocalIdentifier = claimed_id; + var authResponse = await PositiveAuthenticationResponse.CreateAsync(positiveAssertion, rp, CancellationToken.None); Assert.AreEqual(AuthenticationStatus.Authenticated, authResponse.Status); Assert.AreEqual(claimed_id, authResponse.ClaimedIdentifier.ToString()); } diff --git a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs index b6a52a7..465fd23 100644 --- a/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs +++ b/src/DotNetOpenAuth.Test/OpenId/UriIdentifierTests.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Test.OpenId { using System; using System.Linq; using System.Net; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OpenId; @@ -243,7 +244,7 @@ namespace DotNetOpenAuth.Test.OpenId { } [Test] - public void TryRequireSslAdjustsIdentifier() { + public async Task TryRequireSslAdjustsIdentifier() { Identifier secureId; // Try Parse and ctor without explicit scheme var id = Identifier.Parse("www.yahoo.com"); @@ -263,13 +264,13 @@ namespace DotNetOpenAuth.Test.OpenId { Assert.IsFalse(id.TryRequireSsl(out secureId)); Assert.IsTrue(secureId.IsDiscoverySecureEndToEnd, "Although the TryRequireSsl failed, the created identifier should retain the Ssl status."); Assert.AreEqual("http://www.yahoo.com/", secureId.ToString()); - Assert.AreEqual(0, Discover(secureId).Count(), "Since TryRequireSsl failed, the created Identifier should never discover anything."); + Assert.AreEqual(0, (await DiscoverAsync(secureId)).Count(), "Since TryRequireSsl failed, the created Identifier should never discover anything."); id = new UriIdentifier("http://www.yahoo.com"); Assert.IsFalse(id.TryRequireSsl(out secureId)); Assert.IsTrue(secureId.IsDiscoverySecureEndToEnd); Assert.AreEqual("http://www.yahoo.com/", secureId.ToString()); - Assert.AreEqual(0, Discover(secureId).Count()); + Assert.AreEqual(0, (await DiscoverAsync(secureId)).Count()); } /// <summary> diff --git a/src/DotNetOpenAuth.Test/TestBase.cs b/src/DotNetOpenAuth.Test/TestBase.cs index 92adafa..4758b7d 100644 --- a/src/DotNetOpenAuth.Test/TestBase.cs +++ b/src/DotNetOpenAuth.Test/TestBase.cs @@ -7,7 +7,12 @@ namespace DotNetOpenAuth.Test { using System; using System.IO; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Reflection; + using System.Threading; + using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth.Messages; @@ -16,6 +21,8 @@ namespace DotNetOpenAuth.Test { using log4net; using NUnit.Framework; + using log4net.Config; + /// <summary> /// The base class that all test classes inherit from. /// </summary> @@ -48,14 +55,17 @@ namespace DotNetOpenAuth.Test { get { return this.messageDescriptions; } } + internal MockingHostFactories HostFactories; + /// <summary> /// The TestInitialize method for the test cases. /// </summary> [SetUp] public virtual void SetUp() { - log4net.Config.XmlConfigurator.Configure(Assembly.GetExecutingAssembly().GetManifestResourceStream("DotNetOpenAuth.Test.Logging.config")); + XmlConfigurator.Configure(Assembly.GetExecutingAssembly().GetManifestResourceStream("DotNetOpenAuth.Test.Logging.config")); MessageBase.LowSecurityMode = true; this.messageDescriptions = new MessageDescriptionCollection(); + this.HostFactories = new MockingHostFactories(); SetMockHttpContext(); } @@ -64,10 +74,10 @@ namespace DotNetOpenAuth.Test { /// </summary> [TearDown] public virtual void Cleanup() { - log4net.LogManager.Shutdown(); + LogManager.Shutdown(); } - internal static Stats MeasurePerformance(Action action, float maximumAllowedUnitTime, int samples = 10, int iterations = 100, string name = null) { + internal static Stats MeasurePerformance(Func<Task> action, float maximumAllowedUnitTime, int samples = 10, int iterations = 100, string name = null) { if (!PerformanceTestUtilities.IsOptimized(typeof(OpenIdRelyingParty).Assembly)) { Assert.Inconclusive("Unoptimized code."); } @@ -75,7 +85,7 @@ namespace DotNetOpenAuth.Test { var timer = new MultiSampleCodeTimer(samples, iterations); Stats stats; using (new HighPerformance()) { - stats = timer.Measure(name ?? TestContext.CurrentContext.Test.FullName, action); + stats = timer.Measure(name ?? TestContext.CurrentContext.Test.FullName, () => action().Wait()); } stats.AdjustForScale(PerformanceTestUtilities.Baseline.Median); @@ -103,5 +113,49 @@ namespace DotNetOpenAuth.Test { new HttpRequest("mock", "http://mock", "mock"), new HttpResponse(new StringWriter())); } + + protected internal Handler Handle(string uri) { + return new Handler(this, new Uri(uri)); + } + + protected internal Handler Handle(Uri uri) { + return new Handler(this, uri); + } + + protected internal struct Handler { + private TestBase test; + + internal Handler(TestBase test, Uri uri) + : this() { + this.test = test; + this.Uri = uri; + } + + internal Uri Uri { get; private set; } + + internal Func<HttpRequestMessage, Task<HttpResponseMessage>> MessageHandler { get; private set; } + + internal void By(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) { + this.test.HostFactories.Handlers[this.Uri] = req => handler(req, CancellationToken.None); + } + + internal void By(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler) { + this.test.HostFactories.Handlers[this.Uri] = handler; + } + + internal void By(Func<HttpRequestMessage, HttpResponseMessage> handler) { + this.By(req => Task.FromResult(handler(req))); + } + + internal void By(string responseContent, string contentType, HttpStatusCode statusCode = HttpStatusCode.OK) { + this.By( + req => { + var response = new HttpResponseMessage(statusCode); + response.Content = new StringContent(responseContent); + response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + return response; + }); + } + } } } diff --git a/src/DotNetOpenAuth.Test/packages.config b/src/DotNetOpenAuth.Test/packages.config index 38e70d7..cab5101 100644 --- a/src/DotNetOpenAuth.Test/packages.config +++ b/src/DotNetOpenAuth.Test/packages.config @@ -3,5 +3,5 @@ <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> <package id="Moq" version="4.0.10827" targetFramework="net45" /> <package id="NUnit" version="2.6.1" targetFramework="net45" /> - <package id="Validation" version="2.0.1.12362" targetFramework="net45" /> + <package id="Validation" version="2.0.2.13022" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx b/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx index ca23eac..70dc9af 100644 --- a/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx +++ b/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx @@ -1,23 +1,67 @@ <%@ WebHandler Language="C#" Class="OpenIdProviderEndpoint" %> using System; +using System.Threading; +using System.Threading.Tasks; using System.Web; using DotNetOpenAuth.OpenId.Provider; -public class OpenIdProviderEndpoint : IHttpHandler { +using DotNetOpenAuth.Messaging; + +public class OpenIdProviderEndpoint : IHttpAsyncHandler { + public bool IsReusable { + get { return true; } + } + + public IAsyncResult BeginProcessRequest(HttpContext context, System.AsyncCallback cb, object extraData) { + return ToApm(this.ProcessRequestAsync(context), cb, extraData); + } + + public void EndProcessRequest(IAsyncResult result) { + ((Task)result).Wait(); // rethrows exceptions + } + public void ProcessRequest(HttpContext context) { + this.ProcessRequestAsync(context).GetAwaiter().GetResult(); + } + + private static Task ToApm(Task task, AsyncCallback callback, object state) { + if (task == null) { + throw new ArgumentNullException("task"); + } + + var tcs = new TaskCompletionSource<object>(state); + task.ContinueWith( + t => { + if (t.IsFaulted) { + tcs.TrySetException(t.Exception.InnerExceptions); + } else if (t.IsCanceled) { + tcs.TrySetCanceled(); + } else { + tcs.TrySetResult(null); + } + + if (callback != null) { + callback(tcs.Task); + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + + return tcs.Task; + } + + private async Task ProcessRequestAsync(HttpContext context) { OpenIdProvider provider = new OpenIdProvider(); - IRequest request = provider.GetRequest(); + IRequest request = await provider.GetRequestAsync(new HttpRequestWrapper(context.Request), context.Response.ClientDisconnectedToken); if (request != null) { if (!request.IsResponseReady) { IAuthenticationRequest authRequest = (IAuthenticationRequest)request; authRequest.IsAuthenticated = true; } - provider.Respond(request); + var response = await provider.PrepareResponseAsync(request, context.Response.ClientDisconnectedToken); + await response.SendAsync(new HttpContextWrapper(context), context.Response.ClientDisconnectedToken); } } - - public bool IsReusable { - get { return true; } - } }
\ No newline at end of file diff --git a/src/DotNetOpenAuth.TestWeb/Web.config b/src/DotNetOpenAuth.TestWeb/Web.config index 8c78f44..0a8b44c 100644 --- a/src/DotNetOpenAuth.TestWeb/Web.config +++ b/src/DotNetOpenAuth.TestWeb/Web.config @@ -25,7 +25,19 @@ affects performance, set this value to true only during development. --> - <compilation debug="true" targetFramework="4.5"/> + <compilation debug="true" targetFramework="4.5"> + <assemblies> + <add assembly="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add assembly="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add assembly="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add assembly="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> + <add assembly="System.Net.Http.WebRequest, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> + </assemblies> + </compilation> <!-- The <authentication> section enables configuration of the security authentication mode used by diff --git a/src/DotNetOpenAuth.TestWeb/packages.config b/src/DotNetOpenAuth.TestWeb/packages.config new file mode 100644 index 0000000..c527bd3 --- /dev/null +++ b/src/DotNetOpenAuth.TestWeb/packages.config @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> + <package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.Razor" version="2.0.20715.0" targetFramework="net45" /> + <package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> + <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/src/DotNetOpenAuth.sln b/src/DotNetOpenAuth.sln index c56772f..2def580 100644 --- a/src/DotNetOpenAuth.sln +++ b/src/DotNetOpenAuth.sln @@ -219,6 +219,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth.Common EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetOpenAuth.OAuth2.ClientAuthorization", "DotNetOpenAuth.OAuth2.ClientAuthorization\DotNetOpenAuth.OAuth2.ClientAuthorization.csproj", "{CCF3728A-B3D7-404A-9BC6-75197135F2D7}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuth2ProtectedWebApi", "..\samples\OAuth2ProtectedWebApi\OAuth2ProtectedWebApi.csproj", "{58A3721F-5B5C-4CA7-BE39-91640B5B4924}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution CodeAnalysis|Any CPU = CodeAnalysis|Any CPU @@ -503,6 +505,12 @@ Global {CCF3728A-B3D7-404A-9BC6-75197135F2D7}.Debug|Any CPU.Build.0 = Debug|Any CPU {CCF3728A-B3D7-404A-9BC6-75197135F2D7}.Release|Any CPU.ActiveCfg = Release|Any CPU {CCF3728A-B3D7-404A-9BC6-75197135F2D7}.Release|Any CPU.Build.0 = Release|Any CPU + {58A3721F-5B5C-4CA7-BE39-91640B5B4924}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU + {58A3721F-5B5C-4CA7-BE39-91640B5B4924}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU + {58A3721F-5B5C-4CA7-BE39-91640B5B4924}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {58A3721F-5B5C-4CA7-BE39-91640B5B4924}.Debug|Any CPU.Build.0 = Debug|Any CPU + {58A3721F-5B5C-4CA7-BE39-91640B5B4924}.Release|Any CPU.ActiveCfg = Release|Any CPU + {58A3721F-5B5C-4CA7-BE39-91640B5B4924}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -526,6 +534,7 @@ Global {9529606E-AF76-4387-BFB7-3D10A5B399AA} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6} {E135F455-0669-49F8-9207-07FCA8C8FC79} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6} {C78E8235-1D46-43EB-A912-80B522C4E9AE} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6} + {58A3721F-5B5C-4CA7-BE39-91640B5B4924} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6} {6EB90284-BD15-461C-BBF2-131CF55F7C8B} = {8A5CEDB9-7F8A-4BE2-A1B9-97130F453277} {5C65603B-235F-47E6-B536-06385C60DE7F} = {E9ED920D-1F83-48C0-9A4B-09CCE505FE6D} {A78F8FC6-7B03-4230-BE41-761E400D6810} = {B9EB8729-4B54-4453-B089-FE6761BA3057} diff --git a/src/packages/repositories.config b/src/packages/repositories.config index c6a74f3..0d28c5f 100644 --- a/src/packages/repositories.config +++ b/src/packages/repositories.config @@ -3,6 +3,8 @@ <repository path="..\..\projecttemplates\MvcRelyingParty\packages.config" /> <repository path="..\..\projecttemplates\RelyingPartyLogic\packages.config" /> <repository path="..\..\projecttemplates\WebFormsRelyingParty\packages.config" /> + <repository path="..\..\samples\DotNetOpenAuth.ApplicationBlock\packages.config" /> + <repository path="..\..\samples\OAuth2ProtectedWebApi\packages.config" /> <repository path="..\..\samples\OAuthAuthorizationServer\packages.config" /> <repository path="..\..\samples\OAuthClient\packages.config" /> <repository path="..\..\samples\OAuthConsumer\packages.config" /> @@ -10,9 +12,13 @@ <repository path="..\..\samples\OAuthResourceServer\packages.config" /> <repository path="..\..\samples\OAuthServiceProvider\packages.config" /> <repository path="..\..\samples\OpenIdOfflineProvider\packages.config" /> + <repository path="..\..\samples\OpenIdProviderMvc\packages.config" /> <repository path="..\..\samples\OpenIdProviderWebForms\packages.config" /> + <repository path="..\..\samples\OpenIdRelyingPartyMvc\packages.config" /> <repository path="..\..\samples\OpenIdRelyingPartyWebForms\packages.config" /> <repository path="..\..\samples\OpenIdRelyingPartyWebFormsVB\packages.config" /> + <repository path="..\..\samples\OpenIdWebRingSsoProvider\packages.config" /> + <repository path="..\..\samples\OpenIdWebRingSsoRelyingParty\packages.config" /> <repository path="..\DotNetOpenAuth.AspNet.Test\packages.config" /> <repository path="..\DotNetOpenAuth.AspNet\packages.config" /> <repository path="..\DotNetOpenAuth.Core.UI\packages.config" /> @@ -38,4 +44,5 @@ <repository path="..\DotNetOpenAuth.OpenIdInfoCard.UI\packages.config" /> <repository path="..\DotNetOpenAuth.OpenIdOAuth\packages.config" /> <repository path="..\DotNetOpenAuth.Test\packages.config" /> + <repository path="..\DotNetOpenAuth.TestWeb\packages.config" /> </repositories>
\ No newline at end of file diff --git a/tools/DotNetOpenAuth.Versioning.targets b/tools/DotNetOpenAuth.Versioning.targets index 0105071..4e654bf 100644 --- a/tools/DotNetOpenAuth.Versioning.targets +++ b/tools/DotNetOpenAuth.Versioning.targets @@ -6,6 +6,7 @@ <PropertyGroup> <VersionCsFile>$(IntermediatePath)\$(AssemblyName).Version.cs</VersionCsFile> <NoWarn>$(NoWarn);1607</NoWarn> + <UltimateResourceFallbackLocation Condition=" '$(UltimateResourceFallbackLocation)' == '' ">UltimateResourceFallbackLocation.MainAssembly</UltimateResourceFallbackLocation> </PropertyGroup> <UsingTask AssemblyFile="$(ProjectRoot)lib\MSBuild.Community.Tasks.dll" TaskName="AssemblyInfo"/> @@ -52,7 +53,7 @@ AssemblyTitle="$(AssemblyName)" AssemblyProduct="DotNetOpenAuth" NeutralResourcesLanguage="en-US" - UltimateResourceFallbackLocation="UltimateResourceFallbackLocation.MainAssembly" + UltimateResourceFallbackLocation="$(UltimateResourceFallbackLocation)" GenerateClass="true" /> <!-- Avoid applying the newly generated AssemblyInfo.cs file to the build unless it has changed in order to allow for incremental building. --> |