├── .gitattributes ├── .gitignore ├── .vs └── config │ └── applicationhost.config ├── README.md ├── UsingTask.Library ├── PersonRepository.cs ├── Properties │ └── AssemblyInfo.cs ├── UsingTask.Library.csproj └── app.config ├── UsingTask.Service ├── App_Start │ ├── BundleConfig.cs │ ├── FilterConfig.cs │ ├── IdentityConfig.cs │ ├── RouteConfig.cs │ ├── Startup.Auth.cs │ └── WebApiConfig.cs ├── Areas │ └── HelpPage │ │ ├── ApiDescriptionExtensions.cs │ │ ├── App_Start │ │ └── HelpPageConfig.cs │ │ ├── Controllers │ │ └── HelpController.cs │ │ ├── HelpPage.css │ │ ├── HelpPageAreaRegistration.cs │ │ ├── HelpPageConfigurationExtensions.cs │ │ ├── ModelDescriptions │ │ ├── CollectionModelDescription.cs │ │ ├── ComplexTypeModelDescription.cs │ │ ├── DictionaryModelDescription.cs │ │ ├── EnumTypeModelDescription.cs │ │ ├── EnumValueDescription.cs │ │ ├── IModelDocumentationProvider.cs │ │ ├── KeyValuePairModelDescription.cs │ │ ├── ModelDescription.cs │ │ ├── ModelDescriptionGenerator.cs │ │ ├── ModelNameAttribute.cs │ │ ├── ModelNameHelper.cs │ │ ├── ParameterAnnotation.cs │ │ ├── ParameterDescription.cs │ │ └── SimpleTypeModelDescription.cs │ │ ├── Models │ │ └── HelpPageApiModel.cs │ │ ├── SampleGeneration │ │ ├── HelpPageSampleGenerator.cs │ │ ├── HelpPageSampleKey.cs │ │ ├── ImageSample.cs │ │ ├── InvalidSample.cs │ │ ├── ObjectGenerator.cs │ │ ├── SampleDirection.cs │ │ └── TextSample.cs │ │ ├── Views │ │ ├── Help │ │ │ ├── Api.cshtml │ │ │ ├── DisplayTemplates │ │ │ │ ├── ApiGroup.cshtml │ │ │ │ ├── CollectionModelDescription.cshtml │ │ │ │ ├── ComplexTypeModelDescription.cshtml │ │ │ │ ├── DictionaryModelDescription.cshtml │ │ │ │ ├── EnumTypeModelDescription.cshtml │ │ │ │ ├── HelpPageApiModel.cshtml │ │ │ │ ├── ImageSample.cshtml │ │ │ │ ├── InvalidSample.cshtml │ │ │ │ ├── KeyValuePairModelDescription.cshtml │ │ │ │ ├── ModelDescriptionLink.cshtml │ │ │ │ ├── Parameters.cshtml │ │ │ │ ├── Samples.cshtml │ │ │ │ ├── SimpleTypeModelDescription.cshtml │ │ │ │ └── TextSample.cshtml │ │ │ ├── Index.cshtml │ │ │ └── ResourceModel.cshtml │ │ ├── Shared │ │ │ └── _Layout.cshtml │ │ ├── Web.config │ │ └── _ViewStart.cshtml │ │ └── XmlDocumentationProvider.cs ├── Content │ ├── Site.css │ ├── bootstrap.css │ └── bootstrap.min.css ├── Controllers │ ├── AccountController.cs │ ├── HomeController.cs │ ├── PeopleController.cs │ └── ValuesController.cs ├── Global.asax ├── Global.asax.cs ├── Models │ ├── AccountBindingModels.cs │ ├── AccountViewModels.cs │ └── IdentityModels.cs ├── Project_Readme.html ├── Properties │ └── AssemblyInfo.cs ├── Providers │ └── ApplicationOAuthProvider.cs ├── Results │ └── ChallengeResult.cs ├── Scripts │ ├── _references.js │ ├── bootstrap.js │ ├── bootstrap.min.js │ ├── jquery-1.10.2.intellisense.js │ ├── jquery-1.10.2.js │ ├── jquery-1.10.2.min.js │ ├── jquery-1.10.2.min.map │ ├── jquery.validate-vsdoc.js │ ├── jquery.validate.js │ ├── jquery.validate.min.js │ ├── jquery.validate.unobtrusive.js │ ├── jquery.validate.unobtrusive.min.js │ ├── modernizr-2.6.2.js │ ├── respond.js │ └── respond.min.js ├── Startup.cs ├── UsingTask.Service.csproj ├── Views │ ├── Home │ │ └── Index.cshtml │ ├── Shared │ │ ├── Error.cshtml │ │ └── _Layout.cshtml │ ├── Web.config │ └── _ViewStart.cshtml ├── Web.Debug.config ├── Web.Release.config ├── Web.config ├── favicon.ico ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.svg │ ├── glyphicons-halflings-regular.ttf │ └── glyphicons-halflings-regular.woff └── packages.config ├── UsingTask.Shared ├── People.cs ├── Person.cs ├── Properties │ └── AssemblyInfo.cs └── UsingTask.Shared.csproj ├── UsingTask.Tester ├── App.config ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── UsingTask.Tester.csproj ├── UsingTask.UI ├── App.config ├── App.xaml ├── App.xaml.cs ├── Converters.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings └── UsingTask.UI.csproj └── UsingTask.sln /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # Build results 11 | [Dd]ebug/ 12 | [Dd]ebugPublic/ 13 | [Rr]elease/ 14 | [Rr]eleases/ 15 | x64/ 16 | x86/ 17 | build/ 18 | bld/ 19 | [Bb]in/ 20 | [Oo]bj/ 21 | 22 | # Roslyn cache directories 23 | *.ide/ 24 | 25 | # MSTest test Results 26 | [Tt]est[Rr]esult*/ 27 | [Bb]uild[Ll]og.* 28 | 29 | #NUNIT 30 | *.VisualState.xml 31 | TestResult.xml 32 | 33 | # Build Results of an ATL Project 34 | [Dd]ebugPS/ 35 | [Rr]eleasePS/ 36 | dlldata.c 37 | 38 | *_i.c 39 | *_p.c 40 | *_i.h 41 | *.ilk 42 | *.meta 43 | *.obj 44 | *.pch 45 | *.pdb 46 | *.pgc 47 | *.pgd 48 | *.rsp 49 | *.sbr 50 | *.tlb 51 | *.tli 52 | *.tlh 53 | *.tmp 54 | *.tmp_proj 55 | *.log 56 | *.vspscc 57 | *.vssscc 58 | .builds 59 | *.pidb 60 | *.svclog 61 | *.scc 62 | 63 | # Chutzpah Test files 64 | _Chutzpah* 65 | 66 | # Visual C++ cache files 67 | ipch/ 68 | *.aps 69 | *.ncb 70 | *.opensdf 71 | *.sdf 72 | *.cachefile 73 | 74 | # Visual Studio profiler 75 | *.psess 76 | *.vsp 77 | *.vspx 78 | 79 | # TFS 2012 Local Workspace 80 | $tf/ 81 | 82 | # Guidance Automation Toolkit 83 | *.gpState 84 | 85 | # ReSharper is a .NET coding add-in 86 | _ReSharper*/ 87 | *.[Rr]e[Ss]harper 88 | *.DotSettings.user 89 | 90 | # JustCode is a .NET coding addin-in 91 | .JustCode 92 | 93 | # TeamCity is a build add-in 94 | _TeamCity* 95 | 96 | # DotCover is a Code Coverage Tool 97 | *.dotCover 98 | 99 | # NCrunch 100 | _NCrunch_* 101 | .*crunch*.local.xml 102 | 103 | # MightyMoose 104 | *.mm.* 105 | AutoTest.Net/ 106 | 107 | # Web workbench (sass) 108 | .sass-cache/ 109 | 110 | # Installshield output folder 111 | [Ee]xpress/ 112 | 113 | # DocProject is a documentation generator add-in 114 | DocProject/buildhelp/ 115 | DocProject/Help/*.HxT 116 | DocProject/Help/*.HxC 117 | DocProject/Help/*.hhc 118 | DocProject/Help/*.hhk 119 | DocProject/Help/*.hhp 120 | DocProject/Help/Html2 121 | DocProject/Help/html 122 | 123 | # Click-Once directory 124 | publish/ 125 | 126 | # Publish Web Output 127 | *.[Pp]ublish.xml 128 | *.azurePubxml 129 | # TODO: Comment the next line if you want to checkin your web deploy settings 130 | # but database connection strings (with potential passwords) will be unencrypted 131 | *.pubxml 132 | *.publishproj 133 | 134 | # NuGet Packages 135 | *.nupkg 136 | # The packages folder can be ignored because of Package Restore 137 | **/packages/* 138 | # except build/, which is used as an MSBuild target. 139 | !**/packages/build/ 140 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 141 | #!**/packages/repositories.config 142 | 143 | # Windows Azure Build Output 144 | csx/ 145 | *.build.csdef 146 | 147 | # Windows Store app package directory 148 | AppPackages/ 149 | 150 | # Others 151 | *.Cache 152 | ClientBin/ 153 | [Ss]tyle[Cc]op.* 154 | ~$* 155 | *~ 156 | *.dbmdl 157 | *.dbproj.schemaview 158 | *.pfx 159 | *.publishsettings 160 | node_modules/ 161 | bower_components/ 162 | 163 | # RIA/Silverlight projects 164 | Generated_Code/ 165 | 166 | # Backup & report files from converting an old project file 167 | # to a newer Visual Studio version. Backup files are not needed, 168 | # because we have git ;-) 169 | _UpgradeReport_Files/ 170 | Backup*/ 171 | UpgradeLog*.XML 172 | UpgradeLog*.htm 173 | 174 | # SQL Server files 175 | *.mdf 176 | *.ldf 177 | 178 | # Business Intelligence projects 179 | *.rdl.data 180 | *.bim.layout 181 | *.bim_*.settings 182 | 183 | # Microsoft Fakes 184 | FakesAssemblies/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | using-task 2 | ========== 3 | 4 | Sample project to show how to consume async methods / methods that return Task 5 | 6 | Articles discribing the code are collected here: http://www.jeremybytes.com/Downloads.aspx#Tasks 7 | 8 | **Update** 9 | An update of these code samples using .NET Core 3.1 is available here: [using-task-core3](https://github.com/jeremybytes/using-task-core3). 10 | -------------------------------------------------------------------------------- /UsingTask.Library/PersonRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using UsingTask.Shared; 9 | 10 | namespace UsingTask.Library 11 | { 12 | public class PersonRepository 13 | { 14 | public async Task> Get( 15 | CancellationToken cancellationToken = new CancellationToken()) 16 | { 17 | await Task.Delay(3000); 18 | 19 | cancellationToken.ThrowIfCancellationRequested(); 20 | 21 | // Uncomment to test exception handling in calling code 22 | //throw new NotImplementedException("Get operation not implemented"); 23 | 24 | using (var client = new HttpClient()) 25 | { 26 | InitializeClient(client); 27 | HttpResponseMessage response = await client.GetAsync("api/people", cancellationToken); 28 | if (response.IsSuccessStatusCode) 29 | { 30 | return await response.Content.ReadAsAsync>(); 31 | } 32 | return new List(); 33 | } 34 | } 35 | 36 | public async Task Get(int id) 37 | { 38 | using (var client = new HttpClient()) 39 | { 40 | InitializeClient(client); 41 | HttpResponseMessage response = await client.GetAsync("api/people/" + id); 42 | if (response.IsSuccessStatusCode) 43 | { 44 | return await response.Content.ReadAsAsync(); 45 | } 46 | return null; 47 | } 48 | } 49 | 50 | private static void InitializeClient(HttpClient client) 51 | { 52 | client.BaseAddress = new Uri("http://localhost:9874/"); 53 | client.DefaultRequestHeaders.Accept.Add( 54 | new MediaTypeWithQualityHeaderValue("application/json")); 55 | } 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /UsingTask.Library/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("UsingTask.Library")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("UsingTask.Library")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("ef758b0a-0a90-4059-b10e-f15347563294")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /UsingTask.Library/UsingTask.Library.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {ABC241BA-6178-4BA1-B34D-A54EFF9627ED} 8 | Library 9 | Properties 10 | UsingTask.Library 11 | UsingTask.Library 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | {289562d7-3faf-4415-b060-0f88e2854687} 52 | UsingTask.Service 53 | 54 | 55 | {fd4c17ee-177c-4e2a-b22d-f62f350f3da5} 56 | UsingTask.Shared 57 | 58 | 59 | 60 | 67 | -------------------------------------------------------------------------------- /UsingTask.Library/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /UsingTask.Service/App_Start/BundleConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Optimization; 3 | 4 | namespace UsingTask.Service 5 | { 6 | public class BundleConfig 7 | { 8 | // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 9 | public static void RegisterBundles(BundleCollection bundles) 10 | { 11 | bundles.Add(new ScriptBundle("~/bundles/jquery").Include( 12 | "~/Scripts/jquery-{version}.js")); 13 | 14 | // Use the development version of Modernizr to develop with and learn from. Then, when you're 15 | // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. 16 | bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( 17 | "~/Scripts/modernizr-*")); 18 | 19 | bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( 20 | "~/Scripts/bootstrap.js", 21 | "~/Scripts/respond.js")); 22 | 23 | bundles.Add(new StyleBundle("~/Content/css").Include( 24 | "~/Content/bootstrap.css", 25 | "~/Content/site.css")); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /UsingTask.Service/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Mvc; 3 | 4 | namespace UsingTask.Service 5 | { 6 | public class FilterConfig 7 | { 8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 | { 10 | filters.Add(new HandleErrorAttribute()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /UsingTask.Service/App_Start/IdentityConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNet.Identity; 3 | using Microsoft.AspNet.Identity.EntityFramework; 4 | using Microsoft.AspNet.Identity.Owin; 5 | using Microsoft.Owin; 6 | using UsingTask.Service.Models; 7 | 8 | namespace UsingTask.Service 9 | { 10 | // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. 11 | 12 | public class ApplicationUserManager : UserManager 13 | { 14 | public ApplicationUserManager(IUserStore store) 15 | : base(store) 16 | { 17 | } 18 | 19 | public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) 20 | { 21 | var manager = new ApplicationUserManager(new UserStore(context.Get())); 22 | // Configure validation logic for usernames 23 | manager.UserValidator = new UserValidator(manager) 24 | { 25 | AllowOnlyAlphanumericUserNames = false, 26 | RequireUniqueEmail = true 27 | }; 28 | // Configure validation logic for passwords 29 | manager.PasswordValidator = new PasswordValidator 30 | { 31 | RequiredLength = 6, 32 | RequireNonLetterOrDigit = true, 33 | RequireDigit = true, 34 | RequireLowercase = true, 35 | RequireUppercase = true, 36 | }; 37 | var dataProtectionProvider = options.DataProtectionProvider; 38 | if (dataProtectionProvider != null) 39 | { 40 | manager.UserTokenProvider = new DataProtectorTokenProvider(dataProtectionProvider.Create("ASP.NET Identity")); 41 | } 42 | return manager; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /UsingTask.Service/App_Start/RouteConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | using System.Web.Routing; 7 | 8 | namespace UsingTask.Service 9 | { 10 | public class RouteConfig 11 | { 12 | public static void RegisterRoutes(RouteCollection routes) 13 | { 14 | routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 15 | 16 | routes.MapRoute( 17 | name: "Default", 18 | url: "{controller}/{action}/{id}", 19 | defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 20 | ); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /UsingTask.Service/App_Start/Startup.Auth.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.AspNet.Identity; 5 | using Microsoft.AspNet.Identity.EntityFramework; 6 | using Microsoft.Owin; 7 | using Microsoft.Owin.Security.Cookies; 8 | using Microsoft.Owin.Security.Google; 9 | using Microsoft.Owin.Security.OAuth; 10 | using Owin; 11 | using UsingTask.Service.Providers; 12 | using UsingTask.Service.Models; 13 | 14 | namespace UsingTask.Service 15 | { 16 | public partial class Startup 17 | { 18 | public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 19 | 20 | public static string PublicClientId { get; private set; } 21 | 22 | // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 23 | public void ConfigureAuth(IAppBuilder app) 24 | { 25 | // Configure the db context and user manager to use a single instance per request 26 | app.CreatePerOwinContext(ApplicationDbContext.Create); 27 | app.CreatePerOwinContext(ApplicationUserManager.Create); 28 | 29 | // Enable the application to use a cookie to store information for the signed in user 30 | // and to use a cookie to temporarily store information about a user logging in with a third party login provider 31 | app.UseCookieAuthentication(new CookieAuthenticationOptions()); 32 | app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 33 | 34 | // Configure the application for OAuth based flow 35 | PublicClientId = "self"; 36 | OAuthOptions = new OAuthAuthorizationServerOptions 37 | { 38 | TokenEndpointPath = new PathString("/Token"), 39 | Provider = new ApplicationOAuthProvider(PublicClientId), 40 | AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 41 | AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 42 | AllowInsecureHttp = true 43 | }; 44 | 45 | // Enable the application to use bearer tokens to authenticate users 46 | app.UseOAuthBearerTokens(OAuthOptions); 47 | 48 | // Uncomment the following lines to enable logging in with third party login providers 49 | //app.UseMicrosoftAccountAuthentication( 50 | // clientId: "", 51 | // clientSecret: ""); 52 | 53 | //app.UseTwitterAuthentication( 54 | // consumerKey: "", 55 | // consumerSecret: ""); 56 | 57 | //app.UseFacebookAuthentication( 58 | // appId: "", 59 | // appSecret: ""); 60 | 61 | //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() 62 | //{ 63 | // ClientId = "", 64 | // ClientSecret = "" 65 | //}); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /UsingTask.Service/App_Start/WebApiConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Web.Http; 6 | using Microsoft.Owin.Security.OAuth; 7 | using Newtonsoft.Json.Serialization; 8 | 9 | namespace UsingTask.Service 10 | { 11 | public static class WebApiConfig 12 | { 13 | public static void Register(HttpConfiguration config) 14 | { 15 | // Web API configuration and services 16 | // Configure Web API to use only bearer token authentication. 17 | config.SuppressDefaultHostAuthentication(); 18 | config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 19 | 20 | // Web API routes 21 | config.MapHttpAttributeRoutes(); 22 | 23 | config.Routes.MapHttpRoute( 24 | name: "DefaultApi", 25 | routeTemplate: "api/{controller}/{id}", 26 | defaults: new { id = RouteParameter.Optional } 27 | ); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ApiDescriptionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Web; 4 | using System.Web.Http.Description; 5 | 6 | namespace UsingTask.Service.Areas.HelpPage 7 | { 8 | public static class ApiDescriptionExtensions 9 | { 10 | /// 11 | /// Generates an URI-friendly ID for the . E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" 12 | /// 13 | /// The . 14 | /// The ID as a string. 15 | public static string GetFriendlyId(this ApiDescription description) 16 | { 17 | string path = description.RelativePath; 18 | string[] urlParts = path.Split('?'); 19 | string localPath = urlParts[0]; 20 | string queryKeyString = null; 21 | if (urlParts.Length > 1) 22 | { 23 | string query = urlParts[1]; 24 | string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; 25 | queryKeyString = String.Join("_", queryKeys); 26 | } 27 | 28 | StringBuilder friendlyPath = new StringBuilder(); 29 | friendlyPath.AppendFormat("{0}-{1}", 30 | description.HttpMethod.Method, 31 | localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); 32 | if (queryKeyString != null) 33 | { 34 | friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); 35 | } 36 | return friendlyPath.ToString(); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/App_Start/HelpPageConfig.cs: -------------------------------------------------------------------------------- 1 | // Uncomment the following to provide samples for PageResult. Must also add the Microsoft.AspNet.WebApi.OData 2 | // package to your project. 3 | ////#define Handle_PageResultOfT 4 | 5 | using System; 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | using System.Diagnostics; 9 | using System.Diagnostics.CodeAnalysis; 10 | using System.Linq; 11 | using System.Net.Http.Headers; 12 | using System.Reflection; 13 | using System.Web; 14 | using System.Web.Http; 15 | #if Handle_PageResultOfT 16 | using System.Web.Http.OData; 17 | #endif 18 | 19 | namespace UsingTask.Service.Areas.HelpPage 20 | { 21 | /// 22 | /// Use this class to customize the Help Page. 23 | /// For example you can set a custom to supply the documentation 24 | /// or you can provide the samples for the requests/responses. 25 | /// 26 | public static class HelpPageConfig 27 | { 28 | [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", 29 | MessageId = "UsingTask.Service.Areas.HelpPage.TextSample.#ctor(System.String)", 30 | Justification = "End users may choose to merge this string with existing localized resources.")] 31 | [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", 32 | MessageId = "bsonspec", 33 | Justification = "Part of a URI.")] 34 | public static void Register(HttpConfiguration config) 35 | { 36 | //// Uncomment the following to use the documentation from XML documentation file. 37 | //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); 38 | 39 | //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. 40 | //// Also, the string arrays will be used for IEnumerable. The sample objects will be serialized into different media type 41 | //// formats by the available formatters. 42 | //config.SetSampleObjects(new Dictionary 43 | //{ 44 | // {typeof(string), "sample string"}, 45 | // {typeof(IEnumerable), new string[]{"sample 1", "sample 2"}} 46 | //}); 47 | 48 | // Extend the following to provide factories for types not handled automatically (those lacking parameterless 49 | // constructors) or for which you prefer to use non-default property values. Line below provides a fallback 50 | // since automatic handling will fail and GeneratePageResult handles only a single type. 51 | #if Handle_PageResultOfT 52 | config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); 53 | #endif 54 | 55 | // Extend the following to use a preset object directly as the sample for all actions that support a media 56 | // type, regardless of the body parameter or return type. The lines below avoid display of binary content. 57 | // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. 58 | config.SetSampleForMediaType( 59 | new TextSample("Binary JSON content. See http://bsonspec.org for details."), 60 | new MediaTypeHeaderValue("application/bson")); 61 | 62 | //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format 63 | //// and have IEnumerable as the body parameter or return type. 64 | //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable)); 65 | 66 | //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" 67 | //// and action named "Put". 68 | //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); 69 | 70 | //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" 71 | //// on the controller named "Values" and action named "Get" with parameter "id". 72 | //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); 73 | 74 | //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent. 75 | //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. 76 | //config.SetActualRequestType(typeof(string), "Values", "Get"); 77 | 78 | //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent. 79 | //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. 80 | //config.SetActualResponseType(typeof(string), "Values", "Post"); 81 | } 82 | 83 | #if Handle_PageResultOfT 84 | private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) 85 | { 86 | if (type.IsGenericType) 87 | { 88 | Type openGenericType = type.GetGenericTypeDefinition(); 89 | if (openGenericType == typeof(PageResult<>)) 90 | { 91 | // Get the T in PageResult 92 | Type[] typeParameters = type.GetGenericArguments(); 93 | Debug.Assert(typeParameters.Length == 1); 94 | 95 | // Create an enumeration to pass as the first parameter to the PageResult constuctor 96 | Type itemsType = typeof(List<>).MakeGenericType(typeParameters); 97 | object items = sampleGenerator.GetSampleObject(itemsType); 98 | 99 | // Fill in the other information needed to invoke the PageResult constuctor 100 | Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; 101 | object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; 102 | 103 | // Call PageResult(IEnumerable items, Uri nextPageLink, long? count) constructor 104 | ConstructorInfo constructor = type.GetConstructor(parameterTypes); 105 | return constructor.Invoke(parameters); 106 | } 107 | } 108 | 109 | return null; 110 | } 111 | #endif 112 | } 113 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Controllers/HelpController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Web.Http; 3 | using System.Web.Mvc; 4 | using UsingTask.Service.Areas.HelpPage.ModelDescriptions; 5 | using UsingTask.Service.Areas.HelpPage.Models; 6 | 7 | namespace UsingTask.Service.Areas.HelpPage.Controllers 8 | { 9 | /// 10 | /// The controller that will handle requests for the help page. 11 | /// 12 | public class HelpController : Controller 13 | { 14 | private const string ErrorViewName = "Error"; 15 | 16 | public HelpController() 17 | : this(GlobalConfiguration.Configuration) 18 | { 19 | } 20 | 21 | public HelpController(HttpConfiguration config) 22 | { 23 | Configuration = config; 24 | } 25 | 26 | public HttpConfiguration Configuration { get; private set; } 27 | 28 | public ActionResult Index() 29 | { 30 | ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); 31 | return View(Configuration.Services.GetApiExplorer().ApiDescriptions); 32 | } 33 | 34 | public ActionResult Api(string apiId) 35 | { 36 | if (!String.IsNullOrEmpty(apiId)) 37 | { 38 | HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); 39 | if (apiModel != null) 40 | { 41 | return View(apiModel); 42 | } 43 | } 44 | 45 | return View(ErrorViewName); 46 | } 47 | 48 | public ActionResult ResourceModel(string modelName) 49 | { 50 | if (!String.IsNullOrEmpty(modelName)) 51 | { 52 | ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator(); 53 | ModelDescription modelDescription; 54 | if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription)) 55 | { 56 | return View(modelDescription); 57 | } 58 | } 59 | 60 | return View(ErrorViewName); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/HelpPage.css: -------------------------------------------------------------------------------- 1 | .help-page h1, 2 | .help-page .h1, 3 | .help-page h2, 4 | .help-page .h2, 5 | .help-page h3, 6 | .help-page .h3, 7 | #body.help-page, 8 | .help-page-table th, 9 | .help-page-table pre, 10 | .help-page-table p { 11 | font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; 12 | } 13 | 14 | .help-page pre.wrapped { 15 | white-space: -moz-pre-wrap; 16 | white-space: -pre-wrap; 17 | white-space: -o-pre-wrap; 18 | white-space: pre-wrap; 19 | } 20 | 21 | .help-page .warning-message-container { 22 | margin-top: 20px; 23 | padding: 0 10px; 24 | color: #525252; 25 | background: #EFDCA9; 26 | border: 1px solid #CCCCCC; 27 | } 28 | 29 | .help-page-table { 30 | width: 100%; 31 | border-collapse: collapse; 32 | text-align: left; 33 | margin: 0px 0px 20px 0px; 34 | border-top: 1px solid #D4D4D4; 35 | } 36 | 37 | .help-page-table th { 38 | text-align: left; 39 | font-weight: bold; 40 | border-bottom: 1px solid #D4D4D4; 41 | padding: 5px 6px 5px 6px; 42 | } 43 | 44 | .help-page-table td { 45 | border-bottom: 1px solid #D4D4D4; 46 | padding: 10px 8px 10px 8px; 47 | vertical-align: top; 48 | } 49 | 50 | .help-page-table pre, 51 | .help-page-table p { 52 | margin: 0px; 53 | padding: 0px; 54 | font-family: inherit; 55 | font-size: 100%; 56 | } 57 | 58 | .help-page-table tbody tr:hover td { 59 | background-color: #F3F3F3; 60 | } 61 | 62 | .help-page a:hover { 63 | background-color: transparent; 64 | } 65 | 66 | .help-page .sample-header { 67 | border: 2px solid #D4D4D4; 68 | background: #00497E; 69 | color: #FFFFFF; 70 | padding: 8px 15px; 71 | border-bottom: none; 72 | display: inline-block; 73 | margin: 10px 0px 0px 0px; 74 | } 75 | 76 | .help-page .sample-content { 77 | display: block; 78 | border-width: 0; 79 | padding: 15px 20px; 80 | background: #FFFFFF; 81 | border: 2px solid #D4D4D4; 82 | margin: 0px 0px 10px 0px; 83 | } 84 | 85 | .help-page .api-name { 86 | width: 40%; 87 | } 88 | 89 | .help-page .api-documentation { 90 | width: 60%; 91 | } 92 | 93 | .help-page .parameter-name { 94 | width: 20%; 95 | } 96 | 97 | .help-page .parameter-documentation { 98 | width: 40%; 99 | } 100 | 101 | .help-page .parameter-type { 102 | width: 20%; 103 | } 104 | 105 | .help-page .parameter-annotations { 106 | width: 20%; 107 | } 108 | 109 | .help-page h1, 110 | .help-page .h1 { 111 | font-size: 36px; 112 | line-height: normal; 113 | } 114 | 115 | .help-page h2, 116 | .help-page .h2 { 117 | font-size: 24px; 118 | } 119 | 120 | .help-page h3, 121 | .help-page .h3 { 122 | font-size: 20px; 123 | } 124 | 125 | #body.help-page { 126 | font-size: 14px; 127 | line-height: 143%; 128 | color: #333; 129 | } 130 | 131 | .help-page a { 132 | color: #0000EE; 133 | text-decoration: none; 134 | } 135 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/HelpPageAreaRegistration.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Http; 2 | using System.Web.Mvc; 3 | 4 | namespace UsingTask.Service.Areas.HelpPage 5 | { 6 | public class HelpPageAreaRegistration : AreaRegistration 7 | { 8 | public override string AreaName 9 | { 10 | get 11 | { 12 | return "HelpPage"; 13 | } 14 | } 15 | 16 | public override void RegisterArea(AreaRegistrationContext context) 17 | { 18 | context.MapRoute( 19 | "HelpPage_Default", 20 | "Help/{action}/{apiId}", 21 | new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); 22 | 23 | HelpPageConfig.Register(GlobalConfiguration.Configuration); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class CollectionModelDescription : ModelDescription 4 | { 5 | public ModelDescription ElementDescription { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 4 | { 5 | public class ComplexTypeModelDescription : ModelDescription 6 | { 7 | public ComplexTypeModelDescription() 8 | { 9 | Properties = new Collection(); 10 | } 11 | 12 | public Collection Properties { get; private set; } 13 | } 14 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class DictionaryModelDescription : KeyValuePairModelDescription 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | 4 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 5 | { 6 | public class EnumTypeModelDescription : ModelDescription 7 | { 8 | public EnumTypeModelDescription() 9 | { 10 | Values = new Collection(); 11 | } 12 | 13 | public Collection Values { get; private set; } 14 | } 15 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs: -------------------------------------------------------------------------------- 1 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class EnumValueDescription 4 | { 5 | public string Documentation { get; set; } 6 | 7 | public string Name { get; set; } 8 | 9 | public string Value { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | 4 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 5 | { 6 | public interface IModelDocumentationProvider 7 | { 8 | string GetDocumentation(MemberInfo member); 9 | 10 | string GetDocumentation(Type type); 11 | } 12 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class KeyValuePairModelDescription : ModelDescription 4 | { 5 | public ModelDescription KeyModelDescription { get; set; } 6 | 7 | public ModelDescription ValueModelDescription { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/ModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 4 | { 5 | /// 6 | /// Describes a type model. 7 | /// 8 | public abstract class ModelDescription 9 | { 10 | public string Documentation { get; set; } 11 | 12 | public Type ModelType { get; set; } 13 | 14 | public string Name { get; set; } 15 | } 16 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 4 | { 5 | /// 6 | /// Use this attribute to change the name of the generated for a type. 7 | /// 8 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] 9 | public sealed class ModelNameAttribute : Attribute 10 | { 11 | public ModelNameAttribute(string name) 12 | { 13 | Name = name; 14 | } 15 | 16 | public string Name { get; private set; } 17 | } 18 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 7 | { 8 | internal static class ModelNameHelper 9 | { 10 | // Modify this to provide custom model name mapping. 11 | public static string GetModelName(Type type) 12 | { 13 | ModelNameAttribute modelNameAttribute = type.GetCustomAttribute(); 14 | if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) 15 | { 16 | return modelNameAttribute.Name; 17 | } 18 | 19 | string modelName = type.Name; 20 | if (type.IsGenericType) 21 | { 22 | // Format the generic type name to something like: GenericOfAgurment1AndArgument2 23 | Type genericType = type.GetGenericTypeDefinition(); 24 | Type[] genericArguments = type.GetGenericArguments(); 25 | string genericTypeName = genericType.Name; 26 | 27 | // Trim the generic parameter counts from the name 28 | genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); 29 | string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); 30 | modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); 31 | } 32 | 33 | return modelName; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 4 | { 5 | public class ParameterAnnotation 6 | { 7 | public Attribute AnnotationAttribute { get; set; } 8 | 9 | public string Documentation { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | 4 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 5 | { 6 | public class ParameterDescription 7 | { 8 | public ParameterDescription() 9 | { 10 | Annotations = new Collection(); 11 | } 12 | 13 | public Collection Annotations { get; private set; } 14 | 15 | public string Documentation { get; set; } 16 | 17 | public string Name { get; set; } 18 | 19 | public ModelDescription TypeDescription { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class SimpleTypeModelDescription : ModelDescription 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Models/HelpPageApiModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.Net.Http.Headers; 4 | using System.Web.Http.Description; 5 | using UsingTask.Service.Areas.HelpPage.ModelDescriptions; 6 | 7 | namespace UsingTask.Service.Areas.HelpPage.Models 8 | { 9 | /// 10 | /// The model that represents an API displayed on the help page. 11 | /// 12 | public class HelpPageApiModel 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public HelpPageApiModel() 18 | { 19 | UriParameters = new Collection(); 20 | SampleRequests = new Dictionary(); 21 | SampleResponses = new Dictionary(); 22 | ErrorMessages = new Collection(); 23 | } 24 | 25 | /// 26 | /// Gets or sets the that describes the API. 27 | /// 28 | public ApiDescription ApiDescription { get; set; } 29 | 30 | /// 31 | /// Gets or sets the collection that describes the URI parameters for the API. 32 | /// 33 | public Collection UriParameters { get; private set; } 34 | 35 | /// 36 | /// Gets or sets the documentation for the request. 37 | /// 38 | public string RequestDocumentation { get; set; } 39 | 40 | /// 41 | /// Gets or sets the that describes the request body. 42 | /// 43 | public ModelDescription RequestModelDescription { get; set; } 44 | 45 | /// 46 | /// Gets the request body parameter descriptions. 47 | /// 48 | public IList RequestBodyParameters 49 | { 50 | get 51 | { 52 | return GetParameterDescriptions(RequestModelDescription); 53 | } 54 | } 55 | 56 | /// 57 | /// Gets or sets the that describes the resource. 58 | /// 59 | public ModelDescription ResourceDescription { get; set; } 60 | 61 | /// 62 | /// Gets the resource property descriptions. 63 | /// 64 | public IList ResourceProperties 65 | { 66 | get 67 | { 68 | return GetParameterDescriptions(ResourceDescription); 69 | } 70 | } 71 | 72 | /// 73 | /// Gets the sample requests associated with the API. 74 | /// 75 | public IDictionary SampleRequests { get; private set; } 76 | 77 | /// 78 | /// Gets the sample responses associated with the API. 79 | /// 80 | public IDictionary SampleResponses { get; private set; } 81 | 82 | /// 83 | /// Gets the error messages associated with this model. 84 | /// 85 | public Collection ErrorMessages { get; private set; } 86 | 87 | private static IList GetParameterDescriptions(ModelDescription modelDescription) 88 | { 89 | ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; 90 | if (complexTypeModelDescription != null) 91 | { 92 | return complexTypeModelDescription.Properties; 93 | } 94 | 95 | CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; 96 | if (collectionModelDescription != null) 97 | { 98 | complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; 99 | if (complexTypeModelDescription != null) 100 | { 101 | return complexTypeModelDescription.Properties; 102 | } 103 | } 104 | 105 | return null; 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Net.Http.Headers; 5 | 6 | namespace UsingTask.Service.Areas.HelpPage 7 | { 8 | /// 9 | /// This is used to identify the place where the sample should be applied. 10 | /// 11 | public class HelpPageSampleKey 12 | { 13 | /// 14 | /// Creates a new based on media type. 15 | /// 16 | /// The media type. 17 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType) 18 | { 19 | if (mediaType == null) 20 | { 21 | throw new ArgumentNullException("mediaType"); 22 | } 23 | 24 | ActionName = String.Empty; 25 | ControllerName = String.Empty; 26 | MediaType = mediaType; 27 | ParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); 28 | } 29 | 30 | /// 31 | /// Creates a new based on media type and CLR type. 32 | /// 33 | /// The media type. 34 | /// The CLR type. 35 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) 36 | : this(mediaType) 37 | { 38 | if (type == null) 39 | { 40 | throw new ArgumentNullException("type"); 41 | } 42 | 43 | ParameterType = type; 44 | } 45 | 46 | /// 47 | /// Creates a new based on , controller name, action name and parameter names. 48 | /// 49 | /// The . 50 | /// Name of the controller. 51 | /// Name of the action. 52 | /// The parameter names. 53 | public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) 54 | { 55 | if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) 56 | { 57 | throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); 58 | } 59 | if (controllerName == null) 60 | { 61 | throw new ArgumentNullException("controllerName"); 62 | } 63 | if (actionName == null) 64 | { 65 | throw new ArgumentNullException("actionName"); 66 | } 67 | if (parameterNames == null) 68 | { 69 | throw new ArgumentNullException("parameterNames"); 70 | } 71 | 72 | ControllerName = controllerName; 73 | ActionName = actionName; 74 | ParameterNames = new HashSet(parameterNames, StringComparer.OrdinalIgnoreCase); 75 | SampleDirection = sampleDirection; 76 | } 77 | 78 | /// 79 | /// Creates a new based on media type, , controller name, action name and parameter names. 80 | /// 81 | /// The media type. 82 | /// The . 83 | /// Name of the controller. 84 | /// Name of the action. 85 | /// The parameter names. 86 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) 87 | : this(sampleDirection, controllerName, actionName, parameterNames) 88 | { 89 | if (mediaType == null) 90 | { 91 | throw new ArgumentNullException("mediaType"); 92 | } 93 | 94 | MediaType = mediaType; 95 | } 96 | 97 | /// 98 | /// Gets the name of the controller. 99 | /// 100 | /// 101 | /// The name of the controller. 102 | /// 103 | public string ControllerName { get; private set; } 104 | 105 | /// 106 | /// Gets the name of the action. 107 | /// 108 | /// 109 | /// The name of the action. 110 | /// 111 | public string ActionName { get; private set; } 112 | 113 | /// 114 | /// Gets the media type. 115 | /// 116 | /// 117 | /// The media type. 118 | /// 119 | public MediaTypeHeaderValue MediaType { get; private set; } 120 | 121 | /// 122 | /// Gets the parameter names. 123 | /// 124 | public HashSet ParameterNames { get; private set; } 125 | 126 | public Type ParameterType { get; private set; } 127 | 128 | /// 129 | /// Gets the . 130 | /// 131 | public SampleDirection? SampleDirection { get; private set; } 132 | 133 | public override bool Equals(object obj) 134 | { 135 | HelpPageSampleKey otherKey = obj as HelpPageSampleKey; 136 | if (otherKey == null) 137 | { 138 | return false; 139 | } 140 | 141 | return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && 142 | String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && 143 | (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && 144 | ParameterType == otherKey.ParameterType && 145 | SampleDirection == otherKey.SampleDirection && 146 | ParameterNames.SetEquals(otherKey.ParameterNames); 147 | } 148 | 149 | public override int GetHashCode() 150 | { 151 | int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); 152 | if (MediaType != null) 153 | { 154 | hashCode ^= MediaType.GetHashCode(); 155 | } 156 | if (SampleDirection != null) 157 | { 158 | hashCode ^= SampleDirection.GetHashCode(); 159 | } 160 | if (ParameterType != null) 161 | { 162 | hashCode ^= ParameterType.GetHashCode(); 163 | } 164 | foreach (string parameterName in ParameterNames) 165 | { 166 | hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); 167 | } 168 | 169 | return hashCode; 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/SampleGeneration/ImageSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UsingTask.Service.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. 7 | /// 8 | public class ImageSample 9 | { 10 | /// 11 | /// Initializes a new instance of the class. 12 | /// 13 | /// The URL of an image. 14 | public ImageSample(string src) 15 | { 16 | if (src == null) 17 | { 18 | throw new ArgumentNullException("src"); 19 | } 20 | Src = src; 21 | } 22 | 23 | public string Src { get; private set; } 24 | 25 | public override bool Equals(object obj) 26 | { 27 | ImageSample other = obj as ImageSample; 28 | return other != null && Src == other.Src; 29 | } 30 | 31 | public override int GetHashCode() 32 | { 33 | return Src.GetHashCode(); 34 | } 35 | 36 | public override string ToString() 37 | { 38 | return Src; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/SampleGeneration/InvalidSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UsingTask.Service.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. 7 | /// 8 | public class InvalidSample 9 | { 10 | public InvalidSample(string errorMessage) 11 | { 12 | if (errorMessage == null) 13 | { 14 | throw new ArgumentNullException("errorMessage"); 15 | } 16 | ErrorMessage = errorMessage; 17 | } 18 | 19 | public string ErrorMessage { get; private set; } 20 | 21 | public override bool Equals(object obj) 22 | { 23 | InvalidSample other = obj as InvalidSample; 24 | return other != null && ErrorMessage == other.ErrorMessage; 25 | } 26 | 27 | public override int GetHashCode() 28 | { 29 | return ErrorMessage.GetHashCode(); 30 | } 31 | 32 | public override string ToString() 33 | { 34 | return ErrorMessage; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/SampleGeneration/SampleDirection.cs: -------------------------------------------------------------------------------- 1 | namespace UsingTask.Service.Areas.HelpPage 2 | { 3 | /// 4 | /// Indicates whether the sample is used for request or response 5 | /// 6 | public enum SampleDirection 7 | { 8 | Request = 0, 9 | Response 10 | } 11 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/SampleGeneration/TextSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UsingTask.Service.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. 7 | /// 8 | public class TextSample 9 | { 10 | public TextSample(string text) 11 | { 12 | if (text == null) 13 | { 14 | throw new ArgumentNullException("text"); 15 | } 16 | Text = text; 17 | } 18 | 19 | public string Text { get; private set; } 20 | 21 | public override bool Equals(object obj) 22 | { 23 | TextSample other = obj as TextSample; 24 | return other != null && Text == other.Text; 25 | } 26 | 27 | public override int GetHashCode() 28 | { 29 | return Text.GetHashCode(); 30 | } 31 | 32 | public override string ToString() 33 | { 34 | return Text; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/Api.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using UsingTask.Service.Areas.HelpPage.Models 3 | @model HelpPageApiModel 4 | 5 | @{ 6 | var description = Model.ApiDescription; 7 | ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath; 8 | } 9 | 10 | 11 |
12 | 19 |
20 | @Html.DisplayForModel() 21 |
22 |
23 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Controllers 3 | @using System.Web.Http.Description 4 | @using UsingTask.Service.Areas.HelpPage 5 | @using UsingTask.Service.Areas.HelpPage.Models 6 | @model IGrouping 7 | 8 | @{ 9 | var controllerDocumentation = ViewBag.DocumentationProvider != null ? 10 | ViewBag.DocumentationProvider.GetDocumentation(Model.Key) : 11 | null; 12 | } 13 | 14 |

@Model.Key.ControllerName

15 | @if (!String.IsNullOrEmpty(controllerDocumentation)) 16 | { 17 |

@controllerDocumentation

18 | } 19 | 20 | 21 | 22 | 23 | 24 | @foreach (var api in Model) 25 | { 26 | 27 | 28 | 38 | 39 | } 40 | 41 |
APIDescription
@api.HttpMethod.Method @api.RelativePath 29 | @if (api.Documentation != null) 30 | { 31 |

@api.Documentation

32 | } 33 | else 34 | { 35 |

No documentation available.

36 | } 37 |
-------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | @model CollectionModelDescription 3 | @if (Model.ElementDescription is ComplexTypeModelDescription) 4 | { 5 | @Html.DisplayFor(m => m.ElementDescription) 6 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | @model ComplexTypeModelDescription 3 | @Html.DisplayFor(m => m.Properties, "Parameters") -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | @model DictionaryModelDescription 3 | Dictionary of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] 4 | and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | @model EnumTypeModelDescription 3 | 4 |

Possible enumeration values:

5 | 6 | 7 | 8 | 9 | 10 | 11 | @foreach (EnumValueDescription value in Model.Values) 12 | { 13 | 14 | 15 | 18 | 21 | 22 | } 23 | 24 |
NameValueDescription
@value.Name 16 |

@value.Value

17 |
19 |

@value.Documentation

20 |
-------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Description 3 | @using UsingTask.Service.Areas.HelpPage.Models 4 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 5 | @model HelpPageApiModel 6 | 7 | @{ 8 | ApiDescription description = Model.ApiDescription; 9 | } 10 |

@description.HttpMethod.Method @description.RelativePath

11 |
12 |

@description.Documentation

13 | 14 |

Request Information

15 | 16 |

URI Parameters

17 | @Html.DisplayFor(m => m.UriParameters, "Parameters") 18 | 19 |

Body Parameters

20 | 21 |

@Model.RequestDocumentation

22 | 23 | @if (Model.RequestModelDescription != null) 24 | { 25 | @Html.DisplayFor(m => m.RequestModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.RequestModelDescription }) 26 | if (Model.RequestBodyParameters != null) 27 | { 28 | @Html.DisplayFor(m => m.RequestBodyParameters, "Parameters") 29 | } 30 | } 31 | else 32 | { 33 |

None.

34 | } 35 | 36 | @if (Model.SampleRequests.Count > 0) 37 | { 38 |

Request Formats

39 | @Html.DisplayFor(m => m.SampleRequests, "Samples") 40 | } 41 | 42 |

Response Information

43 | 44 |

Resource Description

45 | 46 |

@description.ResponseDescription.Documentation

47 | 48 | @if (Model.ResourceDescription != null) 49 | { 50 | @Html.DisplayFor(m => m.ResourceDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ResourceDescription }) 51 | if (Model.ResourceProperties != null) 52 | { 53 | @Html.DisplayFor(m => m.ResourceProperties, "Parameters") 54 | } 55 | } 56 | else 57 | { 58 |

None.

59 | } 60 | 61 | @if (Model.SampleResponses.Count > 0) 62 | { 63 |

Response Formats

64 | @Html.DisplayFor(m => m.SampleResponses, "Samples") 65 | } 66 | 67 |
-------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage 2 | @model ImageSample 3 | 4 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage 2 | @model InvalidSample 3 | 4 | @if (HttpContext.Current.IsDebuggingEnabled) 5 | { 6 |
7 |

@Model.ErrorMessage

8 |
9 | } 10 | else 11 | { 12 |

Sample not available.

13 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | @model KeyValuePairModelDescription 3 | Pair of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] 4 | and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | @model Type 3 | @{ 4 | ModelDescription modelDescription = ViewBag.modelDescription; 5 | if (modelDescription is ComplexTypeModelDescription || modelDescription is EnumTypeModelDescription) 6 | { 7 | if (Model == typeof(Object)) 8 | { 9 | @:Object 10 | } 11 | else 12 | { 13 | @Html.ActionLink(modelDescription.Name, "ResourceModel", "Help", new { modelName = modelDescription.Name }, null) 14 | } 15 | } 16 | else if (modelDescription is CollectionModelDescription) 17 | { 18 | var collectionDescription = modelDescription as CollectionModelDescription; 19 | var elementDescription = collectionDescription.ElementDescription; 20 | @:Collection of @Html.DisplayFor(m => elementDescription.ModelType, "ModelDescriptionLink", new { modelDescription = elementDescription }) 21 | } 22 | else 23 | { 24 | @Html.DisplayFor(m => modelDescription) 25 | } 26 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Collections.Generic 2 | @using System.Collections.ObjectModel 3 | @using System.Web.Http.Description 4 | @using System.Threading 5 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 6 | @model IList 7 | 8 | @if (Model.Count > 0) 9 | { 10 | 11 | 12 | 13 | 14 | 15 | @foreach (ParameterDescription parameter in Model) 16 | { 17 | ModelDescription modelDescription = parameter.TypeDescription; 18 | 19 | 20 | 23 | 26 | 39 | 40 | } 41 | 42 |
NameDescriptionTypeAdditional information
@parameter.Name 21 |

@parameter.Documentation

22 |
24 | @Html.DisplayFor(m => modelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = modelDescription }) 25 | 27 | @if (parameter.Annotations.Count > 0) 28 | { 29 | foreach (var annotation in parameter.Annotations) 30 | { 31 |

@annotation.Documentation

32 | } 33 | } 34 | else 35 | { 36 |

None.

37 | } 38 |
43 | } 44 | else 45 | { 46 |

None.

47 | } 48 | 49 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Net.Http.Headers 2 | @model Dictionary 3 | 4 | @{ 5 | // Group the samples into a single tab if they are the same. 6 | Dictionary samples = Model.GroupBy(pair => pair.Value).ToDictionary( 7 | pair => String.Join(", ", pair.Select(m => m.Key.ToString()).ToArray()), 8 | pair => pair.Key); 9 | var mediaTypes = samples.Keys; 10 | } 11 |
12 | @foreach (var mediaType in mediaTypes) 13 | { 14 |

@mediaType

15 |
16 | Sample: 17 | @{ 18 | var sample = samples[mediaType]; 19 | if (sample == null) 20 | { 21 |

Sample not available.

22 | } 23 | else 24 | { 25 | @Html.DisplayFor(s => sample); 26 | } 27 | } 28 |
29 | } 30 |
-------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 2 | @model SimpleTypeModelDescription 3 | @Model.Documentation -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml: -------------------------------------------------------------------------------- 1 | @using UsingTask.Service.Areas.HelpPage 2 | @model TextSample 3 | 4 |
5 | @Model.Text
6 | 
-------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/Index.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Controllers 3 | @using System.Web.Http.Description 4 | @using System.Collections.ObjectModel 5 | @using UsingTask.Service.Areas.HelpPage.Models 6 | @model Collection 7 | 8 | @{ 9 | ViewBag.Title = "ASP.NET Web API Help Page"; 10 | 11 | // Group APIs by controller 12 | ILookup apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor); 13 | } 14 | 15 | 16 |
17 |
18 |
19 |

@ViewBag.Title

20 |
21 |
22 |
23 |
24 | 32 |
33 | @foreach (var group in apiGroups) 34 | { 35 | @Html.DisplayFor(m => group, "ApiGroup") 36 | } 37 |
38 |
39 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Help/ResourceModel.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using UsingTask.Service.Areas.HelpPage.ModelDescriptions 3 | @model ModelDescription 4 | 5 | 6 |
7 | 14 |

@Model.Name

15 |

@Model.Documentation

16 |
17 | @Html.DisplayFor(m => Model) 18 |
19 |
20 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | @ViewBag.Title 7 | @RenderSection("scripts", required: false) 8 | 9 | 10 | @RenderBody() 11 | 12 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |
7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | // Change the Layout path below to blend the look and feel of the help page with your existing web pages 3 | Layout = "~/Views/Shared/_Layout.cshtml"; 4 | } -------------------------------------------------------------------------------- /UsingTask.Service/Areas/HelpPage/XmlDocumentationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Web.Http.Controllers; 6 | using System.Web.Http.Description; 7 | using System.Xml.XPath; 8 | using UsingTask.Service.Areas.HelpPage.ModelDescriptions; 9 | 10 | namespace UsingTask.Service.Areas.HelpPage 11 | { 12 | /// 13 | /// A custom that reads the API documentation from an XML documentation file. 14 | /// 15 | public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider 16 | { 17 | private XPathNavigator _documentNavigator; 18 | private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; 19 | private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; 20 | private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; 21 | private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; 22 | private const string ParameterExpression = "param[@name='{0}']"; 23 | 24 | /// 25 | /// Initializes a new instance of the class. 26 | /// 27 | /// The physical path to XML document. 28 | public XmlDocumentationProvider(string documentPath) 29 | { 30 | if (documentPath == null) 31 | { 32 | throw new ArgumentNullException("documentPath"); 33 | } 34 | XPathDocument xpath = new XPathDocument(documentPath); 35 | _documentNavigator = xpath.CreateNavigator(); 36 | } 37 | 38 | public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) 39 | { 40 | XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); 41 | return GetTagValue(typeNode, "summary"); 42 | } 43 | 44 | public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) 45 | { 46 | XPathNavigator methodNode = GetMethodNode(actionDescriptor); 47 | return GetTagValue(methodNode, "summary"); 48 | } 49 | 50 | public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) 51 | { 52 | ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; 53 | if (reflectedParameterDescriptor != null) 54 | { 55 | XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); 56 | if (methodNode != null) 57 | { 58 | string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; 59 | XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); 60 | if (parameterNode != null) 61 | { 62 | return parameterNode.Value.Trim(); 63 | } 64 | } 65 | } 66 | 67 | return null; 68 | } 69 | 70 | public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) 71 | { 72 | XPathNavigator methodNode = GetMethodNode(actionDescriptor); 73 | return GetTagValue(methodNode, "returns"); 74 | } 75 | 76 | public string GetDocumentation(MemberInfo member) 77 | { 78 | string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); 79 | string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; 80 | string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); 81 | XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); 82 | return GetTagValue(propertyNode, "summary"); 83 | } 84 | 85 | public string GetDocumentation(Type type) 86 | { 87 | XPathNavigator typeNode = GetTypeNode(type); 88 | return GetTagValue(typeNode, "summary"); 89 | } 90 | 91 | private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) 92 | { 93 | ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; 94 | if (reflectedActionDescriptor != null) 95 | { 96 | string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); 97 | return _documentNavigator.SelectSingleNode(selectExpression); 98 | } 99 | 100 | return null; 101 | } 102 | 103 | private static string GetMemberName(MethodInfo method) 104 | { 105 | string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); 106 | ParameterInfo[] parameters = method.GetParameters(); 107 | if (parameters.Length != 0) 108 | { 109 | string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); 110 | name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); 111 | } 112 | 113 | return name; 114 | } 115 | 116 | private static string GetTagValue(XPathNavigator parentNode, string tagName) 117 | { 118 | if (parentNode != null) 119 | { 120 | XPathNavigator node = parentNode.SelectSingleNode(tagName); 121 | if (node != null) 122 | { 123 | return node.Value.Trim(); 124 | } 125 | } 126 | 127 | return null; 128 | } 129 | 130 | private XPathNavigator GetTypeNode(Type type) 131 | { 132 | string controllerTypeName = GetTypeName(type); 133 | string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); 134 | return _documentNavigator.SelectSingleNode(selectExpression); 135 | } 136 | 137 | private static string GetTypeName(Type type) 138 | { 139 | string name = type.FullName; 140 | if (type.IsGenericType) 141 | { 142 | // Format the generic type name to something like: Generic{System.Int32,System.String} 143 | Type genericType = type.GetGenericTypeDefinition(); 144 | Type[] genericArguments = type.GetGenericArguments(); 145 | string genericTypeName = genericType.FullName; 146 | 147 | // Trim the generic parameter counts from the name 148 | genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); 149 | string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); 150 | name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); 151 | } 152 | if (type.IsNested) 153 | { 154 | // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. 155 | name = name.Replace("+", "."); 156 | } 157 | 158 | return name; 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /UsingTask.Service/Content/Site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Set width on the form input elements since they're 100% wide by default */ 13 | input, 14 | select, 15 | textarea { 16 | max-width: 280px; 17 | } 18 | -------------------------------------------------------------------------------- /UsingTask.Service/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | 7 | namespace UsingTask.Service.Controllers 8 | { 9 | public class HomeController : Controller 10 | { 11 | public ActionResult Index() 12 | { 13 | ViewBag.Title = "Home Page"; 14 | 15 | return View(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /UsingTask.Service/Controllers/PeopleController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Web.Http; 4 | using UsingTask.Shared; 5 | 6 | namespace UsingTask.Service.Controllers 7 | { 8 | public class PeopleController : ApiController 9 | { 10 | List people = People.GetPeople(); 11 | 12 | // GET api/ 13 | public IEnumerable Get() 14 | { 15 | return people; 16 | } 17 | 18 | // GET api//5 19 | public Person Get(int id) 20 | { 21 | return people.SingleOrDefault(p => p.Id == id); 22 | } 23 | 24 | // POST api/ 25 | public void Post([FromBody]Person value) 26 | { 27 | } 28 | 29 | // PUT api//5 30 | public void Put(int id, [FromBody]Person value) 31 | { 32 | } 33 | 34 | // DELETE api//5 35 | public void Delete(int id) 36 | { 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /UsingTask.Service/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Web.Http; 7 | 8 | namespace UsingTask.Service.Controllers 9 | { 10 | [Authorize] 11 | public class ValuesController : ApiController 12 | { 13 | // GET api/values 14 | public IEnumerable Get() 15 | { 16 | return new string[] { "value1", "value2" }; 17 | } 18 | 19 | // GET api/values/5 20 | public string Get(int id) 21 | { 22 | return "value"; 23 | } 24 | 25 | // POST api/values 26 | public void Post([FromBody]string value) 27 | { 28 | } 29 | 30 | // PUT api/values/5 31 | public void Put(int id, [FromBody]string value) 32 | { 33 | } 34 | 35 | // DELETE api/values/5 36 | public void Delete(int id) 37 | { 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /UsingTask.Service/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="UsingTask.Service.WebApiApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /UsingTask.Service/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Http; 6 | using System.Web.Mvc; 7 | using System.Web.Optimization; 8 | using System.Web.Routing; 9 | 10 | namespace UsingTask.Service 11 | { 12 | public class WebApiApplication : System.Web.HttpApplication 13 | { 14 | protected void Application_Start() 15 | { 16 | AreaRegistration.RegisterAllAreas(); 17 | GlobalConfiguration.Configure(WebApiConfig.Register); 18 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 19 | RouteConfig.RegisterRoutes(RouteTable.Routes); 20 | BundleConfig.RegisterBundles(BundleTable.Bundles); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /UsingTask.Service/Models/AccountBindingModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using Newtonsoft.Json; 4 | 5 | namespace UsingTask.Service.Models 6 | { 7 | // Models used as parameters to AccountController actions. 8 | 9 | public class AddExternalLoginBindingModel 10 | { 11 | [Required] 12 | [Display(Name = "External access token")] 13 | public string ExternalAccessToken { get; set; } 14 | } 15 | 16 | public class ChangePasswordBindingModel 17 | { 18 | [Required] 19 | [DataType(DataType.Password)] 20 | [Display(Name = "Current password")] 21 | public string OldPassword { get; set; } 22 | 23 | [Required] 24 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 25 | [DataType(DataType.Password)] 26 | [Display(Name = "New password")] 27 | public string NewPassword { get; set; } 28 | 29 | [DataType(DataType.Password)] 30 | [Display(Name = "Confirm new password")] 31 | [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] 32 | public string ConfirmPassword { get; set; } 33 | } 34 | 35 | public class RegisterBindingModel 36 | { 37 | [Required] 38 | [Display(Name = "Email")] 39 | public string Email { get; set; } 40 | 41 | [Required] 42 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 43 | [DataType(DataType.Password)] 44 | [Display(Name = "Password")] 45 | public string Password { get; set; } 46 | 47 | [DataType(DataType.Password)] 48 | [Display(Name = "Confirm password")] 49 | [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 50 | public string ConfirmPassword { get; set; } 51 | } 52 | 53 | public class RegisterExternalBindingModel 54 | { 55 | [Required] 56 | [Display(Name = "Email")] 57 | public string Email { get; set; } 58 | } 59 | 60 | public class RemoveLoginBindingModel 61 | { 62 | [Required] 63 | [Display(Name = "Login provider")] 64 | public string LoginProvider { get; set; } 65 | 66 | [Required] 67 | [Display(Name = "Provider key")] 68 | public string ProviderKey { get; set; } 69 | } 70 | 71 | public class SetPasswordBindingModel 72 | { 73 | [Required] 74 | [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 75 | [DataType(DataType.Password)] 76 | [Display(Name = "New password")] 77 | public string NewPassword { get; set; } 78 | 79 | [DataType(DataType.Password)] 80 | [Display(Name = "Confirm new password")] 81 | [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] 82 | public string ConfirmPassword { get; set; } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /UsingTask.Service/Models/AccountViewModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace UsingTask.Service.Models 5 | { 6 | // Models returned by AccountController actions. 7 | 8 | public class ExternalLoginViewModel 9 | { 10 | public string Name { get; set; } 11 | 12 | public string Url { get; set; } 13 | 14 | public string State { get; set; } 15 | } 16 | 17 | public class ManageInfoViewModel 18 | { 19 | public string LocalLoginProvider { get; set; } 20 | 21 | public string Email { get; set; } 22 | 23 | public IEnumerable Logins { get; set; } 24 | 25 | public IEnumerable ExternalLoginProviders { get; set; } 26 | } 27 | 28 | public class UserInfoViewModel 29 | { 30 | public string Email { get; set; } 31 | 32 | public bool HasRegistered { get; set; } 33 | 34 | public string LoginProvider { get; set; } 35 | } 36 | 37 | public class UserLoginInfoViewModel 38 | { 39 | public string LoginProvider { get; set; } 40 | 41 | public string ProviderKey { get; set; } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /UsingTask.Service/Models/IdentityModels.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNet.Identity; 4 | using Microsoft.AspNet.Identity.EntityFramework; 5 | using Microsoft.AspNet.Identity.Owin; 6 | 7 | namespace UsingTask.Service.Models 8 | { 9 | // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. 10 | public class ApplicationUser : IdentityUser 11 | { 12 | public async Task GenerateUserIdentityAsync(UserManager manager, string authenticationType) 13 | { 14 | // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 15 | var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); 16 | // Add custom user claims here 17 | return userIdentity; 18 | } 19 | } 20 | 21 | public class ApplicationDbContext : IdentityDbContext 22 | { 23 | public ApplicationDbContext() 24 | : base("DefaultConnection", throwIfV1Schema: false) 25 | { 26 | } 27 | 28 | public static ApplicationDbContext Create() 29 | { 30 | return new ApplicationDbContext(); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /UsingTask.Service/Project_Readme.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Your ASP.NET application 6 | 95 | 96 | 97 | 98 | 102 | 103 |
104 |
105 |

This application consists of:

106 |
    107 |
  • Help Page for documenting your Web APIs
  • 108 |
  • Theming using Bootstrap
  • 109 |
  • Authentication, if selected, shows how to register and sign in
  • 110 |
  • ASP.NET features managed using NuGet
  • 111 |
112 |
113 | 114 | 130 | 131 |
132 |

Deploy

133 | 138 |
139 | 140 |
141 |

Get help

142 | 146 |
147 |
148 | 149 | 150 | -------------------------------------------------------------------------------- /UsingTask.Service/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("UsingTask.Service")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("UsingTask.Service")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0db41d01-f312-4681-8eef-d4a7fc5a1d81")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Revision and Build Numbers 33 | // by using the '*' as shown below: 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /UsingTask.Service/Providers/ApplicationOAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNet.Identity; 7 | using Microsoft.AspNet.Identity.EntityFramework; 8 | using Microsoft.AspNet.Identity.Owin; 9 | using Microsoft.Owin.Security; 10 | using Microsoft.Owin.Security.Cookies; 11 | using Microsoft.Owin.Security.OAuth; 12 | using UsingTask.Service.Models; 13 | 14 | namespace UsingTask.Service.Providers 15 | { 16 | public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider 17 | { 18 | private readonly string _publicClientId; 19 | 20 | public ApplicationOAuthProvider(string publicClientId) 21 | { 22 | if (publicClientId == null) 23 | { 24 | throw new ArgumentNullException("publicClientId"); 25 | } 26 | 27 | _publicClientId = publicClientId; 28 | } 29 | 30 | public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 31 | { 32 | var userManager = context.OwinContext.GetUserManager(); 33 | 34 | ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); 35 | 36 | if (user == null) 37 | { 38 | context.SetError("invalid_grant", "The user name or password is incorrect."); 39 | return; 40 | } 41 | 42 | ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, 43 | OAuthDefaults.AuthenticationType); 44 | ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, 45 | CookieAuthenticationDefaults.AuthenticationType); 46 | 47 | AuthenticationProperties properties = CreateProperties(user.UserName); 48 | AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); 49 | context.Validated(ticket); 50 | context.Request.Context.Authentication.SignIn(cookiesIdentity); 51 | } 52 | 53 | public override Task TokenEndpoint(OAuthTokenEndpointContext context) 54 | { 55 | foreach (KeyValuePair property in context.Properties.Dictionary) 56 | { 57 | context.AdditionalResponseParameters.Add(property.Key, property.Value); 58 | } 59 | 60 | return Task.FromResult(null); 61 | } 62 | 63 | public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 64 | { 65 | // Resource owner password credentials does not provide a client ID. 66 | if (context.ClientId == null) 67 | { 68 | context.Validated(); 69 | } 70 | 71 | return Task.FromResult(null); 72 | } 73 | 74 | public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) 75 | { 76 | if (context.ClientId == _publicClientId) 77 | { 78 | Uri expectedRootUri = new Uri(context.Request.Uri, "/"); 79 | 80 | if (expectedRootUri.AbsoluteUri == context.RedirectUri) 81 | { 82 | context.Validated(); 83 | } 84 | } 85 | 86 | return Task.FromResult(null); 87 | } 88 | 89 | public static AuthenticationProperties CreateProperties(string userName) 90 | { 91 | IDictionary data = new Dictionary 92 | { 93 | { "userName", userName } 94 | }; 95 | return new AuthenticationProperties(data); 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /UsingTask.Service/Results/ChallengeResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Web.Http; 9 | 10 | namespace UsingTask.Service.Results 11 | { 12 | public class ChallengeResult : IHttpActionResult 13 | { 14 | public ChallengeResult(string loginProvider, ApiController controller) 15 | { 16 | LoginProvider = loginProvider; 17 | Request = controller.Request; 18 | } 19 | 20 | public string LoginProvider { get; set; } 21 | public HttpRequestMessage Request { get; set; } 22 | 23 | public Task ExecuteAsync(CancellationToken cancellationToken) 24 | { 25 | Request.GetOwinContext().Authentication.Challenge(LoginProvider); 26 | 27 | HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 28 | response.RequestMessage = Request; 29 | return Task.FromResult(response); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /UsingTask.Service/Scripts/_references.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/using-task/37f01835f1a0005e2cb5db09decda9d83271da1f/UsingTask.Service/Scripts/_references.js -------------------------------------------------------------------------------- /UsingTask.Service/Scripts/jquery.validate.unobtrusive.min.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /* 16 | ** Unobtrusive validation support library for jQuery and jQuery Validate 17 | ** Copyright (C) Microsoft Corporation. All rights reserved. 18 | */ 19 | (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,e){var b=a(this).find("[data-valmsg-for='"+f(e[0].name)+"']"),d=b.attr("data-valmsg-replace"),g=d?a.parseJSON(d)!==false:null;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(g){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("
  • ").html(this.message).appendTo(b)})}}function k(d){var b=d.data("unobtrusiveContainer"),c=b.attr("data-valmsg-replace"),e=c?a.parseJSON(c):null;if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");d.removeData("unobtrusiveContainer");e&&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(b){var c=a(b),f=c.data(e),i=a.proxy(n,b),g=d.unobtrusive.options||{},h=function(e,d){var c=g[e];c&&a.isFunction(c)&&c.apply(b,d)};if(!f){f={options:{errorClass:g.errorClass||"input-validation-error",errorElement:g.errorElement||"span",errorPlacement:function(){m.apply(b,arguments);h("errorPlacement",arguments)},invalidHandler:function(){l.apply(b,arguments);h("invalidHandler",arguments)},messages:{},rules:{},success:function(){k.apply(b,arguments);h("success",arguments)}},attachValidation:function(){c.off("reset."+e,i).on("reset."+e,i).validate(this.options)},validate:function(){c.validate();return c.valid()}};c.data(e,f)}return f}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(c){var b=a(c),e=b.parents().addBack().filter("form").add(b.find("form")).has("[data-val=true]");b.find("[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});e.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});if(d.methods.extension){b.addSingleVal("accept","mimtype");b.addSingleVal("extension","extension")}else b.addSingleVal("extension","extension","accept");b.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.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength");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").filter("[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").filter("[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); -------------------------------------------------------------------------------- /UsingTask.Service/Scripts/respond.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ 16 | /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ 17 | window.matchMedia = window.matchMedia || (function(doc, undefined){ 18 | 19 | var bool, 20 | docElem = doc.documentElement, 21 | refNode = docElem.firstElementChild || docElem.firstChild, 22 | // fakeBody required for 23 | fakeBody = doc.createElement('body'), 24 | div = doc.createElement('div'); 25 | 26 | div.id = 'mq-test-1'; 27 | div.style.cssText = "position:absolute;top:-100em"; 28 | fakeBody.style.background = "none"; 29 | fakeBody.appendChild(div); 30 | 31 | return function(q){ 32 | 33 | div.innerHTML = '­'; 34 | 35 | docElem.insertBefore(fakeBody, refNode); 36 | bool = div.offsetWidth == 42; 37 | docElem.removeChild(fakeBody); 38 | 39 | return { matches: bool, media: q }; 40 | }; 41 | 42 | })(document); 43 | 44 | 45 | 46 | 47 | /*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ 48 | (function( win ){ 49 | //exposed namespace 50 | win.respond = {}; 51 | 52 | //define update even in native-mq-supporting browsers, to avoid errors 53 | respond.update = function(){}; 54 | 55 | //expose media query support flag for external use 56 | respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches; 57 | 58 | //if media queries are supported, exit here 59 | if( respond.mediaQueriesSupported ){ return; } 60 | 61 | //define vars 62 | var doc = win.document, 63 | docElem = doc.documentElement, 64 | mediastyles = [], 65 | rules = [], 66 | appendedEls = [], 67 | parsedSheets = {}, 68 | resizeThrottle = 30, 69 | head = doc.getElementsByTagName( "head" )[0] || docElem, 70 | base = doc.getElementsByTagName( "base" )[0], 71 | links = head.getElementsByTagName( "link" ), 72 | requestQueue = [], 73 | 74 | //loop stylesheets, send text content to translate 75 | ripCSS = function(){ 76 | var sheets = links, 77 | sl = sheets.length, 78 | i = 0, 79 | //vars for loop: 80 | sheet, href, media, isCSS; 81 | 82 | for( ; i < sl; i++ ){ 83 | sheet = sheets[ i ], 84 | href = sheet.href, 85 | media = sheet.media, 86 | isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; 87 | 88 | //only links plz and prevent re-parsing 89 | if( !!href && isCSS && !parsedSheets[ href ] ){ 90 | // selectivizr exposes css through the rawCssText expando 91 | if (sheet.styleSheet && sheet.styleSheet.rawCssText) { 92 | translate( sheet.styleSheet.rawCssText, href, media ); 93 | parsedSheets[ href ] = true; 94 | } else { 95 | if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) 96 | || href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){ 97 | requestQueue.push( { 98 | href: href, 99 | media: media 100 | } ); 101 | } 102 | } 103 | } 104 | } 105 | makeRequests(); 106 | }, 107 | 108 | //recurse through request queue, get css text 109 | makeRequests = function(){ 110 | if( requestQueue.length ){ 111 | var thisRequest = requestQueue.shift(); 112 | 113 | ajax( thisRequest.href, function( styles ){ 114 | translate( styles, thisRequest.href, thisRequest.media ); 115 | parsedSheets[ thisRequest.href ] = true; 116 | makeRequests(); 117 | } ); 118 | } 119 | }, 120 | 121 | //find media blocks in css text, convert to style blocks 122 | translate = function( styles, href, media ){ 123 | var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ), 124 | ql = qs && qs.length || 0, 125 | //try to get CSS path 126 | href = href.substring( 0, href.lastIndexOf( "/" )), 127 | repUrls = function( css ){ 128 | return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" ); 129 | }, 130 | useMedia = !ql && media, 131 | //vars used in loop 132 | i = 0, 133 | j, fullq, thisq, eachq, eql; 134 | 135 | //if path exists, tack on trailing slash 136 | if( href.length ){ href += "/"; } 137 | 138 | //if no internal queries exist, but media attr does, use that 139 | //note: this currently lacks support for situations where a media attr is specified on a link AND 140 | //its associated stylesheet has internal CSS media queries. 141 | //In those cases, the media attribute will currently be ignored. 142 | if( useMedia ){ 143 | ql = 1; 144 | } 145 | 146 | 147 | for( ; i < ql; i++ ){ 148 | j = 0; 149 | 150 | //media attr 151 | if( useMedia ){ 152 | fullq = media; 153 | rules.push( repUrls( styles ) ); 154 | } 155 | //parse for styles 156 | else{ 157 | fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1; 158 | rules.push( RegExp.$2 && repUrls( RegExp.$2 ) ); 159 | } 160 | 161 | eachq = fullq.split( "," ); 162 | eql = eachq.length; 163 | 164 | for( ; j < eql; j++ ){ 165 | thisq = eachq[ j ]; 166 | mediastyles.push( { 167 | media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all", 168 | rules : rules.length - 1, 169 | hasquery: thisq.indexOf("(") > -1, 170 | minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ), 171 | maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ) 172 | } ); 173 | } 174 | } 175 | 176 | applyMedia(); 177 | }, 178 | 179 | lastCall, 180 | 181 | resizeDefer, 182 | 183 | // returns the value of 1em in pixels 184 | getEmValue = function() { 185 | var ret, 186 | div = doc.createElement('div'), 187 | body = doc.body, 188 | fakeUsed = false; 189 | 190 | div.style.cssText = "position:absolute;font-size:1em;width:1em"; 191 | 192 | if( !body ){ 193 | body = fakeUsed = doc.createElement( "body" ); 194 | body.style.background = "none"; 195 | } 196 | 197 | body.appendChild( div ); 198 | 199 | docElem.insertBefore( body, docElem.firstChild ); 200 | 201 | ret = div.offsetWidth; 202 | 203 | if( fakeUsed ){ 204 | docElem.removeChild( body ); 205 | } 206 | else { 207 | body.removeChild( div ); 208 | } 209 | 210 | //also update eminpx before returning 211 | ret = eminpx = parseFloat(ret); 212 | 213 | return ret; 214 | }, 215 | 216 | //cached container for 1em value, populated the first time it's needed 217 | eminpx, 218 | 219 | //enable/disable styles 220 | applyMedia = function( fromResize ){ 221 | var name = "clientWidth", 222 | docElemProp = docElem[ name ], 223 | currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp, 224 | styleBlocks = {}, 225 | lastLink = links[ links.length-1 ], 226 | now = (new Date()).getTime(); 227 | 228 | //throttle resize calls 229 | if( fromResize && lastCall && now - lastCall < resizeThrottle ){ 230 | clearTimeout( resizeDefer ); 231 | resizeDefer = setTimeout( applyMedia, resizeThrottle ); 232 | return; 233 | } 234 | else { 235 | lastCall = now; 236 | } 237 | 238 | for( var i in mediastyles ){ 239 | var thisstyle = mediastyles[ i ], 240 | min = thisstyle.minw, 241 | max = thisstyle.maxw, 242 | minnull = min === null, 243 | maxnull = max === null, 244 | em = "em"; 245 | 246 | if( !!min ){ 247 | min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); 248 | } 249 | if( !!max ){ 250 | max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); 251 | } 252 | 253 | // if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true 254 | if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){ 255 | if( !styleBlocks[ thisstyle.media ] ){ 256 | styleBlocks[ thisstyle.media ] = []; 257 | } 258 | styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] ); 259 | } 260 | } 261 | 262 | //remove any existing respond style element(s) 263 | for( var i in appendedEls ){ 264 | if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){ 265 | head.removeChild( appendedEls[ i ] ); 266 | } 267 | } 268 | 269 | //inject active styles, grouped by media type 270 | for( var i in styleBlocks ){ 271 | var ss = doc.createElement( "style" ), 272 | css = styleBlocks[ i ].join( "\n" ); 273 | 274 | ss.type = "text/css"; 275 | ss.media = i; 276 | 277 | //originally, ss was appended to a documentFragment and sheets were appended in bulk. 278 | //this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one! 279 | head.insertBefore( ss, lastLink.nextSibling ); 280 | 281 | if ( ss.styleSheet ){ 282 | ss.styleSheet.cssText = css; 283 | } 284 | else { 285 | ss.appendChild( doc.createTextNode( css ) ); 286 | } 287 | 288 | //push to appendedEls to track for later removal 289 | appendedEls.push( ss ); 290 | } 291 | }, 292 | //tweaked Ajax functions from Quirksmode 293 | ajax = function( url, callback ) { 294 | var req = xmlHttp(); 295 | if (!req){ 296 | return; 297 | } 298 | req.open( "GET", url, true ); 299 | req.onreadystatechange = function () { 300 | if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){ 301 | return; 302 | } 303 | callback( req.responseText ); 304 | } 305 | if ( req.readyState == 4 ){ 306 | return; 307 | } 308 | req.send( null ); 309 | }, 310 | //define ajax obj 311 | xmlHttp = (function() { 312 | var xmlhttpmethod = false; 313 | try { 314 | xmlhttpmethod = new XMLHttpRequest(); 315 | } 316 | catch( e ){ 317 | xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" ); 318 | } 319 | return function(){ 320 | return xmlhttpmethod; 321 | }; 322 | })(); 323 | 324 | //translate CSS 325 | ripCSS(); 326 | 327 | //expose update for re-running respond later on 328 | respond.update = ripCSS; 329 | 330 | //adjust on resize 331 | function callMedia(){ 332 | applyMedia( true ); 333 | } 334 | if( win.addEventListener ){ 335 | win.addEventListener( "resize", callMedia, false ); 336 | } 337 | else if( win.attachEvent ){ 338 | win.attachEvent( "onresize", callMedia ); 339 | } 340 | })(this); 341 | -------------------------------------------------------------------------------- /UsingTask.Service/Scripts/respond.min.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ 16 | /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ 17 | window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='­';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document); 18 | 19 | /*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ 20 | (function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this); -------------------------------------------------------------------------------- /UsingTask.Service/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Owin; 5 | using Owin; 6 | 7 | [assembly: OwinStartup(typeof(UsingTask.Service.Startup))] 8 | 9 | namespace UsingTask.Service 10 | { 11 | public partial class Startup 12 | { 13 | public void Configuration(IAppBuilder app) 14 | { 15 | ConfigureAuth(app); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /UsingTask.Service/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | 
    2 |

    ASP.NET

    3 |

    ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.

    4 |

    Learn more »

    5 |
    6 |
    7 |
    8 |

    Getting started

    9 |

    ASP.NET Web API is a framework that makes it easy to build HTTP services that reach 10 | a broad range of clients, including browsers and mobile devices. ASP.NET Web API 11 | is an ideal platform for building RESTful applications on the .NET Framework.

    12 |

    Learn more »

    13 |
    14 |
    15 |

    Get more libraries

    16 |

    NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

    17 |

    Learn more »

    18 |
    19 |
    20 |

    Web Hosting

    21 |

    You can easily find a web hosting company that offers the right mix of features and price for your applications.

    22 |

    Learn more »

    23 |
    24 |
    25 | -------------------------------------------------------------------------------- /UsingTask.Service/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = null; 3 | } 4 | 5 | 6 | 7 | 8 | 9 | Error 10 | 11 | 12 |
    13 |

    Error.

    14 |

    An error occurred while processing your request.

    15 |
    16 | 17 | 18 | -------------------------------------------------------------------------------- /UsingTask.Service/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | @ViewBag.Title 7 | @Styles.Render("~/Content/css") 8 | @Scripts.Render("~/bundles/modernizr") 9 | 10 | 11 | 29 |
    30 | @RenderBody() 31 |
    32 |
    33 |

    © @DateTime.Now.Year - My ASP.NET Application

    34 |
    35 |
    36 | 37 | @Scripts.Render("~/bundles/jquery") 38 | @Scripts.Render("~/bundles/bootstrap") 39 | @RenderSection("scripts", required: false) 40 | 41 | 42 | -------------------------------------------------------------------------------- /UsingTask.Service/Views/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |
    7 |
    8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /UsingTask.Service/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "~/Views/Shared/_Layout.cshtml"; 3 | } 4 | -------------------------------------------------------------------------------- /UsingTask.Service/Web.Debug.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /UsingTask.Service/Web.Release.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /UsingTask.Service/Web.config: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 |
    10 | 11 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /UsingTask.Service/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/using-task/37f01835f1a0005e2cb5db09decda9d83271da1f/UsingTask.Service/favicon.ico -------------------------------------------------------------------------------- /UsingTask.Service/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/using-task/37f01835f1a0005e2cb5db09decda9d83271da1f/UsingTask.Service/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /UsingTask.Service/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/using-task/37f01835f1a0005e2cb5db09decda9d83271da1f/UsingTask.Service/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /UsingTask.Service/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremybytes/using-task/37f01835f1a0005e2cb5db09decda9d83271da1f/UsingTask.Service/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /UsingTask.Service/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /UsingTask.Shared/People.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace UsingTask.Shared 5 | { 6 | public static class People 7 | { 8 | public static List GetPeople() 9 | { 10 | var p = new List() 11 | { 12 | new Person() { Id=1, FirstName="John", LastName="Koenig", 13 | StartDate = new DateTime(1975, 10, 17), Rating=6 }, 14 | new Person() { Id=2, FirstName="Dylan", LastName="Hunt", 15 | StartDate = new DateTime(2000, 10, 2), Rating=8 }, 16 | new Person() { Id=3, FirstName="John", LastName="Crichton", 17 | StartDate = new DateTime(1999, 3, 19), Rating=7 }, 18 | new Person() { Id=4, FirstName="Dave", LastName="Lister", 19 | StartDate = new DateTime(1988, 2, 15), Rating=9 }, 20 | new Person() { Id=5, FirstName="John", LastName="Sheridan", 21 | StartDate = new DateTime(1994, 1, 26), Rating=6 }, 22 | new Person() { Id=6, FirstName="Dante", LastName="Montana", 23 | StartDate = new DateTime(2000, 11, 1), Rating=5 }, 24 | new Person() { Id=7, FirstName="Isaac", LastName="Gampu", 25 | StartDate = new DateTime(1977, 9, 10), Rating=4 } 26 | }; 27 | return p; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /UsingTask.Shared/Person.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace UsingTask.Shared 4 | { 5 | public class Person 6 | { 7 | public int Id { get; set; } 8 | public string FirstName { get; set; } 9 | public string LastName { get; set; } 10 | public DateTime StartDate { get; set; } 11 | public int Rating { get; set; } 12 | 13 | public override string ToString() 14 | { 15 | return string.Format("{0} {1}", FirstName, LastName); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /UsingTask.Shared/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("UsingTask.Shared")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("UsingTask.Shared")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("a600daff-244e-4262-8c77-0ab4cd0682dd")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /UsingTask.Shared/UsingTask.Shared.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {FD4C17EE-177C-4E2A-B22D-F62F350F3DA5} 8 | Library 9 | Properties 10 | UsingTask.Shared 11 | UsingTask.Shared 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 54 | -------------------------------------------------------------------------------- /UsingTask.Tester/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /UsingTask.Tester/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using UsingTask.Library; 5 | using UsingTask.Shared; 6 | 7 | namespace UsingTask.Tester 8 | { 9 | class Program 10 | { 11 | static void Main(string[] args) 12 | { 13 | var repository = new PersonRepository(); 14 | Task> peopleTask = repository.Get(); 15 | peopleTask.ContinueWith(FillConsole, 16 | TaskContinuationOptions.OnlyOnRanToCompletion); 17 | peopleTask.ContinueWith(ShowError, 18 | TaskContinuationOptions.OnlyOnFaulted); 19 | for (int i = 0; i < 5; i++) 20 | Console.WriteLine(i); 21 | Console.ReadLine(); 22 | } 23 | 24 | private static void FillConsole(Task> peopleTask) 25 | { 26 | List people = peopleTask.Result; 27 | foreach (var person in people) 28 | Console.WriteLine(person.ToString()); 29 | } 30 | 31 | private static void ShowError(Task> peopleTask) 32 | { 33 | foreach (var exception in peopleTask.Exception.Flatten().InnerExceptions) 34 | Console.WriteLine("Error: {0}", exception.Message); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /UsingTask.Tester/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("UsingTask.Tester")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("UsingTask.Tester")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("7a43cd5c-35b4-438e-bd29-00b8bad750eb")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /UsingTask.Tester/UsingTask.Tester.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {C926BA2C-F39D-4F4F-9701-20D6528662F6} 8 | Exe 9 | Properties 10 | UsingTask.Tester 11 | UsingTask.Tester 12 | v4.5 13 | 512 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | {abc241ba-6178-4ba1-b34d-a54eff9627ed} 53 | UsingTask.Library 54 | 55 | 56 | {fd4c17ee-177c-4e2a-b22d-f62f350f3da5} 57 | UsingTask.Shared 58 | 59 | 60 | 61 | 68 | -------------------------------------------------------------------------------- /UsingTask.UI/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /UsingTask.UI/App.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | 35 | 36 | 37 | 38 | 39 | 42 | 43 | 44 | 45 | 46 | 49 | 50 | 51 | 52 | 53 | 56 | 57 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 71 | 73 | 76 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 105 | 106 | 107 | 108 | 109 | 112 | 113 | 114 | 115 | 116 | 119 | 120 | 121 | 122 | 123 | 126 | 127 | 128 | 129 | 130 | 133 | 134 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 151 | 152 | 153 | 154 | 155 | 156 | 165 | 166 | 167 | 172 | 173 | 178 | 179 | 184 | 185 | 186 | 187 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 205 | 206 | 208 | 209 | 210 | 212 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | -------------------------------------------------------------------------------- /UsingTask.UI/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | 9 | namespace UsingTask.UI 10 | { 11 | /// 12 | /// Interaction logic for App.xaml 13 | /// 14 | public partial class App : Application 15 | { 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /UsingTask.UI/Converters.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Windows.Data; 4 | using System.Windows.Media; 5 | 6 | namespace UsingTask.UI 7 | { 8 | public class DecadeConverter : IValueConverter 9 | { 10 | public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 11 | { 12 | int year = ((DateTime)value).Year; 13 | return string.Format("{0}0s", year.ToString().Substring(0, 3)); 14 | } 15 | 16 | public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 17 | { 18 | throw new NotImplementedException(); 19 | } 20 | } 21 | 22 | public class RatingConverter : IValueConverter 23 | { 24 | public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 25 | { 26 | int rating = (int)value; 27 | return string.Format("{0}/10 Stars", rating.ToString()); 28 | } 29 | 30 | public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 31 | { 32 | throw new NotImplementedException(); 33 | } 34 | } 35 | 36 | public class RatingStarConverter : IValueConverter 37 | { 38 | public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 39 | { 40 | int rating = (int)value; 41 | string output = string.Empty; 42 | return output.PadLeft(rating, '*'); 43 | } 44 | 45 | public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 46 | { 47 | string input = (string)value; 48 | //int rating = 0; 49 | 50 | //foreach (var ch in input) 51 | // if (ch == '*') 52 | // rating++; 53 | 54 | //return rating; 55 | 56 | return input.Count(c => c == '*'); 57 | } 58 | } 59 | 60 | public class DecadeBrushConverter : IValueConverter 61 | { 62 | public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 63 | { 64 | int decade = (((DateTime)value).Year / 10) * 10; 65 | 66 | switch (decade) 67 | { 68 | case 1970: 69 | return new SolidColorBrush(Colors.Maroon); 70 | case 1980: 71 | return new SolidColorBrush(Colors.DarkGreen); 72 | case 1990: 73 | return new SolidColorBrush(Colors.DarkSlateBlue); 74 | case 2000: 75 | return new SolidColorBrush(Colors.CadetBlue); 76 | default: 77 | return new SolidColorBrush(Colors.DarkSlateGray); 78 | } 79 | } 80 | 81 | public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 82 | { 83 | throw new NotImplementedException(); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /UsingTask.UI/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  7 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |