├── .gitattributes ├── .gitignore ├── LICENSE ├── ProductListCodeSample.sln ├── ProductListCodeSample ├── AppIcon.png ├── AppManifest.xml ├── Features │ └── Feature1 │ │ ├── Feature1.Template.xml │ │ └── Feature1.feature ├── Package │ ├── Package.Template.xml │ └── Package.package ├── ProductListCodeSample.csproj └── Products │ ├── Elements.xml │ ├── ProductsInstance │ ├── Elements.xml │ └── SharePointProjectItem.spdata │ ├── Schema.xml │ └── SharePointProjectItem.spdata ├── ProductListCodeSampleWeb ├── App_Start │ ├── BundleConfig.cs │ ├── FilterConfig.cs │ └── RouteConfig.cs ├── Content │ ├── Site.css │ ├── bootstrap.css │ └── bootstrap.min.css ├── Controllers │ └── HomeController.cs ├── Filters │ └── SharePointContextFilterAttribute.cs ├── Global.asax ├── Global.asax.cs ├── Models │ └── Product.cs ├── ProductListCodeSampleWeb.csproj ├── Project_Readme.html ├── Properties │ └── AssemblyInfo.cs ├── Scripts │ ├── _references.js │ ├── app.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 │ ├── modernizr-2.6.2.js │ ├── respond.js │ ├── respond.min.js │ └── spcontext.js ├── SharePointContext.cs ├── SharePointService.cs ├── TokenHelper.cs ├── Views │ ├── Home │ │ ├── About.cshtml │ │ ├── Contact.cshtml │ │ ├── Delete.cshtml │ │ ├── Edit.cshtml │ │ └── 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 └── README.md /.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 | *.sln.docstates 8 | 9 | # Build results 10 | [Dd]ebug/ 11 | [Dd]ebugPublic/ 12 | [Rr]elease/ 13 | x64/ 14 | build/ 15 | bld/ 16 | [Bb]in/ 17 | [Oo]bj/ 18 | 19 | # MSTest test Results 20 | [Tt]est[Rr]esult*/ 21 | [Bb]uild[Ll]og.* 22 | 23 | #NUNIT 24 | *.VisualState.xml 25 | TestResult.xml 26 | 27 | # Build Results of an ATL Project 28 | [Dd]ebugPS/ 29 | [Rr]eleasePS/ 30 | dlldata.c 31 | 32 | *_i.c 33 | *_p.c 34 | *_i.h 35 | *.ilk 36 | *.meta 37 | *.obj 38 | *.pch 39 | *.pdb 40 | *.pgc 41 | *.pgd 42 | *.rsp 43 | *.sbr 44 | *.tlb 45 | *.tli 46 | *.tlh 47 | *.tmp 48 | *.tmp_proj 49 | *.log 50 | *.vspscc 51 | *.vssscc 52 | .builds 53 | *.pidb 54 | *.svclog 55 | *.scc 56 | 57 | # Chutzpah Test files 58 | _Chutzpah* 59 | 60 | # Visual C++ cache files 61 | ipch/ 62 | *.aps 63 | *.ncb 64 | *.opensdf 65 | *.sdf 66 | *.cachefile 67 | 68 | # Visual Studio profiler 69 | *.psess 70 | *.vsp 71 | *.vspx 72 | 73 | # TFS 2012 Local Workspace 74 | $tf/ 75 | 76 | # Guidance Automation Toolkit 77 | *.gpState 78 | 79 | # ReSharper is a .NET coding add-in 80 | _ReSharper*/ 81 | *.[Rr]e[Ss]harper 82 | *.DotSettings.user 83 | 84 | # JustCode is a .NET coding addin-in 85 | .JustCode 86 | 87 | # TeamCity is a build add-in 88 | _TeamCity* 89 | 90 | # DotCover is a Code Coverage Tool 91 | *.dotCover 92 | 93 | # NCrunch 94 | *.ncrunch* 95 | _NCrunch_* 96 | .*crunch*.local.xml 97 | 98 | # MightyMoose 99 | *.mm.* 100 | AutoTest.Net/ 101 | 102 | # Web workbench (sass) 103 | .sass-cache/ 104 | 105 | # Installshield output folder 106 | [Ee]xpress/ 107 | 108 | # DocProject is a documentation generator add-in 109 | DocProject/buildhelp/ 110 | DocProject/Help/*.HxT 111 | DocProject/Help/*.HxC 112 | DocProject/Help/*.hhc 113 | DocProject/Help/*.hhk 114 | DocProject/Help/*.hhp 115 | DocProject/Help/Html2 116 | DocProject/Help/html 117 | 118 | # Click-Once directory 119 | publish/ 120 | 121 | # Publish Web Output 122 | *.[Pp]ublish.xml 123 | *.azurePubxml 124 | 125 | # NuGet Packages Directory 126 | packages/ 127 | ## TODO: If the tool you use requires repositories.config uncomment the next line 128 | #!packages/repositories.config 129 | 130 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets 131 | # This line needs to be after the ignore of the build folder (and the packages folder if the line above has been uncommented) 132 | !packages/build/ 133 | 134 | # Windows Azure Build Output 135 | csx/ 136 | *.build.csdef 137 | 138 | # Windows Store app package directory 139 | AppPackages/ 140 | 141 | # Others 142 | sql/ 143 | *.Cache 144 | ClientBin/ 145 | [Ss]tyle[Cc]op.* 146 | ~$* 147 | *~ 148 | *.dbmdl 149 | *.dbproj.schemaview 150 | *.pfx 151 | *.publishsettings 152 | node_modules/ 153 | 154 | # RIA/Silverlight projects 155 | Generated_Code/ 156 | 157 | # Backup & report files from converting an old project file to a newer 158 | # Visual Studio version. Backup files are not needed, because we have git ;-) 159 | _UpgradeReport_Files/ 160 | Backup*/ 161 | UpgradeLog*.XML 162 | UpgradeLog*.htm 163 | 164 | # SQL Server files 165 | *.mdf 166 | *.ldf 167 | 168 | # Business Intelligence projects 169 | *.rdl.data 170 | *.bim.layout 171 | *.bim_*.settings 172 | 173 | # Microsoft Fakes 174 | FakesAssemblies/ 175 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /ProductListCodeSample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.30501.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProductListCodeSample", "ProductListCodeSample\ProductListCodeSample.csproj", "{4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProductListCodeSampleWeb", "ProductListCodeSampleWeb\ProductListCodeSampleWeb.csproj", "{6F93EA5E-DF16-48D0-8D71-BC6ECBC06EC6}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0}.Debug|Any CPU.Deploy.0 = Debug|Any CPU 19 | {4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0}.Release|Any CPU.Build.0 = Release|Any CPU 21 | {4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0}.Release|Any CPU.Deploy.0 = Release|Any CPU 22 | {6F93EA5E-DF16-48D0-8D71-BC6ECBC06EC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {6F93EA5E-DF16-48D0-8D71-BC6ECBC06EC6}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {6F93EA5E-DF16-48D0-8D71-BC6ECBC06EC6}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {6F93EA5E-DF16-48D0-8D71-BC6ECBC06EC6}.Release|Any CPU.Build.0 = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(SolutionProperties) = preSolution 28 | HideSolutionNode = FALSE 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /ProductListCodeSample/AppIcon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/Product-List-Code-Sample/a8bf2134b1de93394c1e6d03b680043af1b75472/ProductListCodeSample/AppIcon.png -------------------------------------------------------------------------------- /ProductListCodeSample/AppManifest.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 9 | 10 | Product List Code Sample 11 | ~remoteAppUrl/?{StandardTokens} 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /ProductListCodeSample/Features/Feature1/Feature1.Template.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | -------------------------------------------------------------------------------- /ProductListCodeSample/Features/Feature1/Feature1.feature: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /ProductListCodeSample/Package/Package.Template.xml: -------------------------------------------------------------------------------- 1 |  2 | -------------------------------------------------------------------------------- /ProductListCodeSample/Package/Package.package: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ProductListCodeSample/ProductListCodeSample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {4CADEFA6-48C6-4D1E-9D5B-34DD6A1F8DD0} 8 | Library 9 | Properties 10 | SharePointAppSample 11 | SharePointAppSample 12 | v4.5 13 | 15.0 14 | 512 15 | {C1CDDADD-2546-481F-9697-4EA41081F2FC};{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 16 | False 17 | SharePointApp 18 | {0e713410-3d88-4490-88ff-936799d27aad} 19 | {a3c44afa-bfd1-4b23-8a7f-02f282ed9c61} 20 | {63901990-03ff-410a-9591-f102420d17aa} 21 | {a06aae98-3d5a-4a74-8eaf-cf271e74c457} 22 | {a4f717d5-f194-4cc4-abfb-19883096305a} 23 | 24 | 25 | true 26 | full 27 | false 28 | bin\Debug\ 29 | DEBUG;TRACE 30 | prompt 31 | 4 32 | false 33 | 34 | 35 | pdbonly 36 | true 37 | bin\Release\ 38 | TRACE 39 | prompt 40 | 4 41 | false 42 | 43 | 44 | 45 | manifest-icon 46 | 47 | 48 | Feature1.feature 49 | 50 | 51 | Package.package 52 | 53 | 54 | Designer 55 | 56 | 57 | 58 | 59 | 60 | 61 | Designer 62 | 63 | 64 | 65 | 66 | {6F93EA5E-DF16-48D0-8D71-BC6ECBC06EC6} 67 | ProductListCodeSampleWeb 68 | True 69 | Web 70 | SharePointWebProjectOutput 71 | SharePointAppSampleWeb 72 | False 73 | 74 | 75 | 76 | 77 | {8aa51de9-9486-48f4-9ba7-7834bbd8de05} 78 | 79 | 80 | {17aba39d-d320-4eb7-9a89-46eb2fa18e3a} 81 | 82 | 83 | {8a7a7560-8073-4aaa-adb3-e53fc346ccd6} 84 | 85 | 86 | {5d3afbe2-3f26-4104-9a6e-e5de01b5ca19} 87 | 88 | 89 | 90 | 91 | 10.0 92 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 93 | 94 | 95 | -------------------------------------------------------------------------------- /ProductListCodeSample/Products/Elements.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 14 | 15 | -------------------------------------------------------------------------------- /ProductListCodeSample/Products/ProductsInstance/Elements.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | Product 1 8 | Description for Product 1 9 | $7.99 10 | 11 | 12 | Product 2 13 | Description for Product 2 14 | $5.99 15 | 16 | 17 | Product 3 18 | Description for Product 3 19 | $9.99 20 | 21 | 22 | Product 3 23 | Description for Product 3 24 | $6.99 25 | 26 | 27 | Product 4 28 | Description for Product 4 29 | $8.99 30 | 31 | 32 | Product 5 33 | Description for Product 5 34 | $8.99 35 | 36 | 37 | Product 6 38 | Description for Product 6 39 | $9.99 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /ProductListCodeSample/Products/ProductsInstance/SharePointProjectItem.spdata: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ProductListCodeSample/Products/Schema.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | main.xsl 19 | 30 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | main.xsl 36 | clienttemplates.js 37 | 30 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 |
53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /ProductListCodeSample/Products/SharePointProjectItem.spdata: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/App_Start/BundleConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Optimization; 3 | 4 | namespace SharePointAppSampleWeb 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 ScriptBundle("~/bundles/spcontext").Include( 24 | "~/Scripts/spcontext.js")); 25 | 26 | bundles.Add(new StyleBundle("~/Content/css").Include( 27 | "~/Content/bootstrap.css", 28 | "~/Content/site.css")); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Mvc; 3 | 4 | namespace SharePointAppSampleWeb 5 | { 6 | public class FilterConfig 7 | { 8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 | { 10 | filters.Add(new HandleErrorAttribute()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/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 SharePointAppSampleWeb 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 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/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 | 19 | /* styles for validation helpers */ 20 | .field-validation-error { 21 | color: #b94a48; 22 | } 23 | 24 | .field-validation-valid { 25 | display: none; 26 | } 27 | 28 | input.input-validation-error { 29 | border: 1px solid #b94a48; 30 | } 31 | 32 | input[type="checkbox"].input-validation-error { 33 | border: 0 none; 34 | } 35 | 36 | .validation-summary-errors { 37 | color: #b94a48; 38 | } 39 | 40 | .validation-summary-valid { 41 | display: none; 42 | } -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.SharePoint.Client; 2 | using SharePointAppSampleWeb.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Web; 8 | using System.Web.Mvc; 9 | 10 | namespace SharePointAppSampleWeb.Controllers 11 | { 12 | public class HomeController : Controller 13 | { 14 | [SharePointContextFilter] 15 | public ActionResult Index() 16 | { 17 | var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); 18 | 19 | ViewBag.Username = SharePointService.GetUserName(spContext); 20 | 21 | CamlQuery queryProducts = new CamlQuery(); 22 | queryProducts.ViewXml = @" 23 | 24 | "; 25 | 26 | List products = SharePointService.GetProducts(spContext, queryProducts); 27 | 28 | return View(products); 29 | } 30 | 31 | [SharePointContextFilter] 32 | public ActionResult Edit(int id) 33 | { 34 | var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); 35 | 36 | Product product = SharePointService.GetProductDetails(spContext, id); 37 | return View(product); 38 | } 39 | 40 | [SharePointContextFilter] 41 | [HttpPost] 42 | public ActionResult Edit(Product product) 43 | { 44 | var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); 45 | 46 | SharePointService.UpdateProduct(spContext, product); 47 | return RedirectToAction("Index", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri }); 48 | } 49 | 50 | [SharePointContextFilter] 51 | public ActionResult Delete(int id) 52 | { 53 | var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); 54 | 55 | Product product = SharePointService.GetProductDetails(spContext, id); 56 | return View(product); 57 | } 58 | 59 | [SharePointContextFilter] 60 | [HttpPost] 61 | public ActionResult Delete(Product product) 62 | { 63 | var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); 64 | 65 | SharePointService.DeleteProduct(spContext, product); 66 | return RedirectToAction("Index", new { SPHostUrl = SharePointContext.GetSPHostUrl(HttpContext.Request).AbsoluteUri }); 67 | } 68 | 69 | [HttpPost] 70 | [SharePointContextFilter] 71 | public ActionResult AddProduct(string title,string description,string price) 72 | { 73 | HttpStatusCodeResult httpCode = new HttpStatusCodeResult(HttpStatusCode.MethodNotAllowed); 74 | 75 | var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext); 76 | 77 | Product newProduct = new Product(); 78 | newProduct.Title = title; 79 | newProduct.Description = description; 80 | newProduct.Price = price; 81 | 82 | if (SharePointService.AddProduct(spContext, newProduct)) 83 | { 84 | httpCode = new HttpStatusCodeResult(HttpStatusCode.Created); 85 | } 86 | 87 | return httpCode; 88 | } 89 | 90 | public ActionResult About() 91 | { 92 | ViewBag.Message = "Your application description page."; 93 | 94 | return View(); 95 | } 96 | 97 | public ActionResult Contact() 98 | { 99 | ViewBag.Message = "Your contact page."; 100 | 101 | return View(); 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Filters/SharePointContextFilterAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Web.Mvc; 3 | 4 | namespace SharePointAppSampleWeb 5 | { 6 | /// 7 | /// SharePoint action filter attribute. 8 | /// 9 | public class SharePointContextFilterAttribute : ActionFilterAttribute 10 | { 11 | public override void OnActionExecuting(ActionExecutingContext filterContext) 12 | { 13 | if (filterContext == null) 14 | { 15 | throw new ArgumentNullException("filterContext"); 16 | } 17 | 18 | Uri redirectUrl; 19 | switch (SharePointContextProvider.CheckRedirectionStatus(filterContext.HttpContext, out redirectUrl)) 20 | { 21 | case RedirectionStatus.Ok: 22 | return; 23 | case RedirectionStatus.ShouldRedirect: 24 | filterContext.Result = new RedirectResult(redirectUrl.AbsoluteUri); 25 | break; 26 | case RedirectionStatus.CanNotRedirect: 27 | filterContext.Result = new ViewResult { ViewName = "Error" }; 28 | break; 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="SharePointAppSampleWeb.MvcApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Global.asax.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.Optimization; 7 | using System.Web.Routing; 8 | 9 | namespace SharePointAppSampleWeb 10 | { 11 | public class MvcApplication : System.Web.HttpApplication 12 | { 13 | protected void Application_Start() 14 | { 15 | AreaRegistration.RegisterAllAreas(); 16 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 17 | RouteConfig.RegisterRoutes(RouteTable.Routes); 18 | BundleConfig.RegisterBundles(BundleTable.Bundles); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Models/Product.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | 6 | namespace SharePointAppSampleWeb.Models 7 | { 8 | public class Product 9 | { 10 | public int Id { get; set; } 11 | public string Title { get; set; } 12 | 13 | public string Description { get; set; } 14 | 15 | public string Price { get; set; } 16 | } 17 | } -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/ProductListCodeSampleWeb.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | 8 | 9 | 2.0 10 | {6F93EA5E-DF16-48D0-8D71-BC6ECBC06EC6} 11 | {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} 12 | Library 13 | Properties 14 | SharePointAppSampleWeb 15 | SharePointAppSampleWeb 16 | v4.5 17 | false 18 | true 19 | 44320 20 | 21 | 22 | 23 | 15.0 24 | 25 | 26 | true 27 | full 28 | false 29 | bin\ 30 | DEBUG;TRACE 31 | prompt 32 | 4 33 | 34 | 35 | pdbonly 36 | true 37 | bin\ 38 | TRACE 39 | prompt 40 | 4 41 | 42 | 43 | 44 | 45 | True 46 | 47 | 48 | True 49 | 50 | 51 | True 52 | 53 | 54 | True 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | True 79 | ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll 80 | 81 | 82 | 83 | 84 | 85 | 86 | True 87 | ..\packages\Microsoft.AspNet.WebPages.3.0.0\lib\net45\System.Web.Helpers.dll 88 | 89 | 90 | True 91 | ..\packages\Microsoft.AspNet.Mvc.5.0.0\lib\net45\System.Web.Mvc.dll 92 | 93 | 94 | ..\packages\Microsoft.AspNet.Web.Optimization.1.1.1\lib\net40\System.Web.Optimization.dll 95 | 96 | 97 | True 98 | ..\packages\Microsoft.AspNet.Razor.3.0.0\lib\net45\System.Web.Razor.dll 99 | 100 | 101 | True 102 | ..\packages\Microsoft.AspNet.WebPages.3.0.0\lib\net45\System.Web.WebPages.dll 103 | 104 | 105 | True 106 | ..\packages\Microsoft.AspNet.WebPages.3.0.0\lib\net45\System.Web.WebPages.Deployment.dll 107 | 108 | 109 | True 110 | ..\packages\Microsoft.AspNet.WebPages.3.0.0\lib\net45\System.Web.WebPages.Razor.dll 111 | 112 | 113 | True 114 | ..\packages\Newtonsoft.Json.5.0.6\lib\net45\Newtonsoft.Json.dll 115 | 116 | 117 | True 118 | ..\packages\WebGrease.1.5.2\lib\WebGrease.dll 119 | 120 | 121 | True 122 | ..\packages\Antlr.3.4.1.9004\lib\Antlr3.Runtime.dll 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | Global.asax 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | Web.config 164 | 165 | 166 | Web.config 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 10.0 189 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | True 202 | True 203 | 22066 204 | / 205 | http://localhost:22066/ 206 | False 207 | False 208 | 209 | 210 | False 211 | 212 | 213 | 214 | 215 | 221 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/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 |
  • Sample pages showing basic nav between Home, About, and Contact
  • 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 | 131 | 132 |
133 |

Deploy

134 | 139 |
140 | 141 |
142 |

Get help

143 | 147 |
148 |
149 | 150 | 151 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/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("SharePointAppSampleWeb")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SharePointAppSampleWeb")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 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("ae5d78df-c6c7-44a4-a70a-a9cdde347171")] 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 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Scripts/_references.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/Product-List-Code-Sample/a8bf2134b1de93394c1e6d03b680043af1b75472/ProductListCodeSampleWeb/Scripts/_references.js -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Scripts/app.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function () { 2 | 3 | $("#btnSaveProduct").click(function (e) { 4 | e.preventDefault(); 5 | 6 | var spHostUrl = getSPHostUrlFromQueryString(window.location.search); 7 | 8 | var urlAddProduct = "/Home/AddProduct?SPHostUrl=" + spHostUrl; 9 | 10 | $.post(urlAddProduct, 11 | { 12 | title: $("#productTitle").val(), 13 | description: $("#productDescription").val(), 14 | price: $("#productPrice").val(), 15 | }).done(function () { 16 | $("#myModal").modal('hide'); 17 | location.reload(); 18 | }) 19 | .fail(function () { 20 | alert("Failed to add the new product!"); 21 | }); 22 | }); 23 | 24 | // Gets SPHostUrl from the given query string. 25 | function getSPHostUrlFromQueryString(queryString) { 26 | if (queryString) { 27 | if (queryString[0] === "?") { 28 | queryString = queryString.substring(1); 29 | } 30 | 31 | var keyValuePairArray = queryString.split("&"); 32 | 33 | for (var i = 0; i < keyValuePairArray.length; i++) { 34 | var currentKeyValuePair = keyValuePairArray[i].split("="); 35 | 36 | if (currentKeyValuePair.length > 1 && currentKeyValuePair[0] == "SPHostUrl") { 37 | return currentKeyValuePair[1]; 38 | } 39 | } 40 | } 41 | 42 | return null; 43 | } 44 | 45 | }); -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Scripts/bootstrap.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 | /** 17 | * bootstrap.js v3.0.0 by @fat and @mdo 18 | * Copyright 2013 Twitter Inc. 19 | * http://www.apache.org/licenses/LICENSE-2.0 20 | */ 21 | if(!jQuery)throw new Error("Bootstrap requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]}}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(window.jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d)};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.is("input")?"val":"html",e=c.data();a+="Text",e.resetText||c.data("resetText",c[d]()),c[d](e[a]||this.options[a]),setTimeout(function(){"loadingText"==a?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons"]');if(a.length){var b=this.$element.find("input").prop("checked",!this.$element.hasClass("active")).trigger("change");"radio"===b.prop("type")&&a.find(".active").removeClass("active")}this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(window.jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}this.sliding=!0,f&&this.pause();var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});if(!e.hasClass("active")){if(this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")){if(this.$element.trigger(j),j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)}).emulateTransitionEnd(600)}else{if(this.$element.trigger(j),j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this}};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?(this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350),void 0):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(window.jQuery),+function(a){"use strict";function b(){a(d).remove(),a(e).each(function(b){var d=c(a(this));d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown")),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown"))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){if("ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(''}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(window.jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(c).is("body")?a(window):a(c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#\w/.test(e)&&a(e);return f&&f.length&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parents(".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(window.jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.attr("data-target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top()),"function"==typeof h&&(h=f.bottom());var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;this.affixed!==i&&(this.unpin&&this.$element.css("top",""),this.affixed=i,this.unpin="bottom"==i?e.top-d:null,this.$element.removeClass(b.RESET).addClass("affix"+(i?"-"+i:"")),"bottom"==i&&this.$element.offset({top:document.body.offsetHeight-h-this.$element.height()}))}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery); -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/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 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/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); -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Scripts/spcontext.js: -------------------------------------------------------------------------------- 1 | (function (window, undefined) { 2 | 3 | "use strict"; 4 | 5 | var $ = window.jQuery; 6 | var document = window.document; 7 | 8 | // SPHostUrl parameter name 9 | var SPHostUrlKey = "SPHostUrl"; 10 | 11 | // Gets SPHostUrl from the current URL and appends it as query string to the links which point to current domain in the page. 12 | $(document).ready(function () { 13 | ensureSPHasRedirectedToSharePointRemoved(); 14 | 15 | var spHostUrl = getSPHostUrlFromQueryString(window.location.search); 16 | var currentAuthority = getAuthorityFromUrl(window.location.href).toUpperCase(); 17 | 18 | if (spHostUrl && currentAuthority) { 19 | appendSPHostUrlToLinks(spHostUrl, currentAuthority); 20 | } 21 | }); 22 | 23 | // Appends SPHostUrl as query string to all the links which point to current domain. 24 | function appendSPHostUrlToLinks(spHostUrl, currentAuthority) { 25 | $("a") 26 | .filter(function () { 27 | var authority = getAuthorityFromUrl(this.href); 28 | if (!authority && /^#|:/.test(this.href)) { 29 | // Filters out anchors and urls with other unsupported protocols. 30 | return false; 31 | } 32 | return authority.toUpperCase() == currentAuthority; 33 | }) 34 | .each(function () { 35 | if (!getSPHostUrlFromQueryString(this.search)) { 36 | if (this.search.length > 0) { 37 | this.search += "&" + SPHostUrlKey + "=" + spHostUrl; 38 | } 39 | else { 40 | this.search = "?" + SPHostUrlKey + "=" + spHostUrl; 41 | } 42 | } 43 | }); 44 | } 45 | 46 | // Gets SPHostUrl from the given query string. 47 | function getSPHostUrlFromQueryString(queryString) { 48 | if (queryString) { 49 | if (queryString[0] === "?") { 50 | queryString = queryString.substring(1); 51 | } 52 | 53 | var keyValuePairArray = queryString.split("&"); 54 | 55 | for (var i = 0; i < keyValuePairArray.length; i++) { 56 | var currentKeyValuePair = keyValuePairArray[i].split("="); 57 | 58 | if (currentKeyValuePair.length > 1 && currentKeyValuePair[0] == SPHostUrlKey) { 59 | return currentKeyValuePair[1]; 60 | } 61 | } 62 | } 63 | 64 | return null; 65 | } 66 | 67 | // Gets authority from the given url when it is an absolute url with http/https protocol or a protocol relative url. 68 | function getAuthorityFromUrl(url) { 69 | if (url) { 70 | var match = /^(?:https:\/\/|http:\/\/|\/\/)([^\/\?#]+)(?:\/|#|$|\?)/i.exec(url); 71 | if (match) { 72 | return match[1]; 73 | } 74 | } 75 | return null; 76 | } 77 | 78 | // If SPHasRedirectedToSharePoint exists in the query string, remove it. 79 | // Hence, when user bookmarks the url, SPHasRedirectedToSharePoint will not be included. 80 | // Note that modifying window.location.search will cause an additional request to server. 81 | function ensureSPHasRedirectedToSharePointRemoved() { 82 | var SPHasRedirectedToSharePointParam = "&SPHasRedirectedToSharePoint=1"; 83 | 84 | var queryString = window.location.search; 85 | 86 | if (queryString.indexOf(SPHasRedirectedToSharePointParam) >= 0) { 87 | window.location.search = queryString.replace(SPHasRedirectedToSharePointParam, ""); 88 | } 89 | } 90 | 91 | })(window); 92 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/SharePointContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.IdentityModel.S2S.Protocols.OAuth2; 2 | using Microsoft.IdentityModel.Tokens; 3 | using Microsoft.SharePoint.Client; 4 | using System; 5 | using System.Net; 6 | using System.Security.Principal; 7 | using System.Web; 8 | using System.Web.Configuration; 9 | 10 | namespace SharePointAppSampleWeb 11 | { 12 | /// 13 | /// Encapsulates all the information from SharePoint. 14 | /// 15 | public abstract class SharePointContext 16 | { 17 | public const string SPHostUrlKey = "SPHostUrl"; 18 | public const string SPAppWebUrlKey = "SPAppWebUrl"; 19 | public const string SPLanguageKey = "SPLanguage"; 20 | public const string SPClientTagKey = "SPClientTag"; 21 | public const string SPProductNumberKey = "SPProductNumber"; 22 | 23 | protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); 24 | 25 | private readonly Uri spHostUrl; 26 | private readonly Uri spAppWebUrl; 27 | private readonly string spLanguage; 28 | private readonly string spClientTag; 29 | private readonly string spProductNumber; 30 | 31 | // 32 | protected Tuple userAccessTokenForSPHost; 33 | protected Tuple userAccessTokenForSPAppWeb; 34 | protected Tuple appOnlyAccessTokenForSPHost; 35 | protected Tuple appOnlyAccessTokenForSPAppWeb; 36 | 37 | /// 38 | /// Gets the SharePoint host url from QueryString of the specified HTTP request. 39 | /// 40 | /// The specified HTTP request. 41 | /// The SharePoint host url. Returns null if the HTTP request doesn't contain the SharePoint host url. 42 | public static Uri GetSPHostUrl(HttpRequestBase httpRequest) 43 | { 44 | if (httpRequest == null) 45 | { 46 | throw new ArgumentNullException("httpRequest"); 47 | } 48 | 49 | string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); 50 | Uri spHostUrl; 51 | if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && 52 | (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) 53 | { 54 | return spHostUrl; 55 | } 56 | 57 | return null; 58 | } 59 | 60 | /// 61 | /// Gets the SharePoint host url from QueryString of the specified HTTP request. 62 | /// 63 | /// The specified HTTP request. 64 | /// The SharePoint host url. Returns null if the HTTP request doesn't contain the SharePoint host url. 65 | public static Uri GetSPHostUrl(HttpRequest httpRequest) 66 | { 67 | return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); 68 | } 69 | 70 | /// 71 | /// The SharePoint host url. 72 | /// 73 | public Uri SPHostUrl 74 | { 75 | get { return this.spHostUrl; } 76 | } 77 | 78 | /// 79 | /// The SharePoint app web url. 80 | /// 81 | public Uri SPAppWebUrl 82 | { 83 | get { return this.spAppWebUrl; } 84 | } 85 | 86 | /// 87 | /// The SharePoint language. 88 | /// 89 | public string SPLanguage 90 | { 91 | get { return this.spLanguage; } 92 | } 93 | 94 | /// 95 | /// The SharePoint client tag. 96 | /// 97 | public string SPClientTag 98 | { 99 | get { return this.spClientTag; } 100 | } 101 | 102 | /// 103 | /// The SharePoint product number. 104 | /// 105 | public string SPProductNumber 106 | { 107 | get { return this.spProductNumber; } 108 | } 109 | 110 | /// 111 | /// The user access token for the SharePoint host. 112 | /// 113 | public abstract string UserAccessTokenForSPHost 114 | { 115 | get; 116 | } 117 | 118 | /// 119 | /// The user access token for the SharePoint app web. 120 | /// 121 | public abstract string UserAccessTokenForSPAppWeb 122 | { 123 | get; 124 | } 125 | 126 | /// 127 | /// The app only access token for the SharePoint host. 128 | /// 129 | public abstract string AppOnlyAccessTokenForSPHost 130 | { 131 | get; 132 | } 133 | 134 | /// 135 | /// The app only access token for the SharePoint app web. 136 | /// 137 | public abstract string AppOnlyAccessTokenForSPAppWeb 138 | { 139 | get; 140 | } 141 | 142 | /// 143 | /// Constructor. 144 | /// 145 | /// The SharePoint host url. 146 | /// The SharePoint app web url. 147 | /// The SharePoint language. 148 | /// The SharePoint client tag. 149 | /// The SharePoint product number. 150 | protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) 151 | { 152 | if (spHostUrl == null) 153 | { 154 | throw new ArgumentNullException("spHostUrl"); 155 | } 156 | 157 | if (string.IsNullOrEmpty(spLanguage)) 158 | { 159 | throw new ArgumentNullException("spLanguage"); 160 | } 161 | 162 | if (string.IsNullOrEmpty(spClientTag)) 163 | { 164 | throw new ArgumentNullException("spClientTag"); 165 | } 166 | 167 | if (string.IsNullOrEmpty(spProductNumber)) 168 | { 169 | throw new ArgumentNullException("spProductNumber"); 170 | } 171 | 172 | this.spHostUrl = spHostUrl; 173 | this.spAppWebUrl = spAppWebUrl; 174 | this.spLanguage = spLanguage; 175 | this.spClientTag = spClientTag; 176 | this.spProductNumber = spProductNumber; 177 | } 178 | 179 | /// 180 | /// Creates a user ClientContext for the SharePoint host. 181 | /// 182 | /// A ClientContext instance. 183 | public ClientContext CreateUserClientContextForSPHost() 184 | { 185 | return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); 186 | } 187 | 188 | /// 189 | /// Creates a user ClientContext for the SharePoint app web. 190 | /// 191 | /// A ClientContext instance. 192 | public ClientContext CreateUserClientContextForSPAppWeb() 193 | { 194 | return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); 195 | } 196 | 197 | /// 198 | /// Creates app only ClientContext for the SharePoint host. 199 | /// 200 | /// A ClientContext instance. 201 | public ClientContext CreateAppOnlyClientContextForSPHost() 202 | { 203 | return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); 204 | } 205 | 206 | /// 207 | /// Creates an app only ClientContext for the SharePoint app web. 208 | /// 209 | /// A ClientContext instance. 210 | public ClientContext CreateAppOnlyClientContextForSPAppWeb() 211 | { 212 | return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); 213 | } 214 | 215 | /// 216 | /// Gets the database connection string from SharePoint for autohosted app. 217 | /// 218 | /// The database connection string. Returns null if the app is not autohosted or there is no database. 219 | public string GetDatabaseConnectionString() 220 | { 221 | string dbConnectionString = null; 222 | 223 | using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) 224 | { 225 | if (clientContext != null) 226 | { 227 | var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); 228 | 229 | clientContext.ExecuteQuery(); 230 | 231 | dbConnectionString = result.Value; 232 | } 233 | } 234 | 235 | if (dbConnectionString == null) 236 | { 237 | const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; 238 | 239 | var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; 240 | 241 | dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; 242 | } 243 | 244 | return dbConnectionString; 245 | } 246 | 247 | /// 248 | /// Determines if the specified access token is valid. 249 | /// It considers an access token as not valid if it is null, or it has expired. 250 | /// 251 | /// The access token to verify. 252 | /// True if the access token is valid. 253 | protected static bool IsAccessTokenValid(Tuple accessToken) 254 | { 255 | return accessToken != null && 256 | !string.IsNullOrEmpty(accessToken.Item1) && 257 | accessToken.Item2 > DateTime.UtcNow; 258 | } 259 | 260 | /// 261 | /// Creates a ClientContext with the specified SharePoint site url and the access token. 262 | /// 263 | /// The site url. 264 | /// The access token. 265 | /// A ClientContext instance. 266 | private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) 267 | { 268 | if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) 269 | { 270 | return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); 271 | } 272 | 273 | return null; 274 | } 275 | } 276 | 277 | /// 278 | /// Redirection status. 279 | /// 280 | public enum RedirectionStatus 281 | { 282 | Ok, 283 | ShouldRedirect, 284 | CanNotRedirect 285 | } 286 | 287 | /// 288 | /// Provides SharePointContext instances. 289 | /// 290 | public abstract class SharePointContextProvider 291 | { 292 | private static SharePointContextProvider current; 293 | 294 | /// 295 | /// The current SharePointContextProvider instance. 296 | /// 297 | public static SharePointContextProvider Current 298 | { 299 | get { return SharePointContextProvider.current; } 300 | } 301 | 302 | /// 303 | /// Initializes the default SharePointContextProvider instance. 304 | /// 305 | static SharePointContextProvider() 306 | { 307 | if (!TokenHelper.IsHighTrustApp()) 308 | { 309 | SharePointContextProvider.current = new SharePointAcsContextProvider(); 310 | } 311 | else 312 | { 313 | SharePointContextProvider.current = new SharePointHighTrustContextProvider(); 314 | } 315 | } 316 | 317 | /// 318 | /// Registers the specified SharePointContextProvider instance as current. 319 | /// It should be called by Application_Start() in Global.asax. 320 | /// 321 | /// The SharePointContextProvider to be set as current. 322 | public static void Register(SharePointContextProvider provider) 323 | { 324 | if (provider == null) 325 | { 326 | throw new ArgumentNullException("provider"); 327 | } 328 | 329 | SharePointContextProvider.current = provider; 330 | } 331 | 332 | /// 333 | /// Checks if it is necessary to redirect to SharePoint for user to authenticate. 334 | /// 335 | /// The HTTP context. 336 | /// The redirect url to SharePoint if the status is ShouldRedirect. Null if the status is Ok or CanNotRedirect. 337 | /// Redirection status. 338 | public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) 339 | { 340 | if (httpContext == null) 341 | { 342 | throw new ArgumentNullException("httpContext"); 343 | } 344 | 345 | redirectUrl = null; 346 | 347 | if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) 348 | { 349 | return RedirectionStatus.Ok; 350 | } 351 | 352 | const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; 353 | 354 | if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) 355 | { 356 | return RedirectionStatus.CanNotRedirect; 357 | } 358 | 359 | Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); 360 | 361 | if (spHostUrl == null) 362 | { 363 | return RedirectionStatus.CanNotRedirect; 364 | } 365 | 366 | if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) 367 | { 368 | return RedirectionStatus.CanNotRedirect; 369 | } 370 | 371 | Uri requestUrl = httpContext.Request.Url; 372 | 373 | var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); 374 | 375 | // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. 376 | queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); 377 | queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); 378 | queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); 379 | queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); 380 | queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); 381 | 382 | // Adds SPHasRedirectedToSharePoint=1. 383 | queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); 384 | 385 | UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); 386 | returnUrlBuilder.Query = queryNameValueCollection.ToString(); 387 | 388 | // Inserts StandardTokens. 389 | const string StandardTokens = "{StandardTokens}"; 390 | string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; 391 | returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); 392 | 393 | // Constructs redirect url. 394 | string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); 395 | 396 | redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); 397 | 398 | return RedirectionStatus.ShouldRedirect; 399 | } 400 | 401 | /// 402 | /// Checks if it is necessary to redirect to SharePoint for user to authenticate. 403 | /// 404 | /// The HTTP context. 405 | /// The redirect url to SharePoint if the status is ShouldRedirect. Null if the status is Ok or CanNotRedirect. 406 | /// Redirection status. 407 | public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) 408 | { 409 | return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); 410 | } 411 | 412 | /// 413 | /// Creates a SharePointContext instance with the specified HTTP request. 414 | /// 415 | /// The HTTP request. 416 | /// The SharePointContext instance. Returns null if errors occur. 417 | public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) 418 | { 419 | if (httpRequest == null) 420 | { 421 | throw new ArgumentNullException("httpRequest"); 422 | } 423 | 424 | // SPHostUrl 425 | Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); 426 | if (spHostUrl == null) 427 | { 428 | return null; 429 | } 430 | 431 | // SPAppWebUrl 432 | string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); 433 | Uri spAppWebUrl; 434 | if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || 435 | !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) 436 | { 437 | spAppWebUrl = null; 438 | } 439 | 440 | // SPLanguage 441 | string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; 442 | if (string.IsNullOrEmpty(spLanguage)) 443 | { 444 | return null; 445 | } 446 | 447 | // SPClientTag 448 | string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; 449 | if (string.IsNullOrEmpty(spClientTag)) 450 | { 451 | return null; 452 | } 453 | 454 | // SPProductNumber 455 | string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; 456 | if (string.IsNullOrEmpty(spProductNumber)) 457 | { 458 | return null; 459 | } 460 | 461 | return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); 462 | } 463 | 464 | /// 465 | /// Creates a SharePointContext instance with the specified HTTP request. 466 | /// 467 | /// The HTTP request. 468 | /// The SharePointContext instance. Returns null if errors occur. 469 | public SharePointContext CreateSharePointContext(HttpRequest httpRequest) 470 | { 471 | return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); 472 | } 473 | 474 | /// 475 | /// Gets a SharePointContext instance associated with the specified HTTP context. 476 | /// 477 | /// The HTTP context. 478 | /// The SharePointContext instance. Returns null if not found and a new instance can't be created. 479 | public SharePointContext GetSharePointContext(HttpContextBase httpContext) 480 | { 481 | if (httpContext == null) 482 | { 483 | throw new ArgumentNullException("httpContext"); 484 | } 485 | 486 | Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); 487 | if (spHostUrl == null) 488 | { 489 | return null; 490 | } 491 | 492 | SharePointContext spContext = LoadSharePointContext(httpContext); 493 | 494 | if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) 495 | { 496 | spContext = CreateSharePointContext(httpContext.Request); 497 | 498 | if (spContext != null) 499 | { 500 | SaveSharePointContext(spContext, httpContext); 501 | } 502 | } 503 | 504 | return spContext; 505 | } 506 | 507 | /// 508 | /// Gets a SharePointContext instance associated with the specified HTTP context. 509 | /// 510 | /// The HTTP context. 511 | /// The SharePointContext instance. Returns null if not found and a new instance can't be created. 512 | public SharePointContext GetSharePointContext(HttpContext httpContext) 513 | { 514 | return GetSharePointContext(new HttpContextWrapper(httpContext)); 515 | } 516 | 517 | /// 518 | /// Creates a SharePointContext instance. 519 | /// 520 | /// The SharePoint host url. 521 | /// The SharePoint app web url. 522 | /// The SharePoint language. 523 | /// The SharePoint client tag. 524 | /// The SharePoint product number. 525 | /// The HTTP request. 526 | /// The SharePointContext instance. Returns null if errors occur. 527 | protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); 528 | 529 | /// 530 | /// Validates if the given SharePointContext can be used with the specified HTTP context. 531 | /// 532 | /// The SharePointContext. 533 | /// The HTTP context. 534 | /// True if the given SharePointContext can be used with the specified HTTP context. 535 | protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); 536 | 537 | /// 538 | /// Loads the SharePointContext instance associated with the specified HTTP context. 539 | /// 540 | /// The HTTP context. 541 | /// The SharePointContext instance. Returns null if not found. 542 | protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); 543 | 544 | /// 545 | /// Saves the specified SharePointContext instance associated with the specified HTTP context. 546 | /// null is accepted for clearing the SharePointContext instance associated with the HTTP context. 547 | /// 548 | /// The SharePointContext instance to be saved, or null. 549 | /// The HTTP context. 550 | protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); 551 | } 552 | 553 | #region ACS 554 | 555 | /// 556 | /// Encapsulates all the information from SharePoint in ACS mode. 557 | /// 558 | public class SharePointAcsContext : SharePointContext 559 | { 560 | private readonly string contextToken; 561 | private readonly SharePointContextToken contextTokenObj; 562 | 563 | /// 564 | /// The context token. 565 | /// 566 | public string ContextToken 567 | { 568 | get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } 569 | } 570 | 571 | /// 572 | /// The context token's "CacheKey" claim. 573 | /// 574 | public string CacheKey 575 | { 576 | get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } 577 | } 578 | 579 | /// 580 | /// The context token's "refreshtoken" claim. 581 | /// 582 | public string RefreshToken 583 | { 584 | get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } 585 | } 586 | 587 | public override string UserAccessTokenForSPHost 588 | { 589 | get 590 | { 591 | return GetAccessTokenString(ref this.userAccessTokenForSPHost, 592 | () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); 593 | } 594 | } 595 | 596 | public override string UserAccessTokenForSPAppWeb 597 | { 598 | get 599 | { 600 | if (this.SPAppWebUrl == null) 601 | { 602 | return null; 603 | } 604 | 605 | return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, 606 | () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); 607 | } 608 | } 609 | 610 | public override string AppOnlyAccessTokenForSPHost 611 | { 612 | get 613 | { 614 | return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, 615 | () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); 616 | } 617 | } 618 | 619 | public override string AppOnlyAccessTokenForSPAppWeb 620 | { 621 | get 622 | { 623 | if (this.SPAppWebUrl == null) 624 | { 625 | return null; 626 | } 627 | 628 | return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, 629 | () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); 630 | } 631 | } 632 | 633 | public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) 634 | : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) 635 | { 636 | if (string.IsNullOrEmpty(contextToken)) 637 | { 638 | throw new ArgumentNullException("contextToken"); 639 | } 640 | 641 | if (contextTokenObj == null) 642 | { 643 | throw new ArgumentNullException("contextTokenObj"); 644 | } 645 | 646 | this.contextToken = contextToken; 647 | this.contextTokenObj = contextTokenObj; 648 | } 649 | 650 | /// 651 | /// Ensures the access token is valid and returns it. 652 | /// 653 | /// The access token to verify. 654 | /// The token renewal handler. 655 | /// The access token string. 656 | private static string GetAccessTokenString(ref Tuple accessToken, Func tokenRenewalHandler) 657 | { 658 | RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); 659 | 660 | return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; 661 | } 662 | 663 | /// 664 | /// Renews the access token if it is not valid. 665 | /// 666 | /// The access token to renew. 667 | /// The token renewal handler. 668 | private static void RenewAccessTokenIfNeeded(ref Tuple accessToken, Func tokenRenewalHandler) 669 | { 670 | if (IsAccessTokenValid(accessToken)) 671 | { 672 | return; 673 | } 674 | 675 | try 676 | { 677 | OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); 678 | 679 | DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; 680 | 681 | if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) 682 | { 683 | // Make the access token get renewed a bit earlier than the time when it expires 684 | // so that the calls to SharePoint with it will have enough time to complete successfully. 685 | expiresOn -= AccessTokenLifetimeTolerance; 686 | } 687 | 688 | accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); 689 | } 690 | catch (WebException) 691 | { 692 | } 693 | } 694 | } 695 | 696 | /// 697 | /// Default provider for SharePointAcsContext. 698 | /// 699 | public class SharePointAcsContextProvider : SharePointContextProvider 700 | { 701 | private const string SPContextKey = "SPContext"; 702 | private const string SPCacheKeyKey = "SPCacheKey"; 703 | 704 | protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) 705 | { 706 | string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); 707 | if (string.IsNullOrEmpty(contextTokenString)) 708 | { 709 | return null; 710 | } 711 | 712 | SharePointContextToken contextToken = null; 713 | try 714 | { 715 | contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); 716 | } 717 | catch (WebException) 718 | { 719 | return null; 720 | } 721 | catch (AudienceUriValidationFailedException) 722 | { 723 | return null; 724 | } 725 | 726 | return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); 727 | } 728 | 729 | protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) 730 | { 731 | SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; 732 | 733 | if (spAcsContext != null) 734 | { 735 | Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); 736 | string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); 737 | HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; 738 | string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; 739 | 740 | return spHostUrl == spAcsContext.SPHostUrl && 741 | !string.IsNullOrEmpty(spAcsContext.CacheKey) && 742 | spCacheKey == spAcsContext.CacheKey && 743 | !string.IsNullOrEmpty(spAcsContext.ContextToken) && 744 | (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); 745 | } 746 | 747 | return false; 748 | } 749 | 750 | protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) 751 | { 752 | return httpContext.Session[SPContextKey] as SharePointAcsContext; 753 | } 754 | 755 | protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) 756 | { 757 | SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; 758 | 759 | if (spAcsContext != null) 760 | { 761 | HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) 762 | { 763 | Value = spAcsContext.CacheKey, 764 | Secure = true, 765 | HttpOnly = true 766 | }; 767 | 768 | httpContext.Response.AppendCookie(spCacheKeyCookie); 769 | } 770 | 771 | httpContext.Session[SPContextKey] = spAcsContext; 772 | } 773 | } 774 | 775 | #endregion ACS 776 | 777 | #region HighTrust 778 | 779 | /// 780 | /// Encapsulates all the information from SharePoint in HighTrust mode. 781 | /// 782 | public class SharePointHighTrustContext : SharePointContext 783 | { 784 | private readonly WindowsIdentity logonUserIdentity; 785 | 786 | /// 787 | /// The Windows identity for the current user. 788 | /// 789 | public WindowsIdentity LogonUserIdentity 790 | { 791 | get { return this.logonUserIdentity; } 792 | } 793 | 794 | public override string UserAccessTokenForSPHost 795 | { 796 | get 797 | { 798 | return GetAccessTokenString(ref this.userAccessTokenForSPHost, 799 | () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); 800 | } 801 | } 802 | 803 | public override string UserAccessTokenForSPAppWeb 804 | { 805 | get 806 | { 807 | if (this.SPAppWebUrl == null) 808 | { 809 | return null; 810 | } 811 | 812 | return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, 813 | () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); 814 | } 815 | } 816 | 817 | public override string AppOnlyAccessTokenForSPHost 818 | { 819 | get 820 | { 821 | return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, 822 | () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); 823 | } 824 | } 825 | 826 | public override string AppOnlyAccessTokenForSPAppWeb 827 | { 828 | get 829 | { 830 | if (this.SPAppWebUrl == null) 831 | { 832 | return null; 833 | } 834 | 835 | return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, 836 | () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); 837 | } 838 | } 839 | 840 | public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) 841 | : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) 842 | { 843 | if (logonUserIdentity == null) 844 | { 845 | throw new ArgumentNullException("logonUserIdentity"); 846 | } 847 | 848 | this.logonUserIdentity = logonUserIdentity; 849 | } 850 | 851 | /// 852 | /// Ensures the access token is valid and returns it. 853 | /// 854 | /// The access token to verify. 855 | /// The token renewal handler. 856 | /// The access token string. 857 | private static string GetAccessTokenString(ref Tuple accessToken, Func tokenRenewalHandler) 858 | { 859 | RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); 860 | 861 | return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; 862 | } 863 | 864 | /// 865 | /// Renews the access token if it is not valid. 866 | /// 867 | /// The access token to renew. 868 | /// The token renewal handler. 869 | private static void RenewAccessTokenIfNeeded(ref Tuple accessToken, Func tokenRenewalHandler) 870 | { 871 | if (IsAccessTokenValid(accessToken)) 872 | { 873 | return; 874 | } 875 | 876 | DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); 877 | 878 | if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) 879 | { 880 | // Make the access token get renewed a bit earlier than the time when it expires 881 | // so that the calls to SharePoint with it will have enough time to complete successfully. 882 | expiresOn -= AccessTokenLifetimeTolerance; 883 | } 884 | 885 | accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); 886 | } 887 | } 888 | 889 | /// 890 | /// Default provider for SharePointHighTrustContext. 891 | /// 892 | public class SharePointHighTrustContextProvider : SharePointContextProvider 893 | { 894 | private const string SPContextKey = "SPContext"; 895 | 896 | protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) 897 | { 898 | WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; 899 | if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) 900 | { 901 | return null; 902 | } 903 | 904 | return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); 905 | } 906 | 907 | protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) 908 | { 909 | SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; 910 | 911 | if (spHighTrustContext != null) 912 | { 913 | Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); 914 | WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; 915 | 916 | return spHostUrl == spHighTrustContext.SPHostUrl && 917 | logonUserIdentity != null && 918 | logonUserIdentity.IsAuthenticated && 919 | !logonUserIdentity.IsGuest && 920 | logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; 921 | } 922 | 923 | return false; 924 | } 925 | 926 | protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) 927 | { 928 | return httpContext.Session[SPContextKey] as SharePointHighTrustContext; 929 | } 930 | 931 | protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) 932 | { 933 | httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; 934 | } 935 | } 936 | 937 | #endregion HighTrust 938 | } 939 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/SharePointService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.SharePoint.Client; 2 | using SharePointAppSampleWeb.Models; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Web; 7 | 8 | namespace SharePointAppSampleWeb 9 | { 10 | public static class SharePointService 11 | { 12 | public static string GetUserName(SharePointContext spContext) 13 | { 14 | string strUserName = null; 15 | 16 | User spUser = null; 17 | 18 | using (var clientContext = spContext.CreateUserClientContextForSPHost()) 19 | { 20 | if (clientContext != null) 21 | { 22 | spUser = clientContext.Web.CurrentUser; 23 | 24 | clientContext.Load(spUser, user => user.Title); 25 | 26 | clientContext.ExecuteQuery(); 27 | 28 | strUserName = spUser.Title; 29 | } 30 | } 31 | 32 | return strUserName; 33 | } 34 | 35 | public static List GetProducts(SharePointContext spContext, CamlQuery camlQuery) 36 | { 37 | List products = new List(); 38 | 39 | using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) 40 | { 41 | if (clientContext != null) 42 | { 43 | List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); 44 | 45 | ListItemCollection lstProductItems = lstProducts.GetItems(camlQuery); 46 | 47 | clientContext.Load(lstProductItems); 48 | 49 | clientContext.ExecuteQuery(); 50 | 51 | if (lstProductItems != null) 52 | { 53 | foreach (var lstProductItem in lstProductItems) 54 | { 55 | products.Add( 56 | new Product 57 | { 58 | Id = lstProductItem.Id, 59 | Title = lstProductItem["Title"].ToString(), 60 | Description = lstProductItem["ProductDescription"].ToString(), 61 | Price = lstProductItem["Price"].ToString() 62 | }); 63 | } 64 | } 65 | } 66 | } 67 | 68 | return products; 69 | } 70 | 71 | public static bool AddProduct(SharePointContext spContext, Product product) 72 | { 73 | using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) 74 | { 75 | if (clientContext != null) 76 | { 77 | try 78 | { 79 | List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); 80 | 81 | ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 82 | ListItem newProduct = lstProducts.AddItem(itemCreateInfo); 83 | newProduct["Title"] = product.Title; 84 | newProduct["ProductDescription"] = product.Description; 85 | newProduct["Price"] = product.Price; 86 | newProduct.Update(); 87 | 88 | clientContext.ExecuteQuery(); 89 | 90 | return true; 91 | } 92 | catch (ServerException ex) 93 | { 94 | return false; 95 | } 96 | } 97 | } 98 | 99 | return false; 100 | } 101 | 102 | internal static Product GetProductDetails(SharePointContext spContext, int id) 103 | { 104 | Product product = new Product(); 105 | using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) 106 | { 107 | if (clientContext != null) 108 | { 109 | List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); 110 | ListItem selectedItem = lstProducts.GetItemById(id); 111 | clientContext.Load(selectedItem); 112 | 113 | clientContext.ExecuteQuery(); 114 | 115 | if (selectedItem != null) 116 | { 117 | product = new Product 118 | { 119 | Title = selectedItem["Title"] as string, 120 | Description = selectedItem["ProductDescription"] as string, 121 | Price = selectedItem["Price"] as string, 122 | }; 123 | } 124 | } 125 | 126 | } 127 | 128 | return product; 129 | } 130 | 131 | public static bool UpdateProduct(SharePointContext spContext, Product product) 132 | { 133 | 134 | using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) 135 | { 136 | if (clientContext != null) 137 | { 138 | try 139 | { 140 | List lstProducts = clientContext.Web.Lists.GetByTitle("Products"); 141 | ListItem selectedItem = lstProducts.GetItemById(product.Id); 142 | 143 | selectedItem["Title"] = product.Title; 144 | selectedItem["ProductDescription"] = product.Description; 145 | selectedItem["Price"] = product.Price; 146 | selectedItem.Update(); 147 | 148 | clientContext.ExecuteQuery(); 149 | return true; 150 | 151 | } 152 | catch (ServerException ex) 153 | { 154 | return false; 155 | } 156 | 157 | } 158 | } 159 | return false; 160 | } 161 | 162 | public static void DeleteProduct(SharePointContext spContext, Product product) 163 | { 164 | 165 | using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) 166 | { 167 | try 168 | { 169 | List productsList = clientContext.Web.Lists.GetByTitle("Products"); 170 | ListItem itemToDelete = productsList.GetItemById(product.Id); 171 | itemToDelete.DeleteObject(); 172 | 173 | clientContext.ExecuteQuery(); 174 | } 175 | catch (ServerException ex) 176 | { 177 | // TODO: Exception Handling 178 | } 179 | } 180 | } 181 | 182 | } 183 | } -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/Home/About.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewBag.Title = "About"; 3 | } 4 |

@ViewBag.Title.

5 |

@ViewBag.Message

6 | 7 |

Use this area to provide additional information.

8 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/Home/Contact.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewBag.Title = "Contact"; 3 | } 4 |

@ViewBag.Title.

5 |

@ViewBag.Message

6 | 7 |
8 | One Microsoft Way
9 | Redmond, WA 98052-6399
10 | P: 11 | 425.555.0100 12 |
13 | 14 |
15 | Support: Support@example.com
16 | Marketing: Marketing@example.com 17 |
-------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/Home/Delete.cshtml: -------------------------------------------------------------------------------- 1 | @model SharePointAppSampleWeb.Models.Product 2 | 3 | @{ 4 | ViewBag.Title = "Delete"; 5 | } 6 | 7 |

Delete

8 | 9 |

Are you sure you want to delete this?

10 |
11 |

Product

12 |
13 |
14 |
15 | @Html.DisplayNameFor(model => model.Title) 16 |
17 | 18 |
19 | @Html.DisplayFor(model => model.Title) 20 |
21 | 22 |
23 | @Html.DisplayNameFor(model => model.Description) 24 |
25 | 26 |
27 | @Html.DisplayFor(model => model.Description) 28 |
29 | 30 |
31 | @Html.DisplayNameFor(model => model.Price) 32 |
33 | 34 |
35 | @Html.DisplayFor(model => model.Price) 36 |
37 | 38 |
39 | 40 | @using (Html.BeginForm()) { 41 | @Html.AntiForgeryToken() 42 | 43 |
44 | | 45 | @Html.ActionLink("Back to List", "Index") 46 |
47 | } 48 |
49 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/Home/Edit.cshtml: -------------------------------------------------------------------------------- 1 | @model SharePointAppSampleWeb.Models.Product 2 | 3 | @{ 4 | ViewBag.Title = "Edit"; 5 | } 6 | 7 |

Edit

8 | 9 | 10 | @using (Html.BeginForm()) 11 | { 12 | @Html.AntiForgeryToken() 13 | 14 |
15 |

Product

16 |
17 | @Html.ValidationSummary(true) 18 |
19 | @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" }) 20 |
21 | @Html.EditorFor(model => model.Title) 22 | @Html.ValidationMessageFor(model => model.Title) 23 |
24 |
25 | 26 |
27 | @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" }) 28 |
29 | @Html.EditorFor(model => model.Description) 30 | @Html.ValidationMessageFor(model => model.Description) 31 |
32 |
33 | 34 |
35 | @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" }) 36 |
37 | @Html.EditorFor(model => model.Price) 38 | @Html.ValidationMessageFor(model => model.Price) 39 |
40 |
41 | 42 |
43 |
44 | 45 |
46 |
47 |
48 | } 49 | 50 |
51 | @Html.ActionLink("Back to List", "Index") 52 |
53 | 54 | @section Scripts { 55 | @Scripts.Render("~/bundles/jqueryval") 56 | } 57 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | ViewBag.Title = "Home Page"; 3 | } 4 | 5 | 6 | 7 |
8 |

Welcome @ViewBag.UserName!

9 |

Apps for SharePoint - Embracing web standards, the new cloud app model gives you maximum choice and flexibility to build a new class of apps for SharePoint using familiar languages, tools, and hosting services.

10 |

Learn more »

11 |
12 |
13 |
14 |
15 |

Product List

16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | @foreach (SharePointAppSampleWeb.Models.Product objProduct in Model) 27 | { 28 | 29 | 32 | 33 | 34 | 35 | 36 | 37 | } 38 | 39 |
TitleDescriptionPrice
30 | @Html.ActionLink("Edit", "Edit", new { id = objProduct.Id }) | @Html.ActionLink("Delete", "Delete", new { id = objProduct.Id }) 31 | @objProduct.Title@objProduct.Description@objProduct.Price
40 | 41 | 42 | Add Product 43 | 44 | 45 | 81 | 82 |
83 |
84 |
85 | 86 | @section Scripts { 87 | 88 | } -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = null; 3 | } 4 | 5 | 6 | 7 | 8 | 9 | Unknown User 10 | @Styles.Render("~/Content/css") 11 | 12 | 13 |
14 |
15 |

Unknown User

16 |

Unable to determine your identity. Please try again by launching the app installed on your site.

17 |
18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | @ViewBag.Title - My ASP.NET Application 7 | @Styles.Render("~/Content/css") 8 | @Scripts.Render("~/bundles/modernizr") 9 | 10 | 11 | 30 |
31 | @RenderBody() 32 |
33 |
34 |

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

35 |
36 |
37 | 38 | @Scripts.Render("~/bundles/jquery") 39 | @Scripts.Render("~/bundles/bootstrap") 40 | @Scripts.Render("~/bundles/spcontext") 41 | @RenderSection("Scripts", required: false) 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/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 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "~/Views/Shared/_Layout.cshtml"; 3 | } 4 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Web.Debug.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Web.Release.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 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 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/Product-List-Code-Sample/a8bf2134b1de93394c1e6d03b680043af1b75472/ProductListCodeSampleWeb/favicon.ico -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/Product-List-Code-Sample/a8bf2134b1de93394c1e6d03b680043af1b75472/ProductListCodeSampleWeb/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/Product-List-Code-Sample/a8bf2134b1de93394c1e6d03b680043af1b75472/ProductListCodeSampleWeb/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OfficeDev/Product-List-Code-Sample/a8bf2134b1de93394c1e6d03b680043af1b75472/ProductListCodeSampleWeb/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /ProductListCodeSampleWeb/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [ARCHIVED] Product-List-Code-Sample 2 | ======================== 3 | 4 | **Note:** This repo is archived and no longer actively maintained. Security vulnerabilities may exist in the project, or its dependencies. If you plan to reuse or run any code from this repo, be sure to perform appropriate security checks on the code or dependencies first. Do not use this project as the starting point of a production Office Add-in. Always start your production code by using the Office/SharePoint development workload in Visual Studio, or the [Yeoman generator for Office Add-ins](https://github.com/OfficeDev/generator-office), and follow security best practices as you develop the add-in. 5 | 6 | An App for SharePoint that is Provider Hosted using ASP.NET MVC web application. It deploys the Product List through the declarative approach in the SharePoint App to the App Web. 7 | 8 | 9 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 10 | --------------------------------------------------------------------------------