├── .gitignore ├── GetBearerToken ├── FodyWeavers.xml ├── GetBearerToken.csproj ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── app.config ├── LICENSE ├── README.md ├── SnaffPoint.sln └── SnaffPoint ├── App.config ├── Program.cs ├── Properties └── AssemblyInfo.cs ├── SearchQueryTool ├── Helpers │ ├── CookieReader.cs │ ├── DataConverter.cs │ ├── Extensions.cs │ ├── HttpRequestResponsePair.cs │ ├── HttpRequestRunner.cs │ ├── HttpWebRequestExtensions.cs │ ├── JsonHelper.cs │ └── XmlHelper.cs ├── Model │ ├── SearchConnection.cs │ ├── SearchHistory.cs │ ├── SearchPreset.cs │ ├── SearchPresetList.cs │ ├── SearchQueryRequest.cs │ ├── SearchQueryResult.cs │ ├── SearchRequest.cs │ ├── SearchResult.cs │ ├── SearchResultPresentationSettings.cs │ ├── SearchSuggestionsRequest.cs │ └── SearchSuggestionsResult.cs └── SPAuthenticationClient │ └── AuthenticationClient.cs ├── SnaffPoint.csproj └── presets ├── AWSCFKeysInCode.xml ├── CSharpDbConnStrings.xml ├── CSharpViewstateKeys.xml ├── CmdCredentials.xml ├── ConfigPasswordsVeryNoisy.xml ├── CyberArkCredFile.xml ├── DatabaseByExtension.xml ├── DbConnStringPw.xml ├── DbMgtConfigByName.xml ├── DeployImageByExtension.xml ├── DomainJoinCredsByPath.xml ├── FirefoxLoginsJson.xml ├── FtpClientConfigConfigByName.xml ├── FtpServerConfigByName.xml ├── GitCredsByName.xml ├── InfraAsCodeConfigByExtension.xml ├── InlinePrivateKey.xml ├── JavaDbConnStrings.xml ├── JenkinsByName.xml ├── MemDumpByExtension.xml ├── MemDumpByName.xml ├── NetConfigCreds.xml ├── NetConfigFileByName.xml ├── PHPDbConnStrings.xml ├── PassMgrsByExtension.xml ├── PcapByExtension.xml ├── PsCredentials.xml ├── PyDbConnStrings.xml ├── RdpPasswords.xml ├── RemoteAccessConfByExtension.xml ├── RemoteAccessConfByName.xml ├── RubyConfigFiles.xml ├── RubyDbConnStrings.xml ├── SSHKeysByFileName.xml ├── ShellHistoryByName.xml ├── SqlAccountCreation.xml └── UnattendXML.xml /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml -------------------------------------------------------------------------------- /GetBearerToken/FodyWeavers.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | -------------------------------------------------------------------------------- /GetBearerToken/GetBearerToken.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {A3640B4E-66C9-4211-84F1-E4A7B337BB1E} 8 | Exe 9 | GetBearerToken 10 | GetBearerToken 11 | v4.7.2 12 | 512 13 | true 14 | 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | false 26 | 27 | 28 | AnyCPU 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | false 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 0.14.0 70 | 71 | 72 | 0.14.2 73 | 74 | 75 | 5.7.0 76 | 77 | all 78 | 79 | 80 | 2.13.1 81 | 82 | 83 | 2.2.0 84 | 85 | 86 | 2.2.0 87 | 88 | 89 | 2.2.0 90 | 91 | 92 | 2.2.0 93 | 94 | 95 | 2.2.0 96 | 97 | 98 | 2.2.0 99 | 100 | 101 | 1.1.1 102 | 103 | 104 | 1.1.1 105 | 106 | 107 | 5.8.4 108 | 109 | 110 | 5.8.4 111 | 112 | 113 | 2.2.0 114 | 115 | 116 | 2.2.0 117 | 118 | 119 | 2.2.0 120 | 121 | 122 | 2.2.0 123 | 124 | 125 | 2.2.0 126 | 127 | 128 | 2.2.0 129 | 130 | 131 | 2.2.0 132 | 133 | 134 | 2.2.0 135 | 136 | 137 | 2.2.0 138 | 139 | 140 | 2.2.0 141 | 142 | 143 | 2.2.0 144 | 145 | 146 | 2.2.0 147 | 148 | 149 | 2.2.0 150 | 151 | 152 | 2.2.0 153 | 154 | 155 | 2.2.0 156 | 157 | 158 | 3.33.0 159 | 160 | 161 | 1.25.1 162 | 163 | 164 | 4.36.1 165 | 166 | 167 | 2.18.4 168 | 169 | 170 | 6.12.2 171 | 172 | 173 | 6.12.2 174 | 175 | 176 | 6.12.2 177 | 178 | 179 | 2.2.0 180 | 181 | 182 | 16.1.22315.12000 183 | 184 | 185 | 12.0.3 186 | 187 | 188 | 1.6.0 189 | 190 | 191 | 1.6.0 192 | 193 | 194 | 1.9.0 195 | 196 | 197 | 0.26.0 198 | 199 | 200 | 4.5.1 201 | 202 | 203 | 4.5.0 204 | 205 | 206 | 4.7.0 207 | 208 | 209 | 4.7.1 210 | 211 | 212 | 4.7.0 213 | 214 | 215 | 6.12.2 216 | 217 | 218 | 4.3.0 219 | 220 | 221 | 4.7.0 222 | 223 | 224 | 4.5.4 225 | 226 | 227 | 4.5.0 228 | 229 | 230 | 4.7.1 231 | 232 | 233 | 4.3.0 234 | 235 | 236 | 4.7.0 237 | 238 | 239 | 4.7.0 240 | 241 | 242 | 4.7.0 243 | 244 | 245 | 5.8.4 246 | 247 | 248 | 4.5.0 249 | 250 | 251 | 4.7.1 252 | 253 | 254 | 4.7.2 255 | 256 | 257 | 4.5.4 258 | 259 | 260 | 4.5.0 261 | 262 | 263 | 3.5.0 264 | 265 | 266 | 267 | 268 | 269 | 270 | -------------------------------------------------------------------------------- /GetBearerToken/Program.cs: -------------------------------------------------------------------------------- 1 | using PnP.Core.Auth; 2 | using System; 3 | using System.Threading.Tasks; 4 | 5 | namespace GetBearerToken 6 | { 7 | class Program 8 | { 9 | private static string url = ""; 10 | private static string _adalToken = null; 11 | private static InteractiveAuthenticationProvider _interactiveProvider; 12 | 13 | // shameless rip off https://github.com/pnp/PnP-Tools/blob/master/Solutions/SharePoint.Search.QueryTool/SearchQueryTool/MainWindow.xaml.cs 14 | private static async Task AdalLogin(string url) 15 | { 16 | var spUri = new Uri(url); 17 | 18 | var resourceUri = new Uri(spUri.Scheme + "://" + spUri.Authority); 19 | const string clientId = "9bc3ab49-b65d-410a-85ad-de819febfddc"; 20 | const string redirectUri = "https://oauth.spops.microsoft.com/"; 21 | 22 | string tenant = spUri.Host.Replace("sharepoint", "onmicrosoft") 23 | .Replace("-df", "") 24 | .Replace("-admin", ""); 25 | 26 | if (_interactiveProvider == null || _interactiveProvider.TenantId != tenant) 27 | { 28 | _interactiveProvider = new InteractiveAuthenticationProvider(clientId, tenant, new Uri(redirectUri)); 29 | } 30 | 31 | _adalToken = await _interactiveProvider.GetAccessTokenAsync(resourceUri); 32 | return "Bearer " + _adalToken; 33 | } 34 | 35 | static int Main(string[] args) 36 | { 37 | if (args.Length != 1) 38 | { 39 | System.Console.WriteLine("Please enter your SharePoint online URL."); 40 | return 1; 41 | } 42 | url = args[0]; 43 | 44 | var token = AdalLogin(url); 45 | token.Wait(); 46 | Console.WriteLine(_adalToken); 47 | 48 | return 0; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /GetBearerToken/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("SnaffPoint")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("SnaffPoint")] 12 | [assembly: AssemblyCopyright("Copyright © 2022")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("a3640b4e-66c9-4211-84f1-e4a7b337bb1e")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /GetBearerToken/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Nicolas Heiniger 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SnaffPoint 2 | 3 | ## What is it 4 | SnaffPoint is a tool for pointesters who are in need of some sweetness in this world. It should help you find sensitive files available on SharePoint online and on shared OneDrive files for your company (or your customer). 5 | 6 | ## How does it work 7 | There are actually 2 tools: 8 | - GetBearerToken will perform authentication for you on SharePoint, with the usual GUI and supporting MFA 9 | - SnaffPoint is CLI only and will do the enumeration itself and find the interesting files 10 | 11 | ### GetBearerToken 12 | Nothing fancy, run the tool as follows: 13 | ``` 14 | GetBearerToken.exe https://yoururl.sharepoint.com 15 | ``` 16 | Authenticate successfully and you should get a Bearer token to use in SnaffPoint. This is mostly the code of PNP-Tools (see credits below). 17 | 18 | ### SnaffPoint 19 | Have a look at the help menu here: 20 | ``` 21 | Usage: SnaffPoint.exe -u URL -t JWT [OPTIONS] 22 | 23 | -h, --help This is me :) 24 | 25 | Mandatory: 26 | -u, --url SharePoint online URL where you want to search 27 | -t, --token Bearer token that grants access to said SharePoint 28 | 29 | Common options: 30 | -m, --max-rows Max. number of rows to return per search query (default is 50) 31 | 32 | Presets mode (default): 33 | -p, --preset Path to a folder containing XML search presets (default is ./presets) 34 | 35 | Single query mode: 36 | -q, --query Query search string 37 | -l, --fql Enables FQL (default is KQL) 38 | -r, --refinement-filter Adds a refinement filter 39 | ``` 40 | 41 | Note that the `preset` folder contains many presets that you may or may not want to test on your environment. Have a look at them, and please submit a pull request if you have ideas for other presets. The preset mode is probably what you want to run against your own company. On the other hand, if you need to run the C# assembly in memory, you probably want to specify a single query to avoid the presets on disk and have more control on what you search. 42 | 43 | ## Due credits 44 | [@mikeloss](https://twitter.com/mikeloss) and [@sh3r4_hax](https://twitter.com/sh3r4_hax) for Snaffler (https://github.com/SnaffCon/Snaffler) from which I borrowed the name and adapted many of the rules. 45 | 46 | The contibutors of PNP-Tools, all the code interacting with SharePoint is ~~ripped off~~ inspired by their Search.QueryTool project: https://github.com/pnp/PnP-Tools/tree/master/Solutions/SharePoint.Search.QueryTool/SearchQueryTool 47 | 48 | ## Anything else 49 | You can contact me on Twitter: [@nicolasheiniger](https://twitter.com/NicolasHeiniger) 50 | -------------------------------------------------------------------------------- /SnaffPoint.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.32126.315 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SnaffPoint", "SnaffPoint\SnaffPoint.csproj", "{879A49C7-0493-4235-85F6-EBF962613A76}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GetBearerToken", "GetBearerToken\GetBearerToken.csproj", "{A3640B4E-66C9-4211-84F1-E4A7B337BB1E}" 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 | {879A49C7-0493-4235-85F6-EBF962613A76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {879A49C7-0493-4235-85F6-EBF962613A76}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {879A49C7-0493-4235-85F6-EBF962613A76}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {879A49C7-0493-4235-85F6-EBF962613A76}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {A3640B4E-66C9-4211-84F1-E4A7B337BB1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {A3640B4E-66C9-4211-84F1-E4A7B337BB1E}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {A3640B4E-66C9-4211-84F1-E4A7B337BB1E}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {A3640B4E-66C9-4211-84F1-E4A7B337BB1E}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {807A1A7D-11E1-4CFB-87C8-AFE78EB2AA6B} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /SnaffPoint/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /SnaffPoint/Program.cs: -------------------------------------------------------------------------------- 1 | using SearchQueryTool.Helpers; 2 | using SearchQueryTool.Model; 3 | using System; 4 | using System.Collections.Specialized; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Net; 8 | 9 | namespace SnaffPoint 10 | { 11 | class Program 12 | { 13 | private static string PresetPath = "./presets"; 14 | private static int MaxRows = 50; 15 | private static string SingleQueryText = null; 16 | private static SearchPresetList _SearchPresets; 17 | private static string BearerToken = null; 18 | private static string SPUrl = null; 19 | private static bool isFQL = false; 20 | private static string RefinementFilters = null; 21 | 22 | private static void LoadSearchPresetsFromFolder(string presetFolderPath) 23 | { 24 | try 25 | { 26 | _SearchPresets = new SearchPresetList(presetFolderPath); 27 | } 28 | catch (Exception ex) 29 | { 30 | Console.WriteLine("Failed to read search presets. Error: " + ex.Message); 31 | } 32 | } 33 | 34 | private static SearchQueryResult StartSearchQueryRequest(SearchQueryRequest request) 35 | { 36 | SearchQueryResult searchResults = null; 37 | try 38 | { 39 | HttpRequestResponsePair requestResponsePair = HttpRequestRunner.RunWebRequest(request); 40 | if (requestResponsePair != null) 41 | { 42 | HttpWebResponse response = requestResponsePair.Item2; 43 | if (null != response) 44 | { 45 | if (!response.StatusCode.Equals(HttpStatusCode.OK)) 46 | { 47 | string status = String.Format("HTTP {0} {1}", (int)response.StatusCode, response.StatusDescription); 48 | Console.WriteLine("Request returned with following status: " + status); 49 | } 50 | } 51 | } 52 | searchResults = GetResultItem(requestResponsePair); 53 | 54 | // success, return the results 55 | return searchResults; 56 | } 57 | catch (Exception ex) 58 | { 59 | Console.WriteLine("Request failed with exception: " + ex.Message); 60 | } 61 | return searchResults; 62 | } 63 | 64 | private static SearchQueryResult GetResultItem(HttpRequestResponsePair requestResponsePair) 65 | { 66 | SearchQueryResult searchResults; 67 | var request = requestResponsePair.Item1; 68 | 69 | using (var response = requestResponsePair.Item2) 70 | { 71 | using (var reader = new StreamReader(response.GetResponseStream())) 72 | { 73 | var content = reader.ReadToEnd(); 74 | NameValueCollection requestHeaders = new NameValueCollection(); 75 | foreach (var header in request.Headers.AllKeys) 76 | { 77 | requestHeaders.Add(header, request.Headers[header]); 78 | } 79 | 80 | NameValueCollection responseHeaders = new NameValueCollection(); 81 | foreach (var header in response.Headers.AllKeys) 82 | { 83 | responseHeaders.Add(header, response.Headers[header]); 84 | } 85 | 86 | string requestContent = ""; 87 | if (request.Method == "POST") 88 | { 89 | requestContent = requestResponsePair.Item3; 90 | } 91 | 92 | searchResults = new SearchQueryResult 93 | { 94 | RequestUri = request.RequestUri, 95 | RequestMethod = request.Method, 96 | RequestContent = requestContent, 97 | ContentType = response.ContentType, 98 | ResponseContent = content, 99 | RequestHeaders = requestHeaders, 100 | ResponseHeaders = responseHeaders, 101 | StatusCode = response.StatusCode, 102 | StatusDescription = response.StatusDescription, 103 | HttpProtocolVersion = response.ProtocolVersion.ToString() 104 | }; 105 | searchResults.Process(); 106 | } 107 | } 108 | return searchResults; 109 | } 110 | 111 | static void QueryAllPresets() 112 | { 113 | LoadSearchPresetsFromFolder(PresetPath); 114 | 115 | if (_SearchPresets.Presets.Count > 0) 116 | { 117 | foreach (var preset in _SearchPresets.Presets) 118 | { 119 | Console.WriteLine("\n" + preset.Name + "\n" + new String('=', preset.Name.Length) + "\n"); 120 | preset.Request.Token = BearerToken; 121 | preset.Request.SharePointSiteUrl = SPUrl; 122 | preset.Request.RowLimit = MaxRows; 123 | preset.Request.AcceptType = AcceptType.Json; 124 | preset.Request.AuthenticationType = AuthenticationType.SPOManagement; // force to JWT auth method 125 | // Console.WriteLine("DEBUG - Request: " + preset.Request.ToString()); 126 | SearchQueryResult results = StartSearchQueryRequest(preset.Request); 127 | DisplayResults(results); 128 | } 129 | } 130 | else 131 | { 132 | Console.WriteLine("No presets were found in " + PresetPath); 133 | } 134 | } 135 | 136 | private static void DisplayResults(SearchQueryResult results) 137 | { 138 | if (results != null) 139 | { 140 | if (results.PrimaryQueryResult != null) 141 | { 142 | Console.WriteLine("Found " + results.PrimaryQueryResult.TotalRows + " results"); 143 | if (results.PrimaryQueryResult.TotalRows > MaxRows) 144 | { 145 | Console.WriteLine("Only showing " + MaxRows + " results, though!"); 146 | } 147 | if (results.PrimaryQueryResult.TotalRows > 0) 148 | { 149 | foreach (ResultItem item in results.PrimaryQueryResult.RelevantResults) 150 | { 151 | Console.WriteLine("---"); 152 | Console.WriteLine(item.Title); 153 | Console.WriteLine(item.Path); 154 | } 155 | } 156 | } 157 | else 158 | { 159 | Console.WriteLine("Found no results... maybe the request failed?"); 160 | } 161 | } 162 | else 163 | { 164 | Console.WriteLine("Result are null ! What happened there?"); 165 | } 166 | } 167 | 168 | private static void DoSingleQuery() 169 | { 170 | // preparing the request for you 171 | SearchQueryRequest request = new SearchQueryRequest 172 | { 173 | SharePointSiteUrl = SPUrl, 174 | AcceptType = AcceptType.Json, 175 | Token = BearerToken, 176 | AuthenticationType = AuthenticationType.SPOManagement, 177 | QueryText = SingleQueryText, 178 | HttpMethodType = HttpMethodType.Get, 179 | EnableFql = isFQL, 180 | RowLimit = MaxRows 181 | }; 182 | if (RefinementFilters != null) 183 | { 184 | request.RefinementFilters = RefinementFilters; 185 | } 186 | // DO IT, DO IT, DO IT ! 187 | SearchQueryResult results = StartSearchQueryRequest(request); 188 | DisplayResults(results); 189 | } 190 | 191 | static void PrintHelp() 192 | { 193 | Console.WriteLine( 194 | @" 195 | .dBBBBP dBBBBb dBBBBBb dBBBBP dBBBBP dBBBBBb dBBBBP dBP dBBBBb dBBBBBBP 196 | BP dBP BB dB' dBP.BP dBP 197 | `BBBBb dBP dBP dBP BB dBBBP dBBBP dBBBP' dBP.BP dBP dBP dBP dBP 198 | dBP dBP dBP dBP BB dBP dBP dBP dBP.BP dBP dBP dBP dBP 199 | dBBBBP' dBP dBP dBBBBBBB dBP dBP dBP dBBBBP dBP dBP dBP dBP 200 | 201 | https://github.com/nheiniger/snaffpoint 202 | 203 | SnaffPoint, candy finder for SharePoint 204 | 205 | Usage: SnaffPoint.exe -u URL -t JWT [OPTIONS] 206 | 207 | -h, --help This is me :) 208 | 209 | Mandatory: 210 | -u, --url SharePoint online URL where you want to search 211 | -t, --token Bearer token that grants access to said SharePoint 212 | 213 | Common options: 214 | -m, --max-rows Max. number of rows to return per search query (default is 50) 215 | 216 | Presets mode (default): 217 | -p, --preset Path to a folder containing XML search presets (default is ./presets) 218 | 219 | Single query mode: 220 | -q, --query Query search string 221 | -l, --fql Enables FQL (default is KQL) 222 | -r, --refinement-filter Adds a refinement filter"); 223 | } 224 | 225 | static void Main(string[] args) 226 | { 227 | foreach (var entry in args.Select((value, index) => new { index, value })) 228 | { 229 | switch (entry.value) 230 | { 231 | // do you want FQL powaa? 232 | case "-l": 233 | case "--fql": 234 | isFQL = true; 235 | break; 236 | // no need for hundreds of results 237 | case "-m": 238 | case "--max-rows": 239 | if (args[entry.index + 1].StartsWith("-")) 240 | { 241 | PrintHelp(); 242 | return; 243 | } 244 | if (! int.TryParse(args[entry.index + 1], out MaxRows)) 245 | { 246 | PrintHelp(); 247 | return; 248 | } 249 | break; 250 | // preset path, load presets 251 | case "-p": 252 | case "--preset": 253 | if (args[entry.index + 1].StartsWith("-")) 254 | { 255 | PrintHelp(); 256 | return; 257 | } 258 | PresetPath = args[entry.index + 1]; 259 | break; 260 | // single query 261 | case "-q": 262 | case "--query": 263 | if (args[entry.index + 1].StartsWith("-")) 264 | { 265 | PrintHelp(); 266 | return; 267 | } 268 | SingleQueryText = args[entry.index + 1]; 269 | break; 270 | // fine control is good :) 271 | case "-r": 272 | case "--refinement-filter": 273 | if (args[entry.index + 1].StartsWith("-")) 274 | { 275 | PrintHelp(); 276 | return; 277 | } 278 | RefinementFilters = args[entry.index + 1]; 279 | break; 280 | // Bearer token (JWT) 281 | case "-t": 282 | case "--token": 283 | if (args[entry.index + 1].StartsWith("-")) 284 | { 285 | PrintHelp(); 286 | return; 287 | } 288 | BearerToken = "Bearer " + args[entry.index + 1]; 289 | break; 290 | // SharePoint online URL 291 | case "-u": 292 | case "--url": 293 | if (args[entry.index + 1].StartsWith("-")) 294 | { 295 | PrintHelp(); 296 | return; 297 | } 298 | SPUrl = args[entry.index + 1]; 299 | break; 300 | // send help 301 | case "-h": 302 | case "--help": 303 | PrintHelp(); 304 | return; 305 | } 306 | } 307 | 308 | // did you read the doc? 309 | if (SPUrl == null || BearerToken == null) 310 | { 311 | PrintHelp(); 312 | return; 313 | } 314 | 315 | // if you specify a query I assume you want an answer, otherwise I have some defaults 316 | if (SingleQueryText != null) 317 | { 318 | DoSingleQuery(); 319 | } 320 | else 321 | { 322 | QueryAllPresets(); 323 | } 324 | } 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /SnaffPoint/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("SnaffPoint")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("SnaffPoint")] 12 | [assembly: AssemblyCopyright("Copyright © 2022")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("879a49c7-0493-4235-85f6-ebf962613a76")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/CookieReader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | using System.Text; 4 | 5 | namespace SearchQueryTool.Helpers 6 | { 7 | /// 8 | /// WinInet.dll wrapper 9 | /// 10 | internal static class CookieReader 11 | { 12 | /// 13 | /// Enables the retrieval of cookies that are marked as "HTTPOnly". 14 | /// Do not use this flag if you expose a scriptable interface, 15 | /// because this has security implications. It is imperative that 16 | /// you use this flag only if you can guarantee that you will never 17 | /// expose the cookie to third-party code by way of an 18 | /// extensibility mechanism you provide. 19 | /// Version: Requires Internet Explorer 8.0 or later. 20 | /// 21 | private const int INTERNET_COOKIE_HTTPONLY = 0x00002000; 22 | 23 | [DllImport("wininet.dll", SetLastError = true)] 24 | private static extern bool InternetGetCookieEx( 25 | string url, 26 | string cookieName, 27 | StringBuilder cookieData, 28 | ref int size, 29 | int flags, 30 | IntPtr pReserved); 31 | 32 | /// 33 | /// Returns cookie contents as a string 34 | /// 35 | /// 36 | /// 37 | public static string GetCookie(string url) 38 | { 39 | 40 | int size = 512; 41 | StringBuilder sb = new StringBuilder(size); 42 | if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)) 43 | { 44 | if (size < 0) 45 | { 46 | return null; 47 | } 48 | sb = new StringBuilder(size); 49 | if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero)) 50 | { 51 | return null; 52 | } 53 | } 54 | return sb.ToString(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/DataConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace SearchQueryTool.Helpers 4 | { 5 | public class DataConverter 6 | { 7 | /// 8 | /// Tries the convert to int. 9 | /// 10 | /// The text. 11 | /// 12 | public static int? TryConvertToInt(string text) 13 | { 14 | var num = 0; 15 | if (Int32.TryParse(text, out num)) 16 | { 17 | return num; 18 | } 19 | 20 | return null; 21 | } 22 | 23 | /// 24 | /// Tries the convert to long. 25 | /// 26 | /// The text. 27 | /// 28 | public static long? TryConvertToLong(string text) 29 | { 30 | long num = 0; 31 | if (Int64.TryParse(text, out num)) 32 | { 33 | return num; 34 | } 35 | 36 | return null; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace SearchQueryTool.Helpers 5 | { 6 | internal static class Extensions 7 | { 8 | public static void ForEach(this IEnumerable ie, Action action) 9 | { 10 | foreach (var i in ie) 11 | { 12 | action(i); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/HttpRequestResponsePair.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | namespace SearchQueryTool.Helpers 5 | { 6 | public class HttpRequestResponsePair : Tuple 7 | { 8 | public HttpRequestResponsePair(HttpWebRequest request, HttpWebResponse response) 9 | : this(request, response, null) 10 | { } 11 | 12 | public HttpRequestResponsePair(HttpWebRequest request, HttpWebResponse response, string requestContent) 13 | : base(request, response, requestContent) 14 | { } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/HttpRequestRunner.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Text; 5 | using SearchQueryTool.Model; 6 | using System.Security; 7 | 8 | namespace SearchQueryTool.Helpers 9 | { 10 | public class HttpRequestRunner 11 | { 12 | public static HttpRequestResponsePair RunWebRequest(SearchRequest searchRequest) 13 | { 14 | if (searchRequest.HttpMethodType == HttpMethodType.Get) 15 | { 16 | return RunGetWebRequest(searchRequest); 17 | } 18 | else // POST 19 | { 20 | return RunPostWebRequest(searchRequest); 21 | } 22 | } 23 | 24 | private static HttpRequestResponsePair RunGetWebRequest(SearchRequest searchRequest) 25 | { 26 | var request = CreateWebRequest(searchRequest.GenerateHttpGetUri(), 27 | searchRequest.AcceptType, 28 | searchRequest.Timeout.HasValue? searchRequest.Timeout.Value : SearchRequest.DefaultTimeout, 29 | searchRequest.AuthenticationType, 30 | searchRequest.SharePointSiteUrl, 31 | searchRequest.UserName, 32 | searchRequest.Password, 33 | searchRequest.SecurePassword, 34 | searchRequest.Cookies, 35 | searchRequest.Token); 36 | 37 | HttpWebResponse response = null; 38 | 39 | try 40 | { 41 | response = request.GetResponse() as HttpWebResponse; 42 | } 43 | catch (WebException webEx) 44 | { 45 | if (webEx.Response == null) 46 | throw; 47 | 48 | response = webEx.Response as HttpWebResponse; 49 | } 50 | 51 | return new HttpRequestResponsePair(request, response); 52 | } 53 | 54 | private static HttpRequestResponsePair RunPostWebRequest(SearchRequest searchRequest) 55 | { 56 | string xrequestDigestValue = GetXRequestDigestForPostRequest(searchRequest); 57 | 58 | var request = CreateWebRequest(searchRequest.GenerateHttpPostUri(), 59 | searchRequest.AcceptType, 60 | searchRequest.Timeout.HasValue ? searchRequest.Timeout.Value : SearchRequest.DefaultTimeout, 61 | searchRequest.AuthenticationType, 62 | searchRequest.SharePointSiteUrl, 63 | searchRequest.UserName, 64 | searchRequest.Password, 65 | searchRequest.SecurePassword, 66 | searchRequest.Cookies, 67 | searchRequest.Token); 68 | 69 | request.Method = "POST"; 70 | request.ContentType = "application/json;odata=verbose;charset=utf-8"; 71 | request.Headers["x-requestdigest"] = xrequestDigestValue; 72 | 73 | string payload = searchRequest.GenerateHttpPostBodyPayload(); 74 | 75 | if (!String.IsNullOrEmpty(payload)) 76 | { 77 | byte[] bytes = Encoding.UTF8.GetBytes(payload); 78 | request.ContentLength = (long)bytes.Length; 79 | Stream requestStream = request.GetRequestStream(); 80 | requestStream.Write(bytes, 0, bytes.Length); 81 | requestStream.Close(); 82 | } 83 | 84 | HttpWebResponse response = null; 85 | 86 | try 87 | { 88 | response = request.GetResponse() as HttpWebResponse; 89 | } 90 | catch (WebException webEx) 91 | { 92 | response = webEx.Response as HttpWebResponse; 93 | } 94 | 95 | return new HttpRequestResponsePair(request, response, payload); 96 | } 97 | 98 | private static string GetXRequestDigestForPostRequest(SearchRequest searchRequest) 99 | { 100 | string digestValue = ""; 101 | 102 | var request = CreateWebRequest(searchRequest.GenerateHttpPostUri(), 103 | searchRequest.AcceptType, 104 | searchRequest.Timeout.HasValue ? searchRequest.Timeout.Value : SearchRequest.DefaultTimeout, 105 | searchRequest.AuthenticationType, 106 | searchRequest.SharePointSiteUrl, 107 | searchRequest.UserName, 108 | searchRequest.Password, 109 | searchRequest.SecurePassword, 110 | searchRequest.Cookies, 111 | searchRequest.Token); 112 | 113 | request.Method = "POST"; 114 | request.ContentType = "application/json;odata=verbose;charset=utf-8"; 115 | request.ContentLength = 0; 116 | 117 | try 118 | { 119 | using (var response = (request as HttpWebRequest).GetResponse() as HttpWebResponse) 120 | { 121 | foreach (var header in response.Headers.AllKeys) 122 | { 123 | if (header.ToLower() == "x-requestdigest") 124 | { 125 | digestValue = response.Headers[header]; 126 | break; 127 | } 128 | } 129 | } 130 | } 131 | catch (WebException webex) // expected 403 Forbidden 132 | { 133 | using (WebResponse response = webex.Response) 134 | { 135 | HttpWebResponse httpResponse = response as HttpWebResponse; 136 | 137 | if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.Forbidden) 138 | { 139 | foreach (var header in response.Headers.AllKeys) 140 | { 141 | if (header.ToLower() == "x-requestdigest") 142 | { 143 | digestValue = response.Headers[header]; 144 | break; 145 | } 146 | } 147 | } 148 | } 149 | } 150 | 151 | return digestValue; 152 | } 153 | 154 | private static HttpWebRequest CreateWebRequest(string uri, AcceptType acceptType, 155 | int timeout = SearchRequest.DefaultTimeout, 156 | AuthenticationType authType = AuthenticationType.CurrentUser, 157 | string sharePointSiteUrl = null, 158 | string username = null, 159 | string password = null, 160 | SecureString securePassword = null, 161 | CookieCollection authCookies = null, 162 | string accessToken = null) 163 | { 164 | HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 165 | 166 | request.Accept = acceptType == AcceptType.Json ? "application/json;odata=verbose;charset=utf-8" : "application/xml;charset=utf-8"; 167 | 168 | request.Timeout = timeout * 1000; 169 | request.AllowAutoRedirect = true; 170 | 171 | if (authType == AuthenticationType.CurrentUser) 172 | { 173 | request.ApplyDefaultCredentials(); 174 | } 175 | else if (authType == AuthenticationType.Windows) 176 | { 177 | if (String.IsNullOrWhiteSpace(username)) 178 | throw new ArgumentException("Parameter Username cannot be empty!"); 179 | 180 | if (String.IsNullOrWhiteSpace(password) && securePassword == null) 181 | throw new ArgumentException("Parameter Password cannot be empty!"); 182 | 183 | request.ApplyWindowsCredentials(username, securePassword); 184 | } 185 | else if (authType == AuthenticationType.Forms) 186 | { 187 | if (String.IsNullOrWhiteSpace(username)) 188 | throw new ArgumentException("Parameter Username cannot be empty!"); 189 | 190 | if (String.IsNullOrWhiteSpace(password)) 191 | throw new ArgumentException("Parameter Password cannot be empty!"); 192 | 193 | request.ApplyFormsCredentials(sharePointSiteUrl, username, password); 194 | } 195 | else if (authType == AuthenticationType.SPO) 196 | { 197 | request.ApplyCookieCredentials(authCookies); 198 | } 199 | else if (authType == AuthenticationType.SPOManagement) 200 | { 201 | request.Headers.Add("Authorization", accessToken); 202 | } 203 | return request; 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/HttpWebRequestExtensions.cs: -------------------------------------------------------------------------------- 1 | using SearchQueryTool.SPAuthenticationClient; 2 | using System; 3 | using System.Net; 4 | using System.Security; 5 | using System.ServiceModel; 6 | using System.ServiceModel.Channels; 7 | 8 | namespace SearchQueryTool.Helpers 9 | { 10 | public static class HttpWebRequestExtensions 11 | { 12 | public static void ApplyDefaultCredentials(this HttpWebRequest webRequest) 13 | { 14 | webRequest.UseDefaultCredentials = true; 15 | webRequest.Credentials = CredentialCache.DefaultCredentials; 16 | } 17 | 18 | public static void ApplyWindowsCredentials(this HttpWebRequest webRequest, string username, SecureString password) 19 | { 20 | if (!String.IsNullOrEmpty(username)) 21 | { 22 | string[] usernameParts = username.Split(new char[] { '\\' }, 2, StringSplitOptions.RemoveEmptyEntries); 23 | if (usernameParts.Length == 2) 24 | { 25 | webRequest.Credentials = new NetworkCredential(usernameParts[1], password, usernameParts[0]); 26 | } 27 | else if (usernameParts.Length == 1) 28 | { 29 | webRequest.Credentials = new NetworkCredential(usernameParts[0], password); 30 | } 31 | 32 | webRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); 33 | } 34 | } 35 | 36 | public static void ApplyFormsCredentials(this HttpWebRequest webRequest, string sharepointSiteUrl, string username, string password) 37 | { 38 | if (!String.IsNullOrWhiteSpace(username)) 39 | { 40 | if (!String.IsNullOrWhiteSpace(sharepointSiteUrl)) 41 | { 42 | string url = sharepointSiteUrl; 43 | 44 | if (!url.EndsWith("/")) 45 | url += "/"; 46 | 47 | url = String.Format("{0}_vti_bin/authentication.asmx", url); 48 | 49 | EndpointAddress authServiceAddress = new EndpointAddress(url); 50 | 51 | using (AuthenticationSoapClient client = new AuthenticationSoapClient(new BasicHttpBinding(), authServiceAddress)) 52 | { 53 | using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) 54 | { 55 | var result = client.Login(username, password.ToString()); 56 | if (result.ErrorCode == SPAuthenticationClient.LoginErrorCode.NoError) 57 | { 58 | HttpResponseMessageProperty respProp = (HttpResponseMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name]; 59 | 60 | foreach (string headerName in respProp.Headers.AllKeys) 61 | { 62 | if (headerName == "Set-Cookie") 63 | { 64 | string authCookie = respProp.Headers[headerName]; 65 | webRequest.Headers.Add(HttpRequestHeader.Cookie, authCookie); 66 | break; 67 | } 68 | } 69 | } 70 | else 71 | { 72 | string errorMsg = String.Format("Login request to authentication service at {0} returned error code: {1}", url, result.ErrorCode.ToString()); 73 | throw new InvalidOperationException(errorMsg); 74 | } 75 | } 76 | } 77 | } 78 | } 79 | } 80 | 81 | public static void ApplyCookieCredentials(this HttpWebRequest webRequest, CookieCollection authCookies) 82 | { 83 | if (authCookies != null) 84 | { 85 | webRequest.CookieContainer = new CookieContainer(); 86 | foreach (Cookie cookie in authCookies) 87 | { 88 | webRequest.CookieContainer.Add(cookie); 89 | } 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/JsonHelper.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Text; 3 | 4 | namespace SearchQueryTool.Helpers 5 | { 6 | public class JsonHelper 7 | { 8 | private const string INDENT_STRING = " "; 9 | 10 | public static string FormatJson(string str) 11 | { 12 | var indent = 0; 13 | var quoted = false; 14 | var sb = new StringBuilder(); 15 | for (var i = 0; i < str.Length; i++) 16 | { 17 | var ch = str[i]; 18 | switch (ch) 19 | { 20 | case '{': 21 | case '[': 22 | sb.Append(ch); 23 | if (!quoted) 24 | { 25 | sb.AppendLine(); 26 | Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING)); 27 | } 28 | break; 29 | case '}': 30 | case ']': 31 | if (!quoted) 32 | { 33 | sb.AppendLine(); 34 | Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING)); 35 | } 36 | sb.Append(ch); 37 | break; 38 | case '"': 39 | sb.Append(ch); 40 | bool escaped = false; 41 | var index = i; 42 | while (index > 0 && str[--index] == '\\') 43 | escaped = !escaped; 44 | if (!escaped) 45 | quoted = !quoted; 46 | break; 47 | case ',': 48 | sb.Append(ch); 49 | if (!quoted) 50 | { 51 | sb.AppendLine(); 52 | Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING)); 53 | } 54 | break; 55 | case ':': 56 | sb.Append(ch); 57 | if (!quoted) 58 | sb.Append(" "); 59 | break; 60 | default: 61 | sb.Append(ch); 62 | break; 63 | } 64 | } 65 | return sb.ToString(); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Helpers/XmlHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Xml; 4 | using System.Xml.Linq; 5 | 6 | namespace SearchQueryTool.Helpers 7 | { 8 | public class XmlHelper 9 | { 10 | public static string PrintXml(String xml) 11 | { 12 | try 13 | { 14 | XDocument doc = XDocument.Parse(xml); 15 | return doc.ToString(); 16 | } 17 | catch (Exception) 18 | { 19 | return xml; 20 | } 21 | } 22 | 23 | public static string PrettyXml(string xml) 24 | { 25 | var stringBuilder = new StringBuilder(); 26 | var element = XElement.Parse(xml); 27 | var settings = new XmlWriterSettings 28 | { 29 | OmitXmlDeclaration = true, 30 | Indent = true, 31 | NewLineOnAttributes = true 32 | }; 33 | 34 | using (var xmlWriter = XmlWriter.Create(stringBuilder, settings)) 35 | { 36 | element.Save(xmlWriter); 37 | } 38 | 39 | return stringBuilder.ToString(); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchConnection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Xml.Linq; 4 | 5 | namespace SearchQueryTool.Model 6 | { 7 | public class SearchConnection 8 | { 9 | public string SpSiteUrl { get; set; } 10 | public string Timeout { get; set; } 11 | public string Accept { get; set; } 12 | public string HttpMethod { get; set; } 13 | public int AuthTypeIndex { get; set; } 14 | public int AuthMethodIndex { get; set; } 15 | public string Username { get; set; } 16 | public bool EnableExperimentalFeatures { get; set; } 17 | 18 | public XElement GetXml() 19 | { 20 | var connectionPropsElm = new XElement("Connection-Props"); 21 | connectionPropsElm.Add(new XElement("spsiteurl", SpSiteUrl)); 22 | connectionPropsElm.Add(new XElement("timeout", Timeout)); 23 | connectionPropsElm.Add(new XElement("accept", Accept)); 24 | connectionPropsElm.Add(new XElement("httpmethod", HttpMethod)); 25 | if (!String.IsNullOrWhiteSpace(Username)) 26 | { 27 | connectionPropsElm.Add(new XElement("username", Username)); 28 | } 29 | connectionPropsElm.Add(new XElement("authtype", AuthTypeIndex)); 30 | connectionPropsElm.Add(new XElement("authmethod", AuthMethodIndex)); 31 | connectionPropsElm.Add(new XElement("experimental", EnableExperimentalFeatures)); 32 | 33 | return connectionPropsElm; 34 | } 35 | 36 | public void Load(string path) 37 | { 38 | if (!String.IsNullOrWhiteSpace(path)) 39 | { 40 | try 41 | { 42 | var connectionPropFilePath = Path.Combine(Environment.CurrentDirectory, path); 43 | if (File.Exists(connectionPropFilePath)) 44 | { 45 | var connectionPropsElm = XElement.Load(connectionPropFilePath); 46 | if (connectionPropsElm.HasElements) 47 | { 48 | SpSiteUrl = (string)connectionPropsElm.Element("spsiteurl"); 49 | Timeout = (string)connectionPropsElm.Element("timeout"); 50 | Accept = (string)connectionPropsElm.Element("accept"); 51 | HttpMethod = (string)connectionPropsElm.Element("httpmethod"); 52 | AuthTypeIndex = (int)connectionPropsElm.Element("authtype"); 53 | AuthMethodIndex = (int)connectionPropsElm.Element("authmethod"); 54 | Username = (string)connectionPropsElm.Element("username"); 55 | EnableExperimentalFeatures = (bool)connectionPropsElm.Element("experimental"); 56 | } 57 | } 58 | } 59 | catch (Exception ex) 60 | { 61 | throw new Exception(String.Format("Failed to load search connection from path {0}, error: {1}", path, ex.Message)); 62 | } 63 | } 64 | } 65 | 66 | public void SaveXml(string outputPath) 67 | { 68 | try 69 | { 70 | var xml = GetXml(); 71 | using (var fs = new FileStream(outputPath, FileMode.Create)) 72 | { 73 | xml.Save(fs); 74 | } 75 | } 76 | catch (Exception ex) 77 | { 78 | throw new Exception(String.Format("Failed to save XML, error: {0}", ex.Message)); 79 | } 80 | } 81 | 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchHistory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | 6 | namespace SearchQueryTool.Model 7 | { 8 | public class SearchHistory 9 | { 10 | /// 11 | /// Path to the folder where we find History items. 12 | /// 13 | public string HistoryFolderPath; 14 | 15 | /// 16 | /// List of history items loaded from the HistoryFolderPath. These are actually Preset objects that 17 | /// can populate the user interface. 18 | /// 19 | public List Presets; 20 | 21 | /// 22 | /// Path to the currently selected history item. Use NavigateBack and NavigateForward to 23 | /// traverse the list. 24 | /// 25 | public string Current { get; set; } 26 | 27 | /// 28 | /// Constructor. Create a search history based on the given folder. 29 | /// 30 | /// The folder to read history items from. 31 | public SearchHistory(string historyFolderPath) 32 | { 33 | HistoryFolderPath = historyFolderPath; 34 | Presets = new List(); 35 | ReadFromFolderPath(HistoryFolderPath); 36 | 37 | Current = (Presets.Count > 0) ? Presets.Last().Path : null; 38 | } 39 | 40 | /// 41 | /// Check if we can navigate backwards. We can navigate backwards until we 42 | /// reach the 0th position. 43 | /// 44 | /// True if we can navigate backwards, false otherwise. 45 | public bool CanNavigateBack() 46 | { 47 | if (null == Current) 48 | return false; 49 | 50 | var currentIdx = Presets.FindIndex(item => (item.Path == Current)); 51 | return (currentIdx != 0); 52 | } 53 | 54 | 55 | /// 56 | /// Navigate backwards in the current search history. 57 | /// 58 | public void NavigateBack() 59 | { 60 | if (CanNavigateBack()) 61 | { 62 | var currentIdx = Presets.FindIndex(item => (item.Path == Current)); 63 | currentIdx--; 64 | Current = Presets[currentIdx].Path; 65 | } 66 | } 67 | 68 | /// 69 | /// Check if we can navigate forward from the current position. We can navigate 70 | /// forward as long as we are not in the last position. 71 | /// 72 | /// True if we can navigate forwards, false otherwise. 73 | public bool CanNavigateForward() 74 | { 75 | if (null == Current) 76 | return false; 77 | 78 | var currentIdx = Presets.FindIndex(item => (item.Path == Current)); 79 | var lastIdx = (Presets.Count - 1); 80 | return (currentIdx != lastIdx); 81 | } 82 | 83 | /// 84 | /// Navigate forward in the current search history. 85 | /// 86 | public void NavigateForward() 87 | { 88 | if (CanNavigateForward()) 89 | { 90 | var currentIdx = Presets.FindIndex(item => (item.Path == Current)); 91 | currentIdx++; 92 | Current = Presets[currentIdx].Path; 93 | } 94 | } 95 | 96 | /// 97 | /// Traverse a directory and load all history XML files stored there into a list of presets. 98 | /// 99 | /// Path to load history from. Default is .\History. 100 | /// True if successful, false otherwise 101 | public bool ReadFromFolderPath(string folderPath = @".\History") 102 | { 103 | bool ret; 104 | try 105 | { 106 | foreach (var file in Directory.EnumerateFiles(folderPath, "*.xml")) 107 | { 108 | var preset = new SearchPreset(file); 109 | Presets.Add(preset); 110 | } 111 | ret = true; 112 | } 113 | catch (Exception) 114 | { 115 | ret = false; 116 | } 117 | 118 | return ret; 119 | } 120 | 121 | public void Clear(string folderPath = @".\History") 122 | { 123 | Presets.Clear(); 124 | Current = null; 125 | foreach (var file in Directory.EnumerateFiles(folderPath, "*.xml")) 126 | { 127 | try 128 | { 129 | File.Delete(file); 130 | } 131 | catch (Exception) 132 | { 133 | } 134 | } 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchPreset.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text.RegularExpressions; 6 | using System.Xml.Serialization; 7 | using SearchQueryTool.Helpers; 8 | 9 | namespace SearchQueryTool.Model 10 | { 11 | /// 12 | /// One search preset item. These are the individual entries shown in the preset dropdown list. Each entry 13 | /// includes an object with a full search query with all settings and a link to where this preset is stored 14 | /// as XML on disk. The name is just the filename without any extension. 15 | /// 16 | public class SearchPreset 17 | { 18 | /// 19 | /// The name of the search preset (generated automatically from filename). 20 | /// 21 | public string Name { get; set; } 22 | 23 | public string Annotation { get; set; } 24 | 25 | /// 26 | /// The path to the XML file on disk that represents this search preset. 27 | /// 28 | [XmlIgnore] 29 | public string Path { get; set; } 30 | 31 | /// 32 | /// All options for a search request. 33 | /// 34 | public SearchQueryRequest Request { get; set; } 35 | 36 | public SearchResultPresentationSettings PresentationSettings { get; set; } 37 | 38 | /// 39 | /// All connection related options for a search query. 40 | /// 41 | public SearchConnection Connection { get; set; } 42 | 43 | public SearchPreset() 44 | { 45 | Name = "New preset"; 46 | } 47 | 48 | public SearchPreset(string path, bool rethrowException = false) 49 | { 50 | Load(path, rethrowException); 51 | } 52 | 53 | public bool Save() 54 | { 55 | bool r; 56 | try 57 | { 58 | var serializer = new XmlSerializer(typeof(SearchPreset)); 59 | using (var writer = new StringWriter()) 60 | { 61 | serializer.Serialize(writer, this); 62 | var xml = writer.ToString(); 63 | File.WriteAllText(Path, XmlHelper.PrettyXml(xml)); 64 | } 65 | r = true; 66 | } 67 | catch (Exception) 68 | { 69 | r = false; 70 | } 71 | return r; 72 | } 73 | 74 | public bool Include(string filter) 75 | { 76 | var result = true; 77 | if (!string.IsNullOrWhiteSpace(filter)) 78 | { 79 | var name = this.Name; 80 | filter = NormalizeWhitespace(filter); 81 | var nameTokens = GetTokens(name.ToLowerInvariant()); 82 | var filterTokens = GetTokens(filter.ToLowerInvariant()); 83 | result = ContainsAllItems(nameTokens, filterTokens); 84 | } 85 | return result; 86 | } 87 | 88 | private void Load(string path, bool rethrowException = false) 89 | { 90 | if (!String.IsNullOrWhiteSpace(path)) 91 | { 92 | Path = path; 93 | try 94 | { 95 | Name = System.IO.Path.GetFileNameWithoutExtension(Path); 96 | DeserializeSearchPreset(Path); 97 | } 98 | catch (Exception) 99 | { 100 | if (rethrowException) 101 | { 102 | throw; 103 | } 104 | 105 | Name = Name + " (failed)"; 106 | } 107 | } 108 | } 109 | 110 | private void DeserializeSearchPreset(string xmlFilePath) 111 | { 112 | var serializer = new XmlSerializer(typeof(SearchPreset)); 113 | using (var reader = new StreamReader(xmlFilePath)) 114 | { 115 | var preset = serializer.Deserialize(reader) as SearchPreset; 116 | if (preset != null) 117 | { 118 | Request = preset.Request; 119 | Connection = preset.Connection; 120 | Path = xmlFilePath; 121 | Name = preset.Name; 122 | } 123 | } 124 | } 125 | 126 | public static bool ContainsAllItems(List a, List b) 127 | { 128 | return !b.Except(a).Any(); 129 | } 130 | 131 | private static List GetTokens(string input) 132 | { 133 | return input.Split(' ').ToList(); 134 | } 135 | 136 | private static string NormalizeWhitespace(string presetFilter) 137 | { 138 | return Regex.Replace(presetFilter, @"\s+", " "); 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchPresetList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | 5 | namespace SearchQueryTool.Model 6 | { 7 | public class SearchPresetList 8 | { 9 | private string PresetFolderPath { get; set; } 10 | public List Presets; 11 | 12 | public SearchPresetList(string presetFolderPath) 13 | { 14 | PresetFolderPath = presetFolderPath; 15 | Presets = new List(); 16 | ReadFromFolderPath(PresetFolderPath); 17 | } 18 | 19 | private void ReadFromFolderPath(string folderPath = @".\Presets") 20 | { 21 | try 22 | { 23 | foreach (var file in Directory.EnumerateFiles(folderPath, "*.xml")) 24 | { 25 | AddPreset(file); 26 | } 27 | } 28 | catch (Exception) 29 | { 30 | // ignored 31 | } 32 | } 33 | 34 | private void AddPreset(string file) 35 | { 36 | 37 | var preset = new SearchPreset(file); 38 | Presets.Add(preset); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchQueryRequest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.RegularExpressions; 6 | 7 | namespace SearchQueryTool.Model 8 | { 9 | public class SearchQueryRequest : SearchRequest 10 | { 11 | // escape unescaped ,: in the right places 12 | private static readonly Regex ReEscape = new Regex(@"(?[,:])", 13 | RegexOptions.Compiled | RegexOptions.IgnoreCase); 14 | 15 | public bool? EnableStemming { get; set; } 16 | public bool? EnablePhonetic { get; set; } 17 | public bool? EnableNicknames { get; set; } 18 | public bool? TrimDuplicates { get; set; } 19 | public bool? EnableFql { get; set; } 20 | public bool? EnableQueryRules { get; set; } 21 | public bool? ProcessBestBets { get; set; } 22 | public bool? ByPassResultTypes { get; set; } 23 | public bool? ProcessPersonalFavorites { get; set; } 24 | public bool? GenerateBlockRankLog { get; set; } 25 | public bool? IncludeRankDetail { get; set; } 26 | public int? StartRow { get; set; } 27 | public int? RowLimit { get; set; } 28 | public int? RowsPerPage { get; set; } 29 | public string SelectProperties { get; set; } 30 | public string Refiners { get; set; } 31 | public string RefinementFilters { get; set; } 32 | public string HitHighlightedProperties { get; set; } 33 | public string RankingModelId { get; set; } 34 | public string SortList { get; set; } 35 | public string Culture { get; set; } 36 | public string SourceId { get; set; } 37 | public string HiddenConstraints { get; set; } 38 | public string ResultsUrl { get; set; } 39 | public string QueryTag { get; set; } 40 | public string CollapseSpecification { get; set; } 41 | public string QueryTemplate { get; set; } 42 | public long? TrimDuplicatesIncludeId { get; set; } 43 | public string ClientType { get; set; } 44 | public string PersonalizationData { get; set; } 45 | public bool? EnableMultiGeoSearch { get; set; } 46 | 47 | public string AppendedQueryProperties { get; set; } 48 | public string MultiGeoSearchConfiguration { get; set; } // Make sure it is formatted according to method type. See MultiGeoSearchConfiguration 49 | public bool? IncludePersonalOneDriveResults { get; set; } // https://support.microsoft.com/en-us/help/4469277/sharepoint-online-search-will-not-return-private-onedrive-results 50 | 51 | public SearchQueryRequest Clone() 52 | { 53 | return (SearchQueryRequest)this.MemberwiseClone(); 54 | } 55 | 56 | public override string GenerateHttpGetUri() 57 | { 58 | string sharepointSiteUrl = this.SharePointSiteUrl; 59 | 60 | StringBuilder uriBuilder = new StringBuilder(); 61 | 62 | if (!String.IsNullOrWhiteSpace(sharepointSiteUrl)) 63 | { 64 | uriBuilder.Append(sharepointSiteUrl); 65 | 66 | if (!sharepointSiteUrl.EndsWith("/")) 67 | uriBuilder.Append("/"); 68 | } 69 | 70 | uriBuilder.AppendFormat("_api/search/query?querytext='{0}'", UrlEncode(this.QueryText?.Replace("'","''"))); 71 | 72 | if (this.EnableStemming == true) 73 | uriBuilder.Append("&enablestemming=true"); 74 | else if (this.EnableStemming == false) 75 | uriBuilder.Append("&enablestemming=false"); 76 | 77 | if (this.EnablePhonetic == true) 78 | uriBuilder.Append("&enablephonetic=true"); 79 | else if (this.EnablePhonetic == false) 80 | uriBuilder.Append("&enablephonetic=false"); 81 | 82 | if (this.EnableNicknames == true) 83 | uriBuilder.Append("&enablenicknames=true"); 84 | if (this.EnableNicknames == false) 85 | uriBuilder.Append("&enablenicknames=false"); 86 | 87 | if (this.TrimDuplicates == true) 88 | uriBuilder.Append("&trimduplicates=true"); 89 | else if (this.TrimDuplicates == false) 90 | uriBuilder.Append("&trimduplicates=false"); 91 | 92 | if (this.EnableFql == true) 93 | uriBuilder.Append("&enablefql=true"); 94 | else if (this.EnableFql == false) 95 | uriBuilder.Append("&enablefql=false"); 96 | 97 | if (this.EnableQueryRules == true) 98 | uriBuilder.Append("&enablequeryrules=true"); 99 | else if (this.EnableQueryRules == false) 100 | uriBuilder.Append("&enablequeryrules=false"); 101 | 102 | if (this.ProcessBestBets == true) 103 | uriBuilder.Append("&processbestbets=true"); 104 | else if (this.ProcessBestBets == false) 105 | uriBuilder.Append("&processbestbets=false"); 106 | 107 | if (this.ByPassResultTypes == true) 108 | uriBuilder.Append("&bypassresulttypes=true"); 109 | else if (this.ByPassResultTypes == false) 110 | uriBuilder.Append("&bypassresulttypes=false"); 111 | 112 | if (this.ProcessPersonalFavorites == true) 113 | uriBuilder.Append("&processpersonalfavorites=true"); 114 | else if (this.ProcessPersonalFavorites == false) 115 | uriBuilder.Append("&processpersonalfavorites=false"); 116 | 117 | if (this.GenerateBlockRankLog == true) 118 | uriBuilder.Append("&generateblockranklog=true"); 119 | else if (this.GenerateBlockRankLog == false) 120 | uriBuilder.Append("&generateblockranklog=false"); 121 | 122 | if (this.StartRow.HasValue && this.StartRow.Value > 0) 123 | uriBuilder.AppendFormat("&startrow={0}", this.StartRow.Value); 124 | 125 | if (this.RowsPerPage.HasValue) 126 | uriBuilder.AppendFormat("&rowsperpage={0}", this.RowsPerPage.Value); 127 | 128 | if (this.RowLimit.HasValue) 129 | uriBuilder.AppendFormat("&rowlimit={0}", this.RowLimit.Value); 130 | 131 | if (!String.IsNullOrEmpty(this.QueryTemplate)) 132 | uriBuilder.AppendFormat("&querytemplate='{0}'", UrlEncode(this.QueryTemplate)); 133 | 134 | SetRankDetailProperties(); 135 | 136 | if (!String.IsNullOrEmpty(this.SelectProperties)) 137 | uriBuilder.AppendFormat("&selectproperties='{0}'", UrlEncode(this.SelectProperties)); 138 | 139 | 140 | List customPropertyParts = new List(); 141 | 142 | if (!String.IsNullOrEmpty(this.Refiners)) 143 | uriBuilder.AppendFormat("&refiners='{0}'", UrlEncode(this.Refiners.Replace(" ", ""))); 144 | 145 | if (!String.IsNullOrEmpty(this.RefinementFilters)) 146 | uriBuilder.AppendFormat("&refinementfilters='{0}'", UrlEncode(this.RefinementFilters)); 147 | 148 | if (!String.IsNullOrEmpty(this.SortList)) 149 | uriBuilder.AppendFormat("&sortlist='{0}'", UrlEncode(this.SortList)); 150 | 151 | if (!String.IsNullOrEmpty(this.HitHighlightedProperties)) 152 | uriBuilder.AppendFormat("&hithighlightedproperties='{0}'", UrlEncode(this.HitHighlightedProperties)); 153 | 154 | if (!String.IsNullOrEmpty(this.RankingModelId)) 155 | uriBuilder.AppendFormat("&rankingmodelid='{0}'", UrlEncode(this.RankingModelId)); 156 | 157 | if (!String.IsNullOrEmpty(this.Culture)) 158 | uriBuilder.AppendFormat("&culture={0}", UrlEncode(this.Culture)); 159 | 160 | if (!String.IsNullOrEmpty(this.SourceId)) 161 | { 162 | if (this.SourceId.Contains("|") || this.SourceId.Contains(":")) 163 | { 164 | string[] sourceParts = this.SourceId.Split('|', ':'); 165 | customPropertyParts.Add("SourceLevel:" + sourceParts[0]); 166 | customPropertyParts.Add("SourceName:" + sourceParts[1]); 167 | } 168 | else 169 | { 170 | uriBuilder.AppendFormat("&sourceid='{0}'", UrlEncode(this.SourceId)); 171 | } 172 | } 173 | 174 | if (this.EnableMultiGeoSearch == true) 175 | { 176 | customPropertyParts.Add("EnableMultiGeoSearch:true"); 177 | 178 | if (!String.IsNullOrWhiteSpace(MultiGeoSearchConfiguration)) 179 | { 180 | customPropertyParts.Add($"MultiGeoSearchConfiguration:{MultiGeoSearchConfiguration}"); 181 | } 182 | } 183 | else if (this.EnableMultiGeoSearch == false) 184 | { 185 | customPropertyParts.Add("EnableMultiGeoSearch:false"); 186 | } 187 | 188 | if (this.IncludePersonalOneDriveResults.HasValue && this.IncludePersonalOneDriveResults.Value) 189 | { 190 | customPropertyParts.Add("ContentSetting:3"); 191 | } 192 | 193 | if (!string.IsNullOrWhiteSpace(this.AppendedQueryProperties)) 194 | { 195 | foreach (var item in this.AppendedQueryProperties.Split(',')) 196 | { 197 | customPropertyParts.Add(item.Trim()); 198 | } 199 | } 200 | 201 | if (!String.IsNullOrEmpty(this.HiddenConstraints)) 202 | uriBuilder.AppendFormat("&hiddenconstraints='{0}'", UrlEncode(this.HiddenConstraints)); 203 | 204 | if (!String.IsNullOrEmpty(this.PersonalizationData)) 205 | uriBuilder.AppendFormat("&personalizationdata='{0}'", UrlEncode(this.PersonalizationData)); 206 | 207 | if (!String.IsNullOrEmpty(this.ResultsUrl)) 208 | uriBuilder.AppendFormat("&resultsurl='{0}'", UrlEncode(this.ResultsUrl)); 209 | 210 | if (!String.IsNullOrEmpty(this.QueryTag)) 211 | uriBuilder.AppendFormat("&querytag='{0}'", UrlEncode(this.QueryTag)); 212 | 213 | if (!String.IsNullOrEmpty(this.CollapseSpecification)) 214 | uriBuilder.AppendFormat("&collapsespecification='{0}'", UrlEncode(this.CollapseSpecification)); 215 | 216 | if (!String.IsNullOrEmpty(this.ClientType)) 217 | uriBuilder.AppendFormat("&clienttype='{0}'", this.ClientType); 218 | 219 | if (this.TrimDuplicatesIncludeId.HasValue) 220 | uriBuilder.AppendFormat("&trimduplicatesincludeid={0}", this.TrimDuplicatesIncludeId.Value); 221 | 222 | if (this.AuthenticationType == AuthenticationType.Anonymous) 223 | { 224 | uriBuilder.Append("&QueryTemplatePropertiesUrl='spfile://webroot/queryparametertemplate.xml'"); 225 | } 226 | 227 | if (customPropertyParts.Count > 0) 228 | { 229 | uriBuilder.AppendFormat("&properties='{0}'", string.Join(",", customPropertyParts)); 230 | } 231 | return uriBuilder.ToString(); 232 | } 233 | 234 | private void SetRankDetailProperties() 235 | { 236 | if (this.IncludeRankDetail.HasValue && this.IncludeRankDetail.Value) 237 | { 238 | if (string.IsNullOrWhiteSpace(this.SelectProperties)) 239 | { 240 | this.SelectProperties = "rankdetail,title,path,language,workid"; 241 | } 242 | else 243 | { 244 | var props = this.SelectProperties.Split(',').ToList(); 245 | if (!props.Exists(p => p.Equals("RankDetail", StringComparison.InvariantCultureIgnoreCase))) 246 | props.Add("RankDetail"); 247 | if (!props.Exists(p => p.Equals("Title", StringComparison.InvariantCultureIgnoreCase))) 248 | props.Add("Title"); 249 | if (!props.Exists(p => p.Equals("Path", StringComparison.InvariantCultureIgnoreCase))) 250 | props.Add("Path"); 251 | if (!props.Exists(p => p.Equals("Language", StringComparison.InvariantCultureIgnoreCase))) 252 | props.Add("Language"); 253 | this.SelectProperties = string.Join(",", props); 254 | } 255 | } 256 | if (this.IncludeRankDetail.HasValue && !this.IncludeRankDetail.Value && !string.IsNullOrWhiteSpace(this.SelectProperties)) 257 | { 258 | var props = this.SelectProperties.Split(',').ToList(); 259 | if (props.Exists(p => p.Equals("RankDetail", StringComparison.InvariantCultureIgnoreCase))) 260 | { 261 | props.Remove("RankDetail"); 262 | props.Remove("rankdetail"); 263 | this.SelectProperties = string.Join(",", props); 264 | } 265 | } 266 | } 267 | 268 | public override string GenerateHttpPostUri() 269 | { 270 | string restUri = this.SharePointSiteUrl; 271 | 272 | StringBuilder uriBuilder = new StringBuilder(); 273 | 274 | if (!String.IsNullOrWhiteSpace(restUri)) 275 | { 276 | uriBuilder.Append(restUri); 277 | 278 | if (!restUri.EndsWith("/")) 279 | uriBuilder.Append("/"); 280 | } 281 | 282 | uriBuilder.Append("_api/search/postquery"); 283 | return uriBuilder.ToString(); 284 | } 285 | 286 | public override string GenerateHttpPostBodyPayload() 287 | { 288 | StringBuilder searchRequestBuilder = new StringBuilder(); 289 | List customPropertyParts = new List(); 290 | 291 | searchRequestBuilder.AppendFormat("{{'request': {{ 'Querytext':'{0}'", this.QueryText?.Replace("'","\\'")); 292 | 293 | if (this.EnableStemming == true) 294 | searchRequestBuilder.Append(", 'EnableStemming':true"); 295 | else if (this.EnableStemming == false) 296 | searchRequestBuilder.Append(", 'EnableStemming':false"); 297 | 298 | if (this.EnablePhonetic == true) 299 | searchRequestBuilder.Append(", 'EnablePhonetic':true"); 300 | else if (this.EnablePhonetic == false) 301 | searchRequestBuilder.Append(", 'EnablePhonetic':false"); 302 | 303 | if (this.EnableNicknames == true) 304 | searchRequestBuilder.Append(", 'EnableNicknames':true"); 305 | if (this.EnableNicknames == false) 306 | searchRequestBuilder.Append(", 'EnableNicknames':false"); 307 | 308 | if (this.TrimDuplicates == true) 309 | searchRequestBuilder.Append(", 'TrimDuplicates':true"); 310 | else if (this.TrimDuplicates == false) 311 | searchRequestBuilder.Append(", 'TrimDuplicates':false"); 312 | 313 | if (this.EnableFql == true) 314 | searchRequestBuilder.Append(", 'EnableFQL':true"); 315 | else if (this.EnableFql == false) 316 | searchRequestBuilder.Append(", 'EnableFQL':false"); 317 | 318 | if (this.ProcessBestBets == true) 319 | searchRequestBuilder.Append(", 'ProcessBestBets':true"); 320 | else if (this.ProcessBestBets == false) 321 | searchRequestBuilder.Append(", 'ProcessBestBets':false"); 322 | 323 | if (this.ByPassResultTypes == true) 324 | searchRequestBuilder.Append(", 'BypassResultTypes':true"); 325 | else if (this.ByPassResultTypes == false) 326 | searchRequestBuilder.Append(", 'BypassResultTypes':false"); 327 | 328 | if (this.EnableQueryRules == true) 329 | searchRequestBuilder.Append(", 'EnableQueryRules':true"); 330 | else if (this.EnableQueryRules == false) 331 | searchRequestBuilder.Append(", 'EnableQueryRules':false"); 332 | 333 | if (this.ProcessPersonalFavorites == true) 334 | searchRequestBuilder.Append(", 'ProcessPersonalFavorites':true"); 335 | else if (this.ProcessPersonalFavorites == false) 336 | searchRequestBuilder.Append(", 'ProcessPersonalFavorites':false"); 337 | 338 | if (this.GenerateBlockRankLog == true) 339 | searchRequestBuilder.Append(", 'GenerateBlockRankLog':true"); 340 | else if (this.GenerateBlockRankLog == false) 341 | searchRequestBuilder.Append(", 'GenerateBlockRankLog':false"); 342 | 343 | if (this.StartRow.HasValue && this.StartRow.Value > 0) 344 | searchRequestBuilder.AppendFormat(", 'StartRow':{0}", this.StartRow.Value); 345 | 346 | if (this.RowsPerPage.HasValue) 347 | searchRequestBuilder.AppendFormat(", 'RowsPerPage':{0}", this.RowsPerPage.Value); 348 | 349 | if (this.RowLimit.HasValue) 350 | searchRequestBuilder.AppendFormat(", 'RowLimit':{0}", this.RowLimit.Value); 351 | 352 | SetRankDetailProperties(); 353 | 354 | if (!String.IsNullOrEmpty(this.SelectProperties)) 355 | { 356 | var props = this.SelectProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 357 | searchRequestBuilder.AppendFormat(", 'SelectProperties':{{'results':['{0}']}}", 358 | String.Join("','", props)); 359 | } 360 | 361 | // XXX: BDW: do I need code here? 362 | 363 | if (!String.IsNullOrEmpty(this.Refiners)) 364 | searchRequestBuilder.AppendFormat(", 'Refiners':'{0}'", this.Refiners.Replace(" ", "")); 365 | 366 | if (!String.IsNullOrEmpty(this.RefinementFilters)) 367 | { 368 | searchRequestBuilder.AppendFormat(", 'RefinementFilters':{{'results':['{0}']}}", this.RefinementFilters.Replace("|", "','")); 369 | } 370 | 371 | if (!String.IsNullOrEmpty(this.SortList)) 372 | { 373 | var sorts = this.SortList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 374 | List sortsL = new List(); 375 | foreach (var sort in sorts) 376 | { 377 | var parts = sort.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); 378 | if (parts.Length == 2) 379 | { 380 | if (!String.IsNullOrWhiteSpace(parts[0]) && !String.IsNullOrWhiteSpace(parts[1])) 381 | { 382 | string direction = ""; 383 | if (parts[1].ToLower() == "descending") 384 | direction = "1"; 385 | else if (parts[1].ToLower() == "ascending") 386 | direction = "0"; 387 | 388 | sortsL.Add(String.Format("{{'Property':'{0}','Direction':'{1}'}}", parts[0], direction)); 389 | } 390 | } 391 | } 392 | searchRequestBuilder.AppendFormat(", 'SortList':{{'results':[{0}]}}", String.Join(",", sortsL)); 393 | } 394 | 395 | if (!String.IsNullOrEmpty(this.HitHighlightedProperties)) 396 | { 397 | var props = this.HitHighlightedProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 398 | searchRequestBuilder.AppendFormat(", 'HitHighlightedProperties':{{'results':['{0}']}}", 399 | String.Join("','", props)); 400 | } 401 | 402 | if (this.TrimDuplicatesIncludeId.HasValue) 403 | searchRequestBuilder.AppendFormat(", 'TrimDuplicatesIncludeId':'{0}'", 404 | this.TrimDuplicatesIncludeId.Value); 405 | 406 | if (!String.IsNullOrEmpty(this.QueryTemplate)) 407 | searchRequestBuilder.AppendFormat(", 'QueryTemplate':'{0}'", this.QueryTemplate); 408 | 409 | if (!String.IsNullOrEmpty(this.RankingModelId)) 410 | searchRequestBuilder.AppendFormat(", 'RankingModelId':'{0}'", this.RankingModelId); 411 | 412 | if (!String.IsNullOrEmpty(this.Culture)) 413 | searchRequestBuilder.AppendFormat(", 'Culture':{0}", this.Culture); 414 | 415 | if (!String.IsNullOrEmpty(this.SourceId)) 416 | { 417 | if (this.SourceId.Contains("|") || this.SourceId.Contains(":")) 418 | { 419 | string[] sourceParts = this.SourceId.Split('|', ':'); 420 | customPropertyParts.Add(GetPropertiesJSON("SourceLevel:" + sourceParts[0])); 421 | customPropertyParts.Add(GetPropertiesJSON("SourceName:" + sourceParts[1])); 422 | } 423 | else 424 | { 425 | searchRequestBuilder.AppendFormat(", 'SourceId':'{0}'", this.SourceId); 426 | } 427 | } 428 | 429 | 430 | if (this.EnableMultiGeoSearch == true) 431 | { 432 | customPropertyParts.Add(GetPropertiesJSON("EnableMultiGeoSearch:true")); 433 | 434 | if (!String.IsNullOrWhiteSpace(MultiGeoSearchConfiguration)) 435 | { 436 | customPropertyParts.Add(GetPropertiesJSON($"MultiGeoSearchConfiguration:{MultiGeoSearchConfiguration}")); 437 | } 438 | } 439 | else if (this.EnableMultiGeoSearch == false) 440 | { 441 | customPropertyParts.Add(GetPropertiesJSON("EnableMultiGeoSearch:false")); 442 | } 443 | 444 | if (!string.IsNullOrWhiteSpace(this.AppendedQueryProperties)) 445 | { 446 | foreach (var item in this.AppendedQueryProperties.Split(',')) 447 | { 448 | customPropertyParts.Add(GetPropertiesJSON(item.Trim())); 449 | } 450 | } 451 | 452 | if (!String.IsNullOrEmpty(this.HiddenConstraints)) 453 | searchRequestBuilder.AppendFormat(", 'HiddenConstraints':'{0}'", this.HiddenConstraints); 454 | 455 | if (!String.IsNullOrEmpty(this.PersonalizationData)) 456 | searchRequestBuilder.AppendFormat(", 'PersonalizationData':'{0}'", this.PersonalizationData); 457 | 458 | if (!String.IsNullOrEmpty(this.ResultsUrl)) 459 | searchRequestBuilder.AppendFormat(", 'ResultsUrl':'{0}'", this.ResultsUrl); 460 | 461 | if (!String.IsNullOrEmpty(this.QueryTag)) 462 | searchRequestBuilder.AppendFormat(", 'QueryTag':'{0}'", this.QueryTag); 463 | 464 | if (!String.IsNullOrEmpty(this.CollapseSpecification)) 465 | searchRequestBuilder.AppendFormat(", 'CollapseSpecification':'{0}'", this.CollapseSpecification); 466 | 467 | if (!String.IsNullOrEmpty(this.ClientType)) 468 | searchRequestBuilder.AppendFormat(", 'ClientType':'{0}'", this.ClientType); 469 | 470 | if (this.AuthenticationType == AuthenticationType.Anonymous) 471 | { 472 | searchRequestBuilder.Append( 473 | ", 'QueryTemplatePropertiesUrl':'spfile://webroot/queryparametertemplate.xml'"); 474 | } 475 | 476 | if (customPropertyParts.Count > 0) 477 | { 478 | searchRequestBuilder.AppendFormat(", 'Properties':{{'results':[{0}]}}", String.Join(",", customPropertyParts)); 479 | } 480 | 481 | searchRequestBuilder.Append("} }"); 482 | return searchRequestBuilder.ToString(); 483 | } 484 | 485 | private string GetPropertiesJSON(string value) 486 | { 487 | 488 | string[] pair = value.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); 489 | 490 | bool isBool = bool.TryParse(pair[1].Trim(), out bool dummyBool); 491 | bool isInt = int.TryParse(pair[1].Trim(), out int dummyInt); 492 | string template = "{{'Name' : '{0}','Value' :{{'StrVal' : '{1}','QueryPropertyValueTypeIndex' : 1}}}}"; 493 | if (isBool) 494 | { 495 | template = "{{'Name' : '{0}','Value' :{{'BoolVal' : {1},'QueryPropertyValueTypeIndex' : 3}}}}"; 496 | } 497 | else if (isInt) 498 | { 499 | template = "{{'Name' : '{0}','Value' :{{'IntVal' : {1},'QueryPropertyValueTypeIndex' : 2}}}}"; 500 | } 501 | 502 | return string.Format(template, pair[0].Trim(), pair[1].Trim()); 503 | } 504 | } 505 | } -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchQueryResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Runtime.Serialization.Json; 6 | using System.Text; 7 | using System.Xml; 8 | using System.Xml.Linq; 9 | using System.Xml.XPath; 10 | 11 | namespace SearchQueryTool.Model 12 | { 13 | public class ResultItem : SortedDictionary 14 | { 15 | 16 | /// 17 | /// Return the title of the result. 18 | /// 19 | public string Title 20 | { 21 | get 22 | { 23 | KeyValuePair title = this.FirstOrDefault(x => x.Key.Equals("Title", StringComparison.InvariantCultureIgnoreCase)); 24 | return title.Value; 25 | } 26 | } 27 | 28 | /// 29 | /// Returns the path of the result. 30 | /// 31 | public string Path 32 | { 33 | get 34 | { 35 | return this.FirstOrDefault(x => x.Key.Equals("Path", StringComparison.InvariantCultureIgnoreCase)).Value; 36 | } 37 | } 38 | 39 | } 40 | 41 | public class RefinerResult : List 42 | { 43 | public string Name { get; set; } 44 | } 45 | 46 | public class RefinementItem 47 | { 48 | public long Count { get; set; } 49 | public string Name { get; set; } 50 | public string Token { get; set; } 51 | public string Value { get; set; } 52 | } 53 | 54 | public class PromotedItem 55 | { 56 | public string Title { get; set; } 57 | public string Url { get; set; } 58 | public string Description { get; set; } 59 | public string isVisualBestBet { get; set; } 60 | public string PiSearchResultId { get; set; } 61 | public string renderTemplateId { get; set; } 62 | } 63 | 64 | public class QueryResult 65 | { 66 | public string QueryId { get; set; } 67 | public string QueryRuleId { get; set; } 68 | public string QueryModification { get; set; } 69 | public int TotalRows { get; set; } 70 | public int TotalRowsIncludingDuplicates { get; set; } 71 | public List RelevantResults { get; set; } 72 | public List RefinerResults { get; set; } 73 | public List PromotedResults { get; set; } 74 | 75 | public string ResultTitle { get; internal set; } 76 | public string ResultTitleUrl { get; internal set; } 77 | } 78 | 79 | /// 80 | /// Represents the search query results. 81 | /// 82 | public class SearchQueryResult : SearchResult 83 | { 84 | public SearchQueryResult() 85 | : base() 86 | { 87 | } 88 | 89 | public string SerializedQuery { get; private set; } 90 | public string QueryElapsedTime { get; private set; } 91 | public List TriggeredRules { get; private set; } 92 | public QueryResult PrimaryQueryResult { get; private set; } 93 | public List SecondaryQueryResults { get; private set; } 94 | 95 | public bool IsPartial { get; internal set; } 96 | public string MultiGeoSearchStatus { get; internal set; } 97 | public bool BestBetsTriggered { get; internal set; } 98 | public int BestBetsCount { get; internal set; } 99 | 100 | /// 101 | /// Fireoff processing of the search result content. 102 | /// 103 | public override void Process() 104 | { 105 | if (this.ContentType.StartsWith("application/json")) 106 | { 107 | if (this.RequestMethod == "GET") 108 | { 109 | ProcessJsonFromGetRequest(); 110 | } 111 | else 112 | { 113 | ProcessJsonFromPostRequest(); 114 | } 115 | } 116 | else if (this.ContentType.StartsWith("application/xml")) 117 | { 118 | ProcessXml(); 119 | } 120 | } 121 | 122 | private static XElement GetResultXML(string itsastring) 123 | { 124 | byte[] bytes = new UTF8Encoding().GetBytes(itsastring); 125 | var reader = new StreamReader(new MemoryStream(bytes), true); 126 | var xr = XmlReader.Create(reader, new XmlReaderSettings { CheckCharacters = false }); 127 | return XElement.Load(xr); 128 | } 129 | private void ProcessXml() 130 | { 131 | XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices"; 132 | 133 | var root = GetResultXML(this.ResponseContent); 134 | 135 | if (root != null && root.HasElements) 136 | { 137 | this.QueryElapsedTime = (string)root.Element(d + "ElapsedTime"); 138 | 139 | XElement propertiesElm = root.Element(d + "Properties"); 140 | if (propertiesElm != null && propertiesElm.HasElements) 141 | { 142 | foreach (var elm in propertiesElm.Elements(d + "element")) 143 | { 144 | if (elm != null && elm.Element(d + "Key") != null) 145 | { 146 | if (elm.Element(d + "Key").Value == "SerializedQuery") 147 | { 148 | this.SerializedQuery = elm.Element(d + "Value").Value; 149 | // break; // need to parse through all elements 150 | } 151 | else if (elm.Element(d + "Key").Value == "IsPartial") 152 | { 153 | if (bool.TryParse(elm.Element(d + "Value").Value, out bool isPartial)) 154 | { 155 | IsPartial = isPartial; 156 | } 157 | } 158 | else if (elm.Element(d + "Key").Value == "MultiGeoSearchStatus") 159 | { 160 | this.MultiGeoSearchStatus = elm.Element(d + "Value").Value; 161 | } 162 | } 163 | } 164 | } 165 | 166 | #region Primary Query Result 167 | 168 | var primaryQueryResult = root.Element(d + "PrimaryQueryResult"); 169 | if (primaryQueryResult != null) 170 | { 171 | this.PrimaryQueryResult = new QueryResult(); 172 | 173 | if (primaryQueryResult.Element(d + "QueryId") != null) 174 | { 175 | this.PrimaryQueryResult.QueryId = (string)primaryQueryResult.Element(d + "QueryId"); 176 | } 177 | 178 | if (primaryQueryResult.Element(d + "QueryRuleId") != null) 179 | { 180 | this.PrimaryQueryResult.QueryRuleId = (string)primaryQueryResult.Element(d + "QueryRuleId"); 181 | } 182 | 183 | #region Relevant Results 184 | 185 | var relevantResults = primaryQueryResult.Element(d + "RelevantResults"); 186 | if (relevantResults != null) 187 | { 188 | if (relevantResults.Element(d + "TotalRows") != null) 189 | { 190 | this.PrimaryQueryResult.TotalRows = (int)relevantResults.Element(d + "TotalRows"); 191 | } 192 | 193 | if (relevantResults.Element(d + "TotalRowsIncludingDuplicates") != null) 194 | { 195 | this.PrimaryQueryResult.TotalRowsIncludingDuplicates = (int)relevantResults.Element(d + "TotalRowsIncludingDuplicates"); 196 | } 197 | 198 | XElement queryMod = relevantResults.Descendants(d + "Key").FirstOrDefault(e => e.Value == "QueryModification"); 199 | if (queryMod != null) 200 | { 201 | this.PrimaryQueryResult.QueryModification = queryMod.XPathSelectElement("..").Element(d + "Value").Value; 202 | } 203 | 204 | var table = relevantResults.Element(d + "Table"); 205 | if (table != null && table.HasElements) 206 | { 207 | var rows = table.Element(d + "Rows"); 208 | if (rows != null && rows.HasElements) 209 | { 210 | List resultItems = new List(); 211 | 212 | var items = rows.Elements(d + "element"); 213 | foreach (var item in items) 214 | { 215 | ResultItem resultItem = new ResultItem(); 216 | 217 | if (item.Element(d + "Cells") != null 218 | && item.Element(d + "Cells").HasElements) 219 | { 220 | var itemValues = item.Element(d + "Cells").Elements(d + "element"); 221 | foreach (var itemValue in itemValues) 222 | { 223 | resultItem.Add(itemValue.Element(d + "Key").Value, itemValue.Element(d + "Value").Value); 224 | } 225 | } 226 | 227 | resultItems.Add(resultItem); 228 | } 229 | 230 | this.PrimaryQueryResult.RelevantResults = resultItems; 231 | } 232 | } 233 | } 234 | 235 | #endregion 236 | 237 | #region Refinement Results 238 | 239 | var refinementResults = primaryQueryResult.Element(d + "RefinementResults"); 240 | if (refinementResults != null) 241 | { 242 | var refiners = refinementResults.Element(d + "Refiners"); 243 | if (refiners != null && refiners.HasElements) 244 | { 245 | List refinerResults = new List(); 246 | 247 | var items = refiners.Elements(d + "element"); 248 | foreach (var item in items) 249 | { 250 | RefinerResult refinerResult = new RefinerResult(); 251 | refinerResult.Name = (string)item.Element(d + "Name"); 252 | 253 | if (item.Element(d + "Entries") != null && item.Element(d + "Entries").HasElements) 254 | { 255 | var entries = item.Element(d + "Entries").Elements(d + "element"); 256 | foreach (var entry in entries) 257 | { 258 | refinerResult.Add(new RefinementItem 259 | { 260 | Count = (long)entry.Element(d + "RefinementCount"), 261 | Name = (string)entry.Element(d + "RefinementName"), 262 | Token = (string)entry.Element(d + "RefinementToken"), 263 | Value = (string)entry.Element(d + "RefinementValue"), 264 | }); 265 | } 266 | } 267 | 268 | refinerResults.Add(refinerResult); 269 | } 270 | 271 | this.PrimaryQueryResult.RefinerResults = refinerResults; 272 | } 273 | } 274 | 275 | #endregion 276 | } 277 | 278 | #endregion 279 | 280 | #region Secondary Query Results 281 | 282 | XElement secondaryQueryResults = root.Element(d + "SecondaryQueryResults"); 283 | if (secondaryQueryResults != null && secondaryQueryResults.HasElements) 284 | { 285 | this.SecondaryQueryResults = new List(); 286 | 287 | var resultItems = secondaryQueryResults.Elements(d + "element"); 288 | foreach (var resultItem in resultItems) 289 | { 290 | QueryResult secondaryQueryResult = new QueryResult(); 291 | 292 | if (resultItem.Element(d + "QueryId") != null) 293 | { 294 | secondaryQueryResult.QueryId = (string)resultItem.Element(d + "QueryId"); 295 | } 296 | 297 | if (resultItem.Element(d + "QueryRuleId") != null) 298 | { 299 | secondaryQueryResult.QueryRuleId = (string)resultItem.Element(d + "QueryRuleId"); 300 | } 301 | 302 | var relevantResults = resultItem.Element(d + "RelevantResults"); 303 | if (relevantResults != null) 304 | { 305 | if (relevantResults.Element(d + "TotalRows") != null) 306 | { 307 | secondaryQueryResult.TotalRows = (int)relevantResults.Element(d + "TotalRows"); 308 | } 309 | 310 | if (relevantResults.Element(d + "TotalRowsIncludingDuplicates") != null) 311 | { 312 | secondaryQueryResult.TotalRowsIncludingDuplicates = (int)relevantResults.Element(d + "TotalRowsIncludingDuplicates"); 313 | } 314 | 315 | XElement queryMod = relevantResults.Descendants(d + "Key").FirstOrDefault(e => e.Value == "QueryModification"); 316 | if (queryMod != null) 317 | { 318 | secondaryQueryResult.QueryModification = queryMod.XPathSelectElement("..").Element(d + "Value").Value; 319 | } 320 | 321 | var table = relevantResults.Element(d + "Table"); 322 | if (table != null && table.HasElements) 323 | { 324 | var rows = table.Element(d + "Rows"); 325 | if (rows != null && rows.HasElements) 326 | { 327 | List resultRows = new List(); 328 | 329 | var items = rows.Elements(d + "element"); 330 | foreach (var item in items) 331 | { 332 | ResultItem resultRow = new ResultItem(); 333 | 334 | if (item.Element(d + "Cells") != null && item.Element(d + "Cells").HasElements) 335 | { 336 | var itemValues = item.Element(d + "Cells").Elements(d + "element"); 337 | foreach (var itemValue in itemValues) 338 | { 339 | resultRow.Add(itemValue.Element(d + "Key").Value, itemValue.Element(d + "Value").Value); 340 | } 341 | } 342 | 343 | resultRows.Add(resultRow); 344 | } 345 | 346 | secondaryQueryResult.RelevantResults = resultRows; 347 | } 348 | } 349 | } 350 | 351 | this.SecondaryQueryResults.Add(secondaryQueryResult); 352 | } 353 | 354 | } 355 | 356 | #endregion 357 | } 358 | } 359 | 360 | private void ProcessJsonFromGetRequest() 361 | { 362 | XmlReader reader = 363 | JsonReaderWriterFactory 364 | .CreateJsonReader(Encoding.UTF8.GetBytes(this.ResponseContent), new XmlDictionaryReaderQuotas()); 365 | 366 | XElement root = XElement.Load(reader); 367 | XElement queryElm = root.XPathSelectElement("//query"); 368 | 369 | if (queryElm != null) 370 | { 371 | XElement elapsedTimeElm = queryElm.Element("ElapsedTime"); 372 | if (elapsedTimeElm != null) 373 | { 374 | this.QueryElapsedTime = elapsedTimeElm.Value; 375 | } 376 | 377 | XElement propertiesElm = queryElm.Element("Properties"); 378 | if (propertiesElm != null && propertiesElm.HasElements) 379 | { 380 | if (propertiesElm.Element("results") != null) 381 | { 382 | foreach (var item in propertiesElm.Element("results").Elements("item")) 383 | { 384 | if (item != null && item.Element("Key") != null) 385 | { 386 | if (item.Element("Key").Value == "SerializedQuery") 387 | { 388 | this.SerializedQuery = item.Element("Value").Value; 389 | } 390 | else if (item.Element("Key").Value == "IsPartial") 391 | { 392 | if (bool.TryParse(item.Element("Value").Value, out bool isPartial)) 393 | { 394 | this.IsPartial = isPartial; 395 | } 396 | } 397 | else if (item.Element("Key").Value == "MultiGeoSearchStatus") 398 | { 399 | this.MultiGeoSearchStatus = item.Element("Value").Value; 400 | } 401 | } 402 | } 403 | } 404 | } 405 | 406 | #region Triggered Rules 407 | 408 | XElement triggeredRulesElm = queryElm.Element("TriggeredRules"); 409 | if (triggeredRulesElm != null && triggeredRulesElm.HasElements) 410 | { 411 | if (triggeredRulesElm.Element("results") != null) 412 | { 413 | this.TriggeredRules = new List(); 414 | 415 | foreach (var item in triggeredRulesElm.Element("results").Elements("item")) 416 | { 417 | this.TriggeredRules.Add(item.Value); 418 | } 419 | } 420 | } 421 | 422 | #endregion 423 | 424 | #region Primary Query Results 425 | 426 | XElement primaryQueryResult = queryElm.Element("PrimaryQueryResult"); 427 | if (primaryQueryResult != null) 428 | { 429 | this.PrimaryQueryResult = new QueryResult(); 430 | 431 | if (primaryQueryResult.Element("QueryId") != null) 432 | { 433 | this.PrimaryQueryResult.QueryId = (string)primaryQueryResult.Element("QueryId"); 434 | } 435 | 436 | if (primaryQueryResult.Element("QueryRuleId") != null) 437 | { 438 | this.PrimaryQueryResult.QueryRuleId = (string)primaryQueryResult.Element("QueryRuleId"); 439 | } 440 | 441 | #region Relevant Results 442 | 443 | var relevantResults = primaryQueryResult.Element("RelevantResults"); 444 | if (relevantResults != null) 445 | { 446 | if (relevantResults.Element("TotalRows") != null) 447 | { 448 | this.PrimaryQueryResult.TotalRows = (int)relevantResults.Element("TotalRows"); 449 | } 450 | 451 | if (relevantResults.Element("TotalRowsIncludingDuplicates") != null) 452 | { 453 | this.PrimaryQueryResult.TotalRowsIncludingDuplicates = (int)relevantResults.Element("TotalRowsIncludingDuplicates"); 454 | } 455 | 456 | XElement queryMod = relevantResults.Descendants("Key").FirstOrDefault(e => e.Value == "QueryModification"); 457 | if (queryMod != null) 458 | { 459 | this.PrimaryQueryResult.QueryModification = queryMod.XPathSelectElement("..").Element("Value").Value; 460 | } 461 | 462 | var table = relevantResults.Element("Table"); 463 | if (table != null && table.HasElements) 464 | { 465 | var rows = table.Element("Rows"); 466 | if (rows != null && rows.Element("results") != null && rows.Element("results").HasElements) 467 | { 468 | List resultItems = new List(); 469 | 470 | var items = rows.Element("results").Elements("item"); 471 | foreach (var item in items) 472 | { 473 | ResultItem resultItem = new ResultItem(); 474 | 475 | if (item.Element("Cells") != null && item.Element("Cells").Element("results") != null 476 | && item.Element("Cells").Element("results").HasElements) 477 | { 478 | var itemValues = from i in item.Element("Cells").Element("results").Elements("item") 479 | orderby i.Element("Key").Value ascending 480 | select i; 481 | foreach (var itemValue in itemValues) 482 | { 483 | resultItem.Add(itemValue.Element("Key").Value, itemValue.Element("Value").Value); 484 | } 485 | } 486 | 487 | resultItems.Add(resultItem); 488 | } 489 | 490 | this.PrimaryQueryResult.RelevantResults = resultItems; 491 | } 492 | } 493 | } 494 | 495 | #endregion 496 | 497 | #region Refinement Results 498 | 499 | var refinementResults = primaryQueryResult.Element("RefinementResults"); 500 | if (refinementResults != null) 501 | { 502 | var refiners = refinementResults.Element("Refiners"); 503 | if (refiners != null && refiners.HasElements) 504 | { 505 | var results = refiners.Element("results"); 506 | if (results != null && results.HasElements) 507 | { 508 | List refinerResults = new List(); 509 | 510 | var items = results.Elements("item"); 511 | foreach (var item in items) 512 | { 513 | RefinerResult refinerResult = new RefinerResult(); 514 | refinerResult.Name = (string)item.Element("Name"); 515 | 516 | if (item.Element("Entries") != null && item.Element("Entries").Element("results") != null 517 | && item.Element("Entries").Element("results").HasElements) 518 | { 519 | var entries = item.Element("Entries").Element("results").Elements("item"); 520 | foreach (var entry in entries) 521 | { 522 | refinerResult.Add(new RefinementItem 523 | { 524 | Count = (long)entry.Element("RefinementCount"), 525 | Name = (string)entry.Element("RefinementName"), 526 | Token = (string)entry.Element("RefinementToken"), 527 | Value = (string)entry.Element("RefinementValue"), 528 | }); 529 | } 530 | } 531 | 532 | refinerResults.Add(refinerResult); 533 | } 534 | 535 | this.PrimaryQueryResult.RefinerResults = refinerResults; 536 | } 537 | } 538 | } 539 | 540 | #endregion 541 | } 542 | 543 | #endregion 544 | 545 | #region Secondary Query Results 546 | 547 | XElement secondaryQueryResults = queryElm.Element("SecondaryQueryResults"); 548 | if (secondaryQueryResults != null && secondaryQueryResults.Element("results") != null) 549 | { 550 | var resultsElm = secondaryQueryResults.Element("results"); 551 | 552 | if (resultsElm.HasElements) 553 | { 554 | this.SecondaryQueryResults = new List(); 555 | 556 | var resultItems = resultsElm.Elements("item"); 557 | foreach (var resultItem in resultItems) 558 | { 559 | QueryResult secondaryQueryResult = new QueryResult(); 560 | 561 | if (resultItem.Element("QueryId") != null) 562 | { 563 | secondaryQueryResult.QueryId = (string)resultItem.Element("QueryId"); 564 | 565 | // Checking for Best Bet (a.k.a Promoted type of SecondaryQueryResults 566 | if (String.Compare(secondaryQueryResult.QueryId, "BestBet Query") == 0) 567 | { 568 | if (resultItem.Element("SpecialTermResults") != null) 569 | { 570 | this.BestBetsTriggered = true; 571 | var specialTermResults = resultItem.Element("SpecialTermResults").Element("Results").Element("results"); 572 | this.BestBetsCount = specialTermResults.Elements("item").Count(); 573 | } 574 | else 575 | { 576 | this.BestBetsTriggered = false; 577 | } 578 | } 579 | } 580 | 581 | if (resultItem.Element("QueryRuleId") != null) 582 | { 583 | secondaryQueryResult.QueryRuleId = (string)resultItem.Element("QueryRuleId"); 584 | } 585 | 586 | var relevantResults = resultItem.Element("RelevantResults"); 587 | if (relevantResults != null) 588 | { 589 | if (relevantResults.Element("ResultTitle") != null) 590 | { 591 | secondaryQueryResult.ResultTitle = (string)relevantResults.Element("ResultTitle"); 592 | } 593 | 594 | if (relevantResults.Element("ResultTitleUrl") != null) 595 | { 596 | secondaryQueryResult.ResultTitleUrl = (string)relevantResults.Element("ResultTitleUrl"); 597 | } 598 | 599 | if (relevantResults.Element("TotalRows") != null) 600 | { 601 | secondaryQueryResult.TotalRows = (int)relevantResults.Element("TotalRows"); 602 | } 603 | 604 | if (relevantResults.Element("TotalRowsIncludingDuplicates") != null) 605 | { 606 | secondaryQueryResult.TotalRowsIncludingDuplicates = (int)relevantResults.Element("TotalRowsIncludingDuplicates"); 607 | } 608 | 609 | XElement queryMod = relevantResults.Descendants("Key").FirstOrDefault(e => e.Value == "QueryModification"); 610 | if (queryMod != null) 611 | { 612 | secondaryQueryResult.QueryModification = queryMod.XPathSelectElement("..").Element("Value").Value; 613 | } 614 | 615 | var table = relevantResults.Element("Table"); 616 | if (table != null && table.HasElements) 617 | { 618 | var rows = table.Element("Rows"); 619 | if (rows != null && rows.Element("results") != null && rows.Element("results").HasElements) 620 | { 621 | List resultRows = new List(); 622 | 623 | var items = rows.Element("results").Elements("item"); 624 | foreach (var item in items) 625 | { 626 | ResultItem resultRow = new ResultItem(); 627 | 628 | if (item.Element("Cells") != null && item.Element("Cells").Element("results") != null 629 | && item.Element("Cells").Element("results").HasElements) 630 | { 631 | var itemValues = item.Element("Cells").Element("results").Elements("item"); 632 | foreach (var itemValue in itemValues) 633 | { 634 | resultRow.Add(itemValue.Element("Key").Value, itemValue.Element("Value").Value); 635 | } 636 | } 637 | 638 | resultRows.Add(resultRow); 639 | } 640 | 641 | secondaryQueryResult.RelevantResults = resultRows; 642 | } 643 | } 644 | } 645 | 646 | if (this.BestBetsCount > 0) 647 | { 648 | List promotedRows = new List(); 649 | 650 | var specialTermResults = resultItem?.Element("SpecialTermResults")?.Element("Results")?.Element("results"); 651 | if (specialTermResults != null) 652 | { 653 | var specialTermItems = specialTermResults.Elements("item"); 654 | 655 | foreach (var item in specialTermItems) 656 | { 657 | PromotedItem promotedRow = new PromotedItem(); 658 | promotedRow.Title = (string)item.Element("Title"); 659 | promotedRow.Url = (string)item.Element("Url"); 660 | promotedRow.Description = (string)item.Element("Description"); 661 | promotedRow.isVisualBestBet = (string)item.Element("IsVisualBestBet"); 662 | promotedRow.PiSearchResultId = (string)item.Element("PiSearchResultId"); 663 | promotedRow.renderTemplateId = (string)item.Element("RenderTemplateId"); 664 | promotedRows.Add(promotedRow); 665 | } 666 | secondaryQueryResult.PromotedResults = promotedRows; 667 | } 668 | } 669 | this.SecondaryQueryResults.Add(secondaryQueryResult); 670 | } 671 | } 672 | } 673 | #endregion 674 | } 675 | } 676 | 677 | private void ProcessJsonFromPostRequest() 678 | { 679 | XmlReader reader = 680 | JsonReaderWriterFactory 681 | .CreateJsonReader(Encoding.UTF8.GetBytes(this.ResponseContent), new XmlDictionaryReaderQuotas()); 682 | 683 | XElement root = XElement.Load(reader); 684 | XElement postqueryElm = root.XPathSelectElement("//postquery"); 685 | 686 | if (postqueryElm != null) 687 | { 688 | XElement elapsedTimeElm = postqueryElm.Element("ElapsedTime"); 689 | if (elapsedTimeElm != null) 690 | { 691 | this.QueryElapsedTime = elapsedTimeElm.Value; 692 | } 693 | 694 | XElement propertiesElm = postqueryElm.Element("Properties"); 695 | if (propertiesElm != null && propertiesElm.HasElements) 696 | { 697 | if (propertiesElm.Element("results") != null) 698 | { 699 | foreach (var item in propertiesElm.Element("results").Elements("item")) 700 | { 701 | if (item != null && item.Element("Key") != null) 702 | { 703 | if (item.Element("Key").Value == "SerializedQuery") 704 | { 705 | this.SerializedQuery = item.Element("Value").Value; 706 | } 707 | else if (item.Element("Key").Value == "IsPartial") 708 | { 709 | if (bool.TryParse(item.Element("Value").Value, out bool isPartial)) 710 | { 711 | this.IsPartial = isPartial; 712 | } 713 | } 714 | else if (item.Element("Key").Value == "MultiGeoSearchStatus") 715 | { 716 | this.MultiGeoSearchStatus = item.Element("Value").Value; 717 | } 718 | } 719 | } 720 | } 721 | } 722 | 723 | #region Triggered Rules 724 | 725 | XElement triggeredRulesElm = postqueryElm.Element("TriggeredRules"); 726 | if (triggeredRulesElm != null && triggeredRulesElm.HasElements) 727 | { 728 | if (triggeredRulesElm.Element("results") != null) 729 | { 730 | this.TriggeredRules = new List(); 731 | 732 | foreach (var item in triggeredRulesElm.Element("results").Elements("item")) 733 | { 734 | this.TriggeredRules.Add(item.Value); 735 | } 736 | } 737 | } 738 | 739 | #endregion 740 | 741 | #region Primary Query Results 742 | 743 | XElement primaryQueryResult = postqueryElm.Element("PrimaryQueryResult"); 744 | if (primaryQueryResult != null) 745 | { 746 | this.PrimaryQueryResult = new QueryResult(); 747 | 748 | if (primaryQueryResult.Element("QueryId") != null) 749 | { 750 | this.PrimaryQueryResult.QueryId = (string)primaryQueryResult.Element("QueryId"); 751 | } 752 | 753 | if (primaryQueryResult.Element("QueryRuleId") != null) 754 | { 755 | this.PrimaryQueryResult.QueryRuleId = (string)primaryQueryResult.Element("QueryRuleId"); 756 | } 757 | 758 | #region Relevant Results 759 | 760 | var relevantResults = primaryQueryResult.Element("RelevantResults"); 761 | if (relevantResults != null) 762 | { 763 | if (relevantResults.Element("TotalRows") != null) 764 | { 765 | this.PrimaryQueryResult.TotalRows = (int)relevantResults.Element("TotalRows"); 766 | } 767 | 768 | if (relevantResults.Element("TotalRowsIncludingDuplicates") != null) 769 | { 770 | this.PrimaryQueryResult.TotalRowsIncludingDuplicates = (int)relevantResults.Element("TotalRowsIncludingDuplicates"); 771 | } 772 | 773 | XElement queryMod = relevantResults.Descendants("Key").FirstOrDefault(e => e.Value == "QueryModification"); 774 | if (queryMod != null) 775 | { 776 | this.PrimaryQueryResult.QueryModification = queryMod.XPathSelectElement("..").Element("Value").Value; 777 | } 778 | 779 | var table = relevantResults.Element("Table"); 780 | if (table != null && table.HasElements) 781 | { 782 | var rows = table.Element("Rows"); 783 | if (rows != null && rows.Element("results") != null && rows.Element("results").HasElements) 784 | { 785 | List resultItems = new List(); 786 | 787 | var items = rows.Element("results").Elements("item"); 788 | foreach (var item in items) 789 | { 790 | ResultItem resultItem = new ResultItem(); 791 | 792 | if (item.Element("Cells") != null && item.Element("Cells").Element("results") != null 793 | && item.Element("Cells").Element("results").HasElements) 794 | { 795 | var itemValues = item.Element("Cells").Element("results").Elements("item"); 796 | foreach (var itemValue in itemValues) 797 | { 798 | resultItem.Add(itemValue.Element("Key").Value, itemValue.Element("Value").Value); 799 | } 800 | } 801 | 802 | resultItems.Add(resultItem); 803 | } 804 | 805 | this.PrimaryQueryResult.RelevantResults = resultItems; 806 | } 807 | } 808 | } 809 | 810 | #endregion 811 | 812 | #region Refinement Results 813 | 814 | var refinementResults = primaryQueryResult.Element("RefinementResults"); 815 | if (refinementResults != null) 816 | { 817 | var refiners = refinementResults.Element("Refiners"); 818 | if (refiners != null && refiners.HasElements) 819 | { 820 | var results = refiners.Element("results"); 821 | if (results != null && results.HasElements) 822 | { 823 | List refinerResults = new List(); 824 | 825 | var items = results.Elements("item"); 826 | foreach (var item in items) 827 | { 828 | RefinerResult refinerResult = new RefinerResult(); 829 | refinerResult.Name = (string)item.Element("Name"); 830 | 831 | if (item.Element("Entries") != null && item.Element("Entries").Element("results") != null 832 | && item.Element("Entries").Element("results").HasElements) 833 | { 834 | var entries = item.Element("Entries").Element("results").Elements("item"); 835 | foreach (var entry in entries) 836 | { 837 | refinerResult.Add(new RefinementItem 838 | { 839 | Count = (long)entry.Element("RefinementCount"), 840 | Name = (string)entry.Element("RefinementName"), 841 | Token = (string)entry.Element("RefinementToken"), 842 | Value = (string)entry.Element("RefinementValue"), 843 | }); 844 | } 845 | } 846 | 847 | refinerResults.Add(refinerResult); 848 | } 849 | 850 | this.PrimaryQueryResult.RefinerResults = refinerResults; 851 | } 852 | } 853 | } 854 | 855 | #endregion 856 | } 857 | 858 | #endregion 859 | 860 | #region Secondary Query Results 861 | 862 | XElement secondaryQueryResults = postqueryElm.Element("SecondaryQueryResults"); 863 | if (secondaryQueryResults != null && secondaryQueryResults.Element("results") != null) 864 | { 865 | var resultsElm = secondaryQueryResults.Element("results"); 866 | 867 | if (resultsElm.HasElements) 868 | { 869 | this.SecondaryQueryResults = new List(); 870 | 871 | var resultItems = resultsElm.Elements("item"); 872 | foreach (var resultItem in resultItems) 873 | { 874 | QueryResult secondaryQueryResult = new QueryResult(); 875 | 876 | if (resultItem.Element("QueryId") != null) 877 | { 878 | secondaryQueryResult.QueryId = (string)resultItem.Element("QueryId"); 879 | } 880 | 881 | if (resultItem.Element("QueryRuleId") != null) 882 | { 883 | secondaryQueryResult.QueryRuleId = (string)resultItem.Element("QueryRuleId"); 884 | } 885 | 886 | var relevantResults = resultItem.Element("RelevantResults"); 887 | if (relevantResults != null) 888 | { 889 | if (relevantResults.Element("TotalRows") != null) 890 | { 891 | secondaryQueryResult.TotalRows = (int)relevantResults.Element("TotalRows"); 892 | } 893 | 894 | if (relevantResults.Element("TotalRowsIncludingDuplicates") != null) 895 | { 896 | secondaryQueryResult.TotalRowsIncludingDuplicates = (int)relevantResults.Element("TotalRowsIncludingDuplicates"); 897 | } 898 | 899 | XElement queryMod = relevantResults.Descendants("Key").FirstOrDefault(e => e.Value == "QueryModification"); 900 | if (queryMod != null) 901 | { 902 | secondaryQueryResult.QueryModification = queryMod.XPathSelectElement("..").Element("Value").Value; 903 | } 904 | 905 | var table = relevantResults.Element("Table"); 906 | if (table != null && table.HasElements) 907 | { 908 | var rows = table.Element("Rows"); 909 | if (rows != null && rows.Element("results") != null && rows.Element("results").HasElements) 910 | { 911 | List resultRows = new List(); 912 | 913 | var items = rows.Element("results").Elements("item"); 914 | foreach (var item in items) 915 | { 916 | ResultItem resultRow = new ResultItem(); 917 | 918 | if (item.Element("Cells") != null && item.Element("Cells").Element("results") != null 919 | && item.Element("Cells").Element("results").HasElements) 920 | { 921 | var itemValues = item.Element("Cells").Element("results").Elements("item"); 922 | foreach (var itemValue in itemValues) 923 | { 924 | resultRow.Add(itemValue.Element("Key").Value, itemValue.Element("Value").Value); 925 | } 926 | } 927 | 928 | resultRows.Add(resultRow); 929 | } 930 | 931 | secondaryQueryResult.RelevantResults = resultRows; 932 | } 933 | } 934 | } 935 | 936 | this.SecondaryQueryResults.Add(secondaryQueryResult); 937 | } 938 | } 939 | } 940 | 941 | #endregion 942 | } 943 | } 944 | } 945 | } 946 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchRequest.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Security; 3 | using System.Web; 4 | using System.Xml.Serialization; 5 | 6 | namespace SearchQueryTool.Model 7 | { 8 | public enum HttpMethodType 9 | { 10 | Get, 11 | Post 12 | } 13 | 14 | public enum AcceptType 15 | { 16 | Json, 17 | Xml 18 | } 19 | 20 | public enum AuthenticationType 21 | { 22 | CurrentUser, 23 | Windows, 24 | Forms, 25 | SPO, 26 | SPOManagement, 27 | Anonymous 28 | } 29 | 30 | public abstract class SearchRequest 31 | { 32 | public const int DefaultTimeout = 30; // 30 seconds timout 33 | 34 | public string SharePointSiteUrl { get; set; } 35 | public string QueryText { get; set; } 36 | public int? Timeout { get; set; } 37 | 38 | public HttpMethodType HttpMethodType { get; set; } 39 | public AcceptType AcceptType { get; set; } 40 | public AuthenticationType AuthenticationType { get; set; } 41 | public string UserName { get; set; } 42 | public string Password { get; set; } 43 | public SecureString SecurePassword { get; set; } 44 | [XmlIgnore] 45 | public CookieCollection Cookies { get; set; } 46 | 47 | public string Token { get; set; } 48 | 49 | public abstract string GenerateHttpGetUri(); 50 | public abstract string GenerateHttpPostUri(); 51 | public abstract string GenerateHttpPostBodyPayload(); 52 | 53 | public override string ToString() 54 | { 55 | return GenerateHttpGetUri().ToString(); 56 | } 57 | 58 | protected static string UrlEncode(string str) 59 | { 60 | return HttpUtility.UrlEncode(str); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Specialized; 3 | using System.Net; 4 | 5 | namespace SearchQueryTool.Model 6 | { 7 | public abstract class SearchResult 8 | { 9 | public HttpStatusCode StatusCode { get; set; } 10 | public string StatusDescription { get; set; } 11 | public string HttpProtocolVersion { get; set; } 12 | public string ContentType { get; set; } 13 | public TimeSpan ElapsedTime { get; set; } 14 | public long ElapsedMilliseconds { get; set; } 15 | public NameValueCollection ResponseHeaders { get; set; } 16 | public NameValueCollection RequestHeaders { get; set; } 17 | public string ResponseContent { get; set; } 18 | public Uri RequestUri { get; set; } 19 | public string RequestMethod { get; set; } 20 | public string RequestContent { get; set; } 21 | 22 | public abstract void Process(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchResultPresentationSettings.cs: -------------------------------------------------------------------------------- 1 | namespace SearchQueryTool.Model 2 | { 3 | public class SearchResultPresentationSettings 4 | { 5 | public const string DefaultFormat = "{counter}. {Title}"; 6 | 7 | public string PrimaryResultsTitleFormat { get; set; } = DefaultFormat; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchSuggestionsRequest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | namespace SearchQueryTool.Model 5 | { 6 | public class SearchSuggestionsRequest: SearchRequest 7 | { 8 | public bool? PreQuerySuggestions { get; set; } 9 | public bool? ShowPeopleNameSuggestions { get; set; } 10 | public int? NumberOfQuerySuggestions { get; set; } 11 | public int? NumberOfResultSuggestions { get; set; } 12 | public bool? HitHighlighting { get; set; } 13 | public bool? CapitalizeFirstLetters { get; set; } 14 | public int? Culture { get; set; } 15 | 16 | public override string GenerateHttpGetUri() 17 | { 18 | string restUri = this.SharePointSiteUrl; 19 | 20 | StringBuilder uriBuilder = new StringBuilder(); 21 | 22 | if (!String.IsNullOrWhiteSpace(restUri)) 23 | { 24 | uriBuilder.Append(restUri); 25 | 26 | if (!restUri.EndsWith("/")) 27 | uriBuilder.Append("/"); 28 | } 29 | 30 | uriBuilder.AppendFormat("_api/search/suggest?querytext='{0}'", this.QueryText); 31 | 32 | if (this.PreQuerySuggestions == true) 33 | uriBuilder.Append("&fprequerysuggestions=true"); 34 | else if (this.PreQuerySuggestions == false) 35 | uriBuilder.Append("&fprequerysuggestions=false"); 36 | 37 | if (this.ShowPeopleNameSuggestions == true) 38 | uriBuilder.Append("&showpeoplenamesuggestions=true"); 39 | else if (this.ShowPeopleNameSuggestions == false) 40 | uriBuilder.Append("&showpeoplenamesuggestions=false"); 41 | 42 | if (this.HitHighlighting == true) 43 | uriBuilder.Append("&fhithighlighting=true"); 44 | else if (this.HitHighlighting == false) 45 | uriBuilder.Append("&fhithighlighting=false"); 46 | 47 | if (this.CapitalizeFirstLetters == true) 48 | uriBuilder.Append("&fcapitalizefirstletters=true"); 49 | else if (this.CapitalizeFirstLetters == false) 50 | uriBuilder.Append("&fcapitalizefirstletters=false"); 51 | 52 | if (this.NumberOfQuerySuggestions.HasValue) 53 | uriBuilder.AppendFormat("&inumberofquerysuggestions={0}", this.NumberOfQuerySuggestions.Value); 54 | 55 | if (this.NumberOfResultSuggestions.HasValue) 56 | uriBuilder.AppendFormat("&inumberofresultsuggestions={0}", this.NumberOfResultSuggestions.Value); 57 | 58 | if (this.Culture.HasValue) 59 | uriBuilder.AppendFormat("&culture={0}", this.Culture.Value); 60 | 61 | return uriBuilder.ToString(); 62 | } 63 | 64 | public override string GenerateHttpPostUri() 65 | { 66 | throw new NotImplementedException(); 67 | } 68 | 69 | public override string GenerateHttpPostBodyPayload() 70 | { 71 | throw new NotImplementedException(); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/Model/SearchSuggestionsResult.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Runtime.Serialization.Json; 3 | using System.Text; 4 | using System.Xml; 5 | using System.Xml.Linq; 6 | using System.Xml.XPath; 7 | 8 | namespace SearchQueryTool.Model 9 | { 10 | /// 11 | /// Represents search suggestions results. 12 | /// 13 | public class SearchSuggestionsResult : SearchResult 14 | { 15 | public SearchSuggestionsResult() 16 | :base() 17 | { 18 | } 19 | 20 | public List SuggestionResults { get; private set; } 21 | 22 | /// 23 | /// Fireoff processing of the search result content. 24 | /// 25 | public override void Process() 26 | { 27 | if (this.ContentType.StartsWith("application/json")) 28 | { 29 | ProcessJson(); 30 | } 31 | else if (this.ContentType.StartsWith("application/xml")) 32 | { 33 | ProcessXml(); 34 | } 35 | } 36 | 37 | private void ProcessXml() 38 | { 39 | XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices"; 40 | 41 | var root = XElement.Parse(this.ResponseContent); 42 | 43 | if (root != null && root.HasElements) 44 | { 45 | XElement queriesElm = root.Element(d + "Queries"); 46 | if (queriesElm != null && queriesElm.HasElements) 47 | { 48 | List resultItems = new List(); 49 | 50 | foreach (var item in queriesElm.Elements(d + "element")) 51 | { 52 | if (item != null && item.Element(d + "Query") != null) 53 | { 54 | var query = item.Element(d + "Query").Value; 55 | var isPersonal = (bool)item.Element(d + "IsPersonal"); 56 | 57 | resultItems.Add(new SuggestionResulItem { Query = query, IsPersonal = isPersonal }); 58 | } 59 | } 60 | 61 | this.SuggestionResults = resultItems; 62 | } 63 | } 64 | } 65 | 66 | private void ProcessJson() 67 | { 68 | XmlReader reader = 69 | JsonReaderWriterFactory 70 | .CreateJsonReader(Encoding.UTF8.GetBytes(this.ResponseContent), new XmlDictionaryReaderQuotas()); 71 | 72 | XElement root = XElement.Load(reader); 73 | XElement suggestElm = root.XPathSelectElement("//suggest"); 74 | 75 | if (suggestElm != null) 76 | { 77 | XElement queriesElm = suggestElm.Element("Queries"); 78 | if (queriesElm != null) 79 | { 80 | if (queriesElm.Element("results") != null) 81 | { 82 | List resultItems = new List(); 83 | 84 | foreach (var item in queriesElm.Element("results").Elements("item")) 85 | { 86 | if (item != null && item.Element("Query") != null) 87 | { 88 | var query = item.Element("Query").Value; 89 | var isPersonal = (bool)item.Element("IsPersonal"); 90 | 91 | resultItems.Add(new SuggestionResulItem { Query = query, IsPersonal = isPersonal }); 92 | } 93 | } 94 | 95 | this.SuggestionResults = resultItems; 96 | 97 | } 98 | } 99 | } 100 | } 101 | } 102 | 103 | public class SuggestionResulItem 104 | { 105 | public string Query { get; set; } 106 | public bool IsPersonal { get; set; } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /SnaffPoint/SearchQueryTool/SPAuthenticationClient/AuthenticationClient.cs: -------------------------------------------------------------------------------- 1 | namespace SearchQueryTool.SPAuthenticationClient 2 | { 3 | [System.Diagnostics.DebuggerStepThroughAttribute()] 4 | [System.Runtime.Serialization.DataContractAttribute(Name = "LoginResult", Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] 5 | [System.SerializableAttribute()] 6 | public partial class LoginResult : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged 7 | { 8 | [System.NonSerializedAttribute()] 9 | private System.Runtime.Serialization.ExtensionDataObject extensionDataField; 10 | 11 | [System.Runtime.Serialization.OptionalFieldAttribute()] 12 | private string CookieNameField; 13 | 14 | private LoginErrorCode ErrorCodeField; 15 | 16 | private int TimeoutSecondsField; 17 | 18 | [global::System.ComponentModel.BrowsableAttribute(false)] 19 | public System.Runtime.Serialization.ExtensionDataObject ExtensionData 20 | { 21 | get 22 | { 23 | return this.extensionDataField; 24 | } 25 | set 26 | { 27 | this.extensionDataField = value; 28 | } 29 | } 30 | 31 | [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false)] 32 | public string CookieName 33 | { 34 | get 35 | { 36 | return this.CookieNameField; 37 | } 38 | set 39 | { 40 | if ((object.ReferenceEquals(this.CookieNameField, value) != true)) 41 | { 42 | this.CookieNameField = value; 43 | this.RaisePropertyChanged("CookieName"); 44 | } 45 | } 46 | } 47 | 48 | [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true)] 49 | public LoginErrorCode ErrorCode 50 | { 51 | get 52 | { 53 | return this.ErrorCodeField; 54 | } 55 | set 56 | { 57 | if ((this.ErrorCodeField.Equals(value) != true)) 58 | { 59 | this.ErrorCodeField = value; 60 | this.RaisePropertyChanged("ErrorCode"); 61 | } 62 | } 63 | } 64 | 65 | [System.Runtime.Serialization.DataMemberAttribute(IsRequired = true)] 66 | public int TimeoutSeconds 67 | { 68 | get 69 | { 70 | return this.TimeoutSecondsField; 71 | } 72 | set 73 | { 74 | if ((this.TimeoutSecondsField.Equals(value) != true)) 75 | { 76 | this.TimeoutSecondsField = value; 77 | this.RaisePropertyChanged("TimeoutSeconds"); 78 | } 79 | } 80 | } 81 | 82 | public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 83 | 84 | protected void RaisePropertyChanged(string propertyName) 85 | { 86 | System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; 87 | if ((propertyChanged != null)) 88 | { 89 | propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); 90 | } 91 | } 92 | } 93 | 94 | [System.Runtime.Serialization.DataContractAttribute(Name = "LoginErrorCode", Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] 95 | public enum LoginErrorCode : int 96 | { 97 | 98 | [System.Runtime.Serialization.EnumMemberAttribute()] 99 | NoError = 0, 100 | 101 | [System.Runtime.Serialization.EnumMemberAttribute()] 102 | NotInFormsAuthenticationMode = 1, 103 | 104 | [System.Runtime.Serialization.EnumMemberAttribute()] 105 | PasswordNotMatch = 2, 106 | } 107 | 108 | [System.Runtime.Serialization.DataContractAttribute(Name = "AuthenticationMode", Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] 109 | public enum AuthenticationMode : int 110 | { 111 | 112 | [System.Runtime.Serialization.EnumMemberAttribute()] 113 | None = 0, 114 | 115 | [System.Runtime.Serialization.EnumMemberAttribute()] 116 | Windows = 1, 117 | 118 | [System.Runtime.Serialization.EnumMemberAttribute()] 119 | Passport = 2, 120 | 121 | [System.Runtime.Serialization.EnumMemberAttribute()] 122 | Forms = 3, 123 | } 124 | 125 | [System.ServiceModel.ServiceContractAttribute(Namespace = "http://schemas.microsoft.com/sharepoint/soap/", ConfigurationName = "SPAuthenticationServiceReference.AuthenticationSoap")] 126 | public interface AuthenticationSoap 127 | { 128 | [System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/sharepoint/soap/Login", ReplyAction = "*")] 129 | LoginResponse Login(LoginRequest request); 130 | 131 | [System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/sharepoint/soap/Login", ReplyAction = "*")] 132 | System.Threading.Tasks.Task LoginAsync(LoginRequest request); 133 | 134 | [System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/sharepoint/soap/Mode", ReplyAction = "*")] 135 | AuthenticationMode Mode(); 136 | 137 | [System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/sharepoint/soap/Mode", ReplyAction = "*")] 138 | System.Threading.Tasks.Task ModeAsync(); 139 | } 140 | 141 | [System.Diagnostics.DebuggerStepThroughAttribute()] 142 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 143 | [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] 144 | public partial class LoginRequest 145 | { 146 | 147 | [System.ServiceModel.MessageBodyMemberAttribute(Name = "Login", Namespace = "http://schemas.microsoft.com/sharepoint/soap/", Order = 0)] 148 | public LoginRequestBody Body; 149 | 150 | public LoginRequest() 151 | { 152 | } 153 | 154 | public LoginRequest(LoginRequestBody Body) 155 | { 156 | this.Body = Body; 157 | } 158 | } 159 | 160 | [System.Diagnostics.DebuggerStepThroughAttribute()] 161 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 162 | [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] 163 | public partial class LoginRequestBody 164 | { 165 | 166 | [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] 167 | public string username; 168 | 169 | [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 1)] 170 | public string password; 171 | 172 | public LoginRequestBody() 173 | { 174 | } 175 | 176 | public LoginRequestBody(string username, string password) 177 | { 178 | this.username = username; 179 | this.password = password; 180 | } 181 | } 182 | 183 | [System.Diagnostics.DebuggerStepThroughAttribute()] 184 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 185 | [System.ServiceModel.MessageContractAttribute(IsWrapped = false)] 186 | public partial class LoginResponse 187 | { 188 | 189 | [System.ServiceModel.MessageBodyMemberAttribute(Name = "LoginResponse", Namespace = "http://schemas.microsoft.com/sharepoint/soap/", Order = 0)] 190 | public LoginResponseBody Body; 191 | 192 | public LoginResponse() 193 | { 194 | } 195 | 196 | public LoginResponse(LoginResponseBody Body) 197 | { 198 | this.Body = Body; 199 | } 200 | } 201 | 202 | [System.Diagnostics.DebuggerStepThroughAttribute()] 203 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 204 | [System.Runtime.Serialization.DataContractAttribute(Namespace = "http://schemas.microsoft.com/sharepoint/soap/")] 205 | public partial class LoginResponseBody 206 | { 207 | 208 | [System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue = false, Order = 0)] 209 | public LoginResult LoginResult; 210 | 211 | public LoginResponseBody() 212 | { 213 | } 214 | 215 | public LoginResponseBody(LoginResult LoginResult) 216 | { 217 | this.LoginResult = LoginResult; 218 | } 219 | } 220 | 221 | public interface AuthenticationSoapChannel : AuthenticationSoap, System.ServiceModel.IClientChannel 222 | { 223 | } 224 | 225 | public partial class AuthenticationSoapClient : System.ServiceModel.ClientBase, AuthenticationSoap 226 | { 227 | 228 | public AuthenticationSoapClient() 229 | { 230 | } 231 | 232 | public AuthenticationSoapClient(string endpointConfigurationName) : 233 | base(endpointConfigurationName) 234 | { 235 | } 236 | 237 | public AuthenticationSoapClient(string endpointConfigurationName, string remoteAddress) : 238 | base(endpointConfigurationName, remoteAddress) 239 | { 240 | } 241 | 242 | public AuthenticationSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 243 | base(endpointConfigurationName, remoteAddress) 244 | { 245 | } 246 | 247 | public AuthenticationSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 248 | base(binding, remoteAddress) 249 | { 250 | } 251 | 252 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 253 | LoginResponse AuthenticationSoap.Login(LoginRequest request) 254 | { 255 | return base.Channel.Login(request); 256 | } 257 | 258 | public LoginResult Login(string username, string password) 259 | { 260 | LoginRequest inValue = new LoginRequest(); 261 | inValue.Body = new LoginRequestBody(); 262 | inValue.Body.username = username; 263 | inValue.Body.password = password; 264 | LoginResponse retVal = ((AuthenticationSoap)(this)).Login(inValue); 265 | return retVal.Body.LoginResult; 266 | } 267 | 268 | [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] 269 | System.Threading.Tasks.Task AuthenticationSoap.LoginAsync(LoginRequest request) 270 | { 271 | return base.Channel.LoginAsync(request); 272 | } 273 | 274 | public System.Threading.Tasks.Task LoginAsync(string username, string password) 275 | { 276 | LoginRequest inValue = new LoginRequest(); 277 | inValue.Body = new LoginRequestBody(); 278 | inValue.Body.username = username; 279 | inValue.Body.password = password; 280 | return ((AuthenticationSoap)(this)).LoginAsync(inValue); 281 | } 282 | 283 | public AuthenticationMode Mode() 284 | { 285 | return base.Channel.Mode(); 286 | } 287 | 288 | public System.Threading.Tasks.Task ModeAsync() 289 | { 290 | return base.Channel.ModeAsync(); 291 | } 292 | } 293 | } 294 | -------------------------------------------------------------------------------- /SnaffPoint/SnaffPoint.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {879A49C7-0493-4235-85F6-EBF962613A76} 8 | Exe 9 | SnaffPoint 10 | SnaffPoint 11 | v4.7.2 12 | 512 13 | true 14 | true 15 | 16 | 17 | AnyCPU 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /SnaffPoint/presets/AWSCFKeysInCode.xml: -------------------------------------------------------------------------------- 1 | 2 | AWSKeysInCode 3 | 4 | OR(NEAR(OR("X-Amz-Credential", "aws_key", "awskey", "aws.key", "aws-key", "*aws*"), OR("AKIA*", "AGPA*", "AIPA*", "AROA*", "ANPA*", "ANVA*", "ASIA*"), n=10), "CF-Access-Client-Secret") 5 | true 6 | filetype:or("yaml","yml","toml","xml","json","config","ini","inf","cnf","conf","properties","env","dist","txt","sql","log","sqlite","sqlite3","fdb","tfvars","js","cjs","mjs","hpp","cpp","cs","ts","tsx","ls","es6","es","php","phtml","inc","php3","php5","php7","ps1","psd1","psm1","py","rb","netrc","exports","functions","extra","npmrc","env","bashrc","profile","zshrc","bash_history","zsh_history","sh_history","zhistory","irb_history") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | 10 | -------------------------------------------------------------------------------- /SnaffPoint/presets/CSharpDbConnStrings.xml: -------------------------------------------------------------------------------- 1 | 2 | CSharpDbConnStrings 3 | 4 | NEAR("data source", "password", n=30) 5 | true 6 | filetype:or("aspx","ashx","asmx","asp","cshtml","cs","ascx","config") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/CSharpViewstateKeys.xml: -------------------------------------------------------------------------------- 1 | 2 | CSharpViewstateKeys 3 | 4 | *validationkey* OR *decryptionkey* 5 | filetype:or("aspx","ashx","asmx","asp","cshtml","cs","ascx","config") 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/CmdCredentials.xml: -------------------------------------------------------------------------------- 1 | 2 | cmdCredentials 3 | 4 | OR(NEAR("schtasks", "p", n=10),NEAR("schtasks", "rp", n=10), NEAR("psexec*", "-p", n=10), "passw*", "net user ", "cmdkey ", NEAR("net use ", "/user:", n=10)) 5 | true 6 | filetype:or("bat","cmd","ps1","psd1","psm1") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/ConfigPasswordsVeryNoisy.xml: -------------------------------------------------------------------------------- 1 | 2 | ConfigPasswordsVeryNoisy 3 | 4 | NEAR(OR("user","username","login"), OR("password","pass","passw","passwd","secret","key","credential"), n=4) 5 | true 6 | filetype:or("yaml","yml","toml","xml","json","config","ini","inf","cnf","conf","properties","env","dist","txt","sql","log","sqlite","sqlite3","fdb","tfvars","ps1","psd1","psm1","py","rb","netrc","exports","functions","extra","npmrc","env","bashrc","profile","zshrc","bash_history","zsh_history","sh_history","zhistory","irb_history","ovpn") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | 10 | -------------------------------------------------------------------------------- /SnaffPoint/presets/CyberArkCredFile.xml: -------------------------------------------------------------------------------- 1 | 2 | CyberArkCredFile 3 | 4 | true 5 | filetype:equals("cred") 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/DatabaseByExtension.xml: -------------------------------------------------------------------------------- 1 | 2 | DatabaseByExtension 3 | 4 | * 5 | true 6 | filetype:or("mdf","sdf","sqldump") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/DbConnStringPw.xml: -------------------------------------------------------------------------------- 1 | 2 | DbConnStringPw 3 | 4 | NEAR("connectionstring*", "passw*", n=30) 5 | true 6 | filetype:or("yaml","yml","toml","xml","json","config","ini","inf","cnf","conf","properties","env","dist","txt","sql","log","sqlite","sqlite3","fdb","tfvars","js","cjs","mjs","cs","ts","tsx","ls","es6","es","php","phtml","inc","php3","php5","php7","ps1","psd1","psm1","py","rb") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/DbMgtConfigByName.xml: -------------------------------------------------------------------------------- 1 | 2 | DbMgtConfigByName 3 | 4 | filename:OR("SqlStudio.bin",".mysql_history",".psql_history",".pgpass",".dbeaver-data-sources.xml","credentials-config.json","dbvis.xml","robomongo.json") 5 | true 6 | LastModifiedTime:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/DeployImageByExtension.xml: -------------------------------------------------------------------------------- 1 | 2 | DeployImageByExtension 3 | 4 | * 5 | true 6 | filetype:or("wim","ova","ovf") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | 10 | -------------------------------------------------------------------------------- /SnaffPoint/presets/DomainJoinCredsByPath.xml: -------------------------------------------------------------------------------- 1 | 2 | DomainJoinCredsByPath 3 | 4 | filename:customsettings.ini 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/FirefoxLoginsJson.xml: -------------------------------------------------------------------------------- 1 | 2 | FirefoxLoginsJson 3 | 4 | filename:logins.json 5 | LastModifiedTime:descending,Rank:descending 6 | 7 | -------------------------------------------------------------------------------- /SnaffPoint/presets/FtpClientConfigConfigByName.xml: -------------------------------------------------------------------------------- 1 | 2 | FtpClientConfigConfigByName 3 | 4 | filename:OR("recentservers.xml","sftp-config.json") 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/FtpServerConfigByName.xml: -------------------------------------------------------------------------------- 1 | 2 | FtpServerConfigByName 3 | 4 | OR(filename:proftpdpasswd,filename:filezilla.xml) 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/GitCredsByName.xml: -------------------------------------------------------------------------------- 1 | 2 | GitCredsByName 3 | 4 | filename:OR(".git-credentials") 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/InfraAsCodeConfigByExtension.xml: -------------------------------------------------------------------------------- 1 | 2 | InfraAsCodeConfigByExtension 3 | 4 | * 5 | true 6 | filetype:or("cscfg","tfvars") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/InlinePrivateKey.xml: -------------------------------------------------------------------------------- 1 | 2 | InlinePrivateKey 3 | 4 | NEAR(BEGIN, OR(RSA, OPENSSH, DSA, EC, PGP), PRIVATE, KEY, n=1) 5 | true 6 | filetype:or("yaml","yml","toml","xml","json","config","ini","inf","cnf","conf","properties","env","dist","txt","sql","log","sqlite","sqlite3","fdb","tfvars","js","cjs","mjs","cs","ts","tsx","ls","es6","es","php","phtml","inc","php3","php5","php7","ps1","psd1","psm1","py","rb","netrc","exports","functions","extra","npmrc","env","bashrc","profile","zshrc","bash_history","zsh_history","sh_history","zhistory","irb_history") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/JavaDbConnStrings.xml: -------------------------------------------------------------------------------- 1 | 2 | JavaDbConnStrings 3 | 4 | NEAR("getConnection*", "jdbc:", n=2) 5 | true 6 | filetype:or("jsp","do","java","cfm") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/JenkinsByName.xml: -------------------------------------------------------------------------------- 1 | 2 | JenkinsByName 3 | 4 | OR(filename:credentials.xml,filename:jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin.xml) 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/MemDumpByExtension.xml: -------------------------------------------------------------------------------- 1 | 2 | MemDumpByExtension 3 | 4 | * 5 | true 6 | filetype:equals("dmp") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/MemDumpByName.xml: -------------------------------------------------------------------------------- 1 | 2 | MemDumpByName 3 | 4 | filename:or(MEMORY.DMP,hiberfil.sys,lsass.dmp,lsass.exe.dmp) 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/NetConfigCreds.xml: -------------------------------------------------------------------------------- 1 | 2 | NetConfigCreds 3 | 4 | OR("NVRAM config last updated","simple-bind authenticated encrypt","pac key","snmp-server community") 5 | true 6 | not(filetype:or("bmp","eps","gif","ico","jfi","jfif","jif","jpe","jpeg","jpg","png","psd","svg","tif","tiff","webp","xcf","ttf","otf","lock","css","less")) 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/NetConfigFileByName.xml: -------------------------------------------------------------------------------- 1 | 2 | NetConfigFileByName 3 | 4 | filename:OR("running-config.cfg","startup-config.cfg","running-config","startup-config") 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/PHPDbConnStrings.xml: -------------------------------------------------------------------------------- 1 | 2 | PHPDbConnStrings 3 | 4 | OR(mysql_connect,mysql_pconnect,mysql_change_user,pg_connect,pg_pconnect) 5 | true 6 | filetype:or("php","phtml","inc","php3","php5","php7") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | 10 | -------------------------------------------------------------------------------- /SnaffPoint/presets/PassMgrsByExtension.xml: -------------------------------------------------------------------------------- 1 | 2 | PassMgrsByExtension 3 | 4 | * 5 | true 6 | filetype:or("kdbx","kdb","psafe3","kwallet","keychain","agilekeychain","cred") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/PcapByExtension.xml: -------------------------------------------------------------------------------- 1 | 2 | PcapByExtension 3 | 4 | * 5 | true 6 | filetype:or("pcap","pcapng","cap") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/PsCredentials.xml: -------------------------------------------------------------------------------- 1 | 2 | PsCredentials 3 | 4 | OR("-SecureString","-AsPlainText","Net.NetworkCredential") 5 | true 6 | filetype:or("ps1","psd1","psm1") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/PyDbConnStrings.xml: -------------------------------------------------------------------------------- 1 | 2 | PyDbConnStrings 3 | 4 | OR("mysql.connector.connect","psycopg2.connect") 5 | true 6 | filetype:or("py") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/RdpPasswords.xml: -------------------------------------------------------------------------------- 1 | 2 | RdpPasswords 3 | 4 | password 5 | filetype:equals("rdp") 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/RemoteAccessConfByExtension.xml: -------------------------------------------------------------------------------- 1 | 2 | RemoteAccessConfByExtension 3 | 4 | * 5 | true 6 | filetype:or("rdg","rtsz","rtsx","ovpn") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/RemoteAccessConfByName.xml: -------------------------------------------------------------------------------- 1 | 2 | RemoteAccessConfByName 3 | 4 | filename:OR("mobaxterm.ini","mobaxterm backup.zip","confCons.xml") 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/RubyConfigFiles.xml: -------------------------------------------------------------------------------- 1 | 2 | RubyConfigFiles 3 | 4 | OR("database.yml",".secret_token.rb","knife.rb","carrerwave.rb","omiauth.rb") 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/RubyDbConnStrings.xml: -------------------------------------------------------------------------------- 1 | 2 | RubyDbConnStrings 3 | 4 | "DBI.connect" 5 | true 6 | filetype:equals("rb") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/SSHKeysByFileName.xml: -------------------------------------------------------------------------------- 1 | 2 | SSHKeysByFileName 3 | 4 | filename:OR("id_rsa","id_dsa","id_ecdsa","id_ed25519") 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/ShellHistoryByName.xml: -------------------------------------------------------------------------------- 1 | 2 | ShellHistoryByName 3 | 4 | filename:OR(".bash_history",".zsh_history",".sh_history","zhistory",".irb_history","ConsoleHost_History.txt") 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | -------------------------------------------------------------------------------- /SnaffPoint/presets/SqlAccountCreation.xml: -------------------------------------------------------------------------------- 1 | 2 | SqlAccountCreation 3 | 4 | AND(NEAR("create", OR("user", "login"), n=1), OR("identified by", "with password")) 5 | true 6 | filetype:or("yaml","yml","toml","xml","json","config","ini","inf","cnf","conf","properties","env","dist","txt","sql","log","sqlite","sqlite3","fdb","tfvars","js","cjs","mjs","cs","ts","tsx","ls","es6","es","php","phtml","inc","php3","php5","php7","ps1","psd1","psm1","py","rb","netrc","exports","functions","extra","npmrc","env","bashrc","profile","zshrc","bash_history","zsh_history","sh_history","zhistory","irb_history") 7 | LastModifiedTime:descending,Rank:descending 8 | 9 | -------------------------------------------------------------------------------- /SnaffPoint/presets/UnattendXML.xml: -------------------------------------------------------------------------------- 1 | 2 | UnattendXML 3 | 4 | AND(NOT("*SENSITIVE*DATA*DELETED*"),OR(filename:Autounattend.xml,filename:unattend.xml)) 5 | true 6 | LastModifiedTime:descending,Rank:descending 7 | 8 | --------------------------------------------------------------------------------