├── .gitignore ├── LICENSE ├── README.md ├── images ├── predictive-autocomplete-configure.png └── predictive-autocomplete.png └── predictive-autocomplete ├── PredictiveAutocomplete.sln ├── PredictiveAutocomplete ├── Configuration │ └── Configuration.cs ├── CypherQueryCreator.cs ├── License.txt ├── PredictiveAutocomplete.csproj ├── Processor.cs ├── Properties │ └── AssemblyInfo.cs ├── Services │ └── BlobService.cs └── packages.config └── PredictiveAutocomplete_Test ├── App.config ├── PredictiveAutocomplete_Test.csproj ├── Program.cs ├── Properties └── AssemblyInfo.cs └── packages.config /.gitignore: -------------------------------------------------------------------------------- 1 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 2 | [Bb]in/ 3 | [Oo]bj/ 4 | 5 | # mstest test results 6 | TestResults 7 | 8 | ## Ignore Visual Studio temporary files, build results, and 9 | ## files generated by popular Visual Studio add-ons. 10 | 11 | # User-specific files 12 | *.suo 13 | *.user 14 | *.sln.docstates 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Rr]elease/ 19 | x64/ 20 | *_i.c 21 | *_p.c 22 | *.ilk 23 | *.meta 24 | *.obj 25 | *.pch 26 | *.pdb 27 | *.pgc 28 | *.pgd 29 | *.rsp 30 | *.sbr 31 | *.tlb 32 | *.tli 33 | *.tlh 34 | *.tmp 35 | *.log 36 | *.vspscc 37 | *.vssscc 38 | .builds 39 | 40 | # Visual C++ cache files 41 | ipch/ 42 | *.aps 43 | *.ncb 44 | *.opensdf 45 | *.sdf 46 | 47 | # Visual Studio profiler 48 | *.psess 49 | *.vsp 50 | *.vspx 51 | 52 | # Guidance Automation Toolkit 53 | *.gpState 54 | 55 | # ReSharper is a .NET coding add-in 56 | _ReSharper* 57 | 58 | # NCrunch 59 | *.ncrunch* 60 | .*crunch*.local.xml 61 | 62 | # Installshield output folder 63 | [Ee]xpress 64 | 65 | # DocProject is a documentation generator add-in 66 | DocProject/buildhelp/ 67 | DocProject/Help/*.HxT 68 | DocProject/Help/*.HxC 69 | DocProject/Help/*.hhc 70 | DocProject/Help/*.hhk 71 | DocProject/Help/*.hhp 72 | DocProject/Help/Html2 73 | DocProject/Help/html 74 | 75 | # Click-Once directory 76 | publish 77 | 78 | # Publish Web Output 79 | *.Publish.xml 80 | 81 | # NuGet Packages Directory 82 | packages 83 | 84 | # Windows Azure Build Output 85 | csx 86 | *.build.csdef 87 | 88 | # Windows Store app package directory 89 | AppPackages/ 90 | 91 | # Others 92 | [Bb]in 93 | [Oo]bj 94 | sql 95 | TestResults 96 | [Tt]est[Rr]esult* 97 | *.Cache 98 | ClientBin 99 | [Ss]tyle[Cc]op.* 100 | ~$* 101 | *.dbmdl 102 | Generated_Code #added for RIA/Silverlight projects 103 | 104 | # Backup & report files from converting an old project file to a newer 105 | # Visual Studio version. Backup files are not needed, because we have git ;-) 106 | _UpgradeReport_Files/ 107 | Backup*/ 108 | UpgradeLog*.XML 109 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. {http://fsf.org/} 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see {http://www.gnu.org/licenses/}. 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | predictive-autocomplete Copyright (C) 2013 Kenny Bastani 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | {http://www.gnu.org/licenses/}. 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | {http://www.gnu.org/philosophy/why-not-lgpl.html}. 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Predictive Autocomplete 2 | ======================= 3 | 4 | Generates a ranked predictive autocomplete index of JSON files accessible over HTTP for search engine text box query completion using Neo4j graph database and Windows Azure cloud storage account. 5 | 6 | 7 | 8 | Creates a hierachical JSON file index that is accessible over HTTP GET requests. Easily implemented into Bootstrap.js Type Ahead JQuery plugin. Use a Neo4j graph database for easy ranking and Windows Azure cloud storage account for JSON file storage. 9 | 10 | 11 | 12 | 13 | Configuration 14 | ======================= 15 | 16 | Open the PredictiveAutocomplete solution file in Microsoft Visual Studio 2012. 17 | 18 | Open the App.config file in the PredictiveAutocomplete_Test project. 19 | 20 | Configure the settings to point to your Neo4j instance. 21 | 22 | Configure the settings to point to your Windows Azure storage account. 23 | 24 | Configure the path to your public storage container that will be used to store the JSON files. 25 | 26 | 27 | 28 | Running test project from console 29 | ======================= 30 | 31 | Use the GetRankedNodesForQuery method to get ranked nodes from Neo4j graph database using a templated cypher query that queries an index using a supplied valid lucene query. 32 | 33 | Each node in the index has a weight rating by specifying a relationship name which is used to determine the 34 | distinct number of incoming links to each node in your query with that relationship name. 35 | 36 | You must specify the valid property name that is to be used as the label for the autocomplete search. 37 | 38 | For example, if you are querying a database of books and wanted to list the names of books in the 39 | autocomplete search, then the label property would be "Title" where each book node b has b.Title as the book name. 40 | 41 | Parameters in order: 42 | 43 | 1. The case sensitive Neo4j node index name that you want to query. 44 | 2. The valid lucene query that you want to use to query the supplied index. 45 | 3. The relationship name that will be used to determine the number of incoming links to each node you are querying for. Leave blank if you want to query all incoming links regardless of relationship type. 46 | 4. The label property name for each of your Neo4j nodes. See method summary for details. 47 | 5. Skip a number of a nodes, ordered by the Neo4j assigned node id of each node you are querying for. Use this for processing batches on large graph queries. 48 | 6. Limit the number of results you would like returned. Use this in combination with the skip property to process batches on large graph queries. 49 | 7. Returns a list of nodes that implements IGraphNode interface, having a label and size property for ranking result order. 50 | 51 | Use the IndexAutoCompleteKey method in the Processor class to index the autocomplete keys to blob storage uri. 52 | 53 | Your URI to the JSON file index will be: 54 | 55 | http://BLOB_STORAGE_NAME.blob.core.windows.net/BLOB_STORAGE_CONTAINER_ID/cache/PARTIAL_SEARCH_QUERY 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /images/predictive-autocomplete-configure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbastani/predictive-autocomplete/141499c97aae3ca7ace1a366ccd6d31bf96c4ef9/images/predictive-autocomplete-configure.png -------------------------------------------------------------------------------- /images/predictive-autocomplete.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kbastani/predictive-autocomplete/141499c97aae3ca7ace1a366ccd6d31bf96c4ef9/images/predictive-autocomplete.png -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2012 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PredictiveAutocomplete", "PredictiveAutocomplete\PredictiveAutocomplete.csproj", "{9F4BF250-ACCD-4471-91C3-DBC8862E72AC}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PredictiveAutocomplete_Test", "PredictiveAutocomplete_Test\PredictiveAutocomplete_Test.csproj", "{D48761DB-F0DC-43C7-8E5B-AB6D8BABA74D}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {9F4BF250-ACCD-4471-91C3-DBC8862E72AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {9F4BF250-ACCD-4471-91C3-DBC8862E72AC}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {9F4BF250-ACCD-4471-91C3-DBC8862E72AC}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {9F4BF250-ACCD-4471-91C3-DBC8862E72AC}.Release|Any CPU.Build.0 = Release|Any CPU 18 | {D48761DB-F0DC-43C7-8E5B-AB6D8BABA74D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {D48761DB-F0DC-43C7-8E5B-AB6D8BABA74D}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {D48761DB-F0DC-43C7-8E5B-AB6D8BABA74D}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {D48761DB-F0DC-43C7-8E5B-AB6D8BABA74D}.Release|Any CPU.Build.0 = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | EndGlobal 27 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/Configuration/Configuration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.WindowsAzure; 2 | using Microsoft.WindowsAzure.Storage; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Configuration; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace PredictiveAutocomplete 11 | { 12 | /// 13 | /// Utilities class used to load and retrieve platform configurations. 14 | /// 15 | public sealed class Configuration 16 | { 17 | #region Configuration Static Methods 18 | 19 | #region Private Fields 20 | 21 | // Configuration private fields 22 | private CloudStorageAccount _dataConnectionString = default(CloudStorageAccount); 23 | private string _neo4jConnectionString = string.Empty; 24 | private string _neo4jConnectionStringAuthentication = string.Empty; 25 | private string _autoCompleteCacheId = string.Empty; 26 | private string _blobStorageAddress = string.Empty; 27 | 28 | // Singleton state flag 29 | private bool _initialized = false; 30 | 31 | // Instance 32 | private static readonly Configuration _instance = new Configuration(); 33 | 34 | #endregion 35 | 36 | #region Public Fields 37 | 38 | /// 39 | /// The data connection string to Microsoft Windows Azure Blob Storage. 40 | /// 41 | public static CloudStorageAccount DataConnectionString { get { _instance.Internal_CheckEnforceIllegalAccess(); return _instance._dataConnectionString; } } 42 | 43 | /// 44 | /// The Neo4j connection string to this instance's memory store. 45 | /// 46 | public static string Neo4jConnectionString { get { _instance.Internal_CheckEnforceIllegalAccess(); return _instance._neo4jConnectionString; } } 47 | 48 | /// 49 | /// The Neo4j connection string's authentication mechanism. 50 | /// 51 | public static string Neo4jConnectionStringAuthentication { get { _instance.Internal_CheckEnforceIllegalAccess(); return _instance._neo4jConnectionStringAuthentication; } } 52 | 53 | /// 54 | /// The Auto Complete identifier for predictive search index. 55 | /// 56 | public static string AutoCompleteCacheId { get { _instance.Internal_CheckEnforceIllegalAccess(); return _instance._autoCompleteCacheId; } } 57 | 58 | /// 59 | /// The blob storage URI for this instance. 60 | /// 61 | public static string BlobStorageAddress { get { _instance.Internal_CheckEnforceIllegalAccess(); return _instance._blobStorageAddress; } } 62 | 63 | /// 64 | /// The instance of the singleton configuration class for the Core assembly. 65 | /// 66 | public static Configuration Instance { get { _instance.Internal_CheckEnforceIllegalAccess(); return _instance; } } 67 | 68 | /// 69 | /// Flag containing the initialization status of the singleton configuration class. If this flag is set to false, 70 | /// access to its other properties will result in an UnauthorizedAccessException. 71 | /// 72 | public static bool Initialized { get { _instance.Internal_CheckEnforceIllegalAccess(); return _instance._initialized; } } 73 | 74 | #endregion 75 | 76 | /// 77 | /// Private constructor for the singleton configuration class. 78 | /// 79 | private Configuration() 80 | { 81 | 82 | } 83 | 84 | /// 85 | /// Initialization method used to instantiate configuration data embedded as a resource in the Core assembly. 86 | /// 87 | public static void Initialize() 88 | { 89 | lock (_instance) 90 | { 91 | if (!_instance._initialized) 92 | { 93 | // Initialize configuration values 94 | _instance._autoCompleteCacheId = GetAutoCompleteAddress(); 95 | _instance._dataConnectionString = GetDataConnectionString(); 96 | _instance._neo4jConnectionString = GetNeo4jConnectionString(); 97 | _instance._neo4jConnectionStringAuthentication = GetNeo4jConnectionStringAuthentication(); 98 | 99 | // Set the initialized flag to true 100 | _instance._initialized = true; 101 | } 102 | } 103 | } 104 | 105 | 106 | /// 107 | /// Check to enforce that the singleton configuration class has been properly initialized before access. 108 | /// 109 | /// Returns true of the singleton configuration class has been initialized. 110 | public static bool CheckEnforceIllegalAccess() 111 | { 112 | return _instance.Internal_CheckEnforceIllegalAccess(); 113 | } 114 | 115 | /// 116 | /// Internal reference check to enforce that the singleton configuration class has been properly initialized before access. 117 | /// 118 | /// Returns true of the singleton configuration class has been initialized. 119 | private bool Internal_CheckEnforceIllegalAccess() 120 | { 121 | if (_instance._initialized) 122 | { 123 | return true; 124 | } 125 | else 126 | { 127 | try 128 | { 129 | Configuration.Initialize(); 130 | return true; 131 | } 132 | catch (Exception) 133 | { 134 | return false; 135 | } 136 | } 137 | } 138 | 139 | #endregion 140 | 141 | public static CloudStorageAccount GetDataConnectionString() 142 | { 143 | try 144 | { 145 | if (CloudConfigurationManager.GetSetting("DataConnectionString") != null) 146 | { 147 | string storageId = CloudConfigurationManager.GetSetting("DataConnectionString"); 148 | return CloudStorageAccount.Parse(storageId); 149 | } 150 | } 151 | catch (Exception) 152 | { 153 | } 154 | 155 | string connString = ConfigurationManager.AppSettings["DataConnectionString"]; 156 | return CloudStorageAccount.Parse(connString); 157 | 158 | } 159 | 160 | 161 | public static string GetAutoCompleteCacheId() 162 | { 163 | if (Initialized) 164 | { 165 | return AutoCompleteCacheId; 166 | } 167 | else 168 | { 169 | return GetAutoCompleteAddress(); 170 | } 171 | } 172 | 173 | public static string GetAutoCompleteAddress() 174 | { 175 | try 176 | { 177 | if (CloudConfigurationManager.GetSetting("AutoCompleteCacheId") != null) 178 | { 179 | string cacheId = CloudConfigurationManager.GetSetting("AutoCompleteCacheId"); 180 | return cacheId; 181 | } 182 | } 183 | catch (Exception) 184 | { 185 | } 186 | 187 | 188 | return ConfigurationManager.AppSettings["AutoCompleteCacheId"]; 189 | 190 | } 191 | 192 | public static string GetDatabaseUri() 193 | { 194 | if (Initialized) 195 | { 196 | return Neo4jConnectionString; 197 | } 198 | else 199 | { 200 | return GetNeo4jConnectionString(); 201 | } 202 | } 203 | 204 | public static string GetNeo4jConnectionString() 205 | { 206 | try 207 | { 208 | if (CloudConfigurationManager.GetSetting("GuySwarm.MyAddress") != null) 209 | { 210 | var databaseUri = CloudConfigurationManager.GetSetting("Neo4j.ConnectionString"); 211 | return databaseUri; 212 | } 213 | } 214 | catch (Exception) 215 | { 216 | } 217 | // Get database URI from configuration 218 | return ConfigurationManager.AppSettings["Neo4j.ConnectionString"]; 219 | } 220 | 221 | public static string GetAuthorizationHeader() 222 | { 223 | if (Initialized) 224 | { 225 | return Neo4jConnectionStringAuthentication; 226 | } 227 | else 228 | { 229 | return GetNeo4jConnectionStringAuthentication(); 230 | } 231 | } 232 | 233 | public static string GetNeo4jConnectionStringAuthentication() 234 | { 235 | try 236 | { 237 | if (CloudConfigurationManager.GetSetting("Neo4j.ConnectionString.Authentication") != null) 238 | { 239 | var authentication = CloudConfigurationManager.GetSetting("Neo4j.ConnectionString.Authentication"); 240 | return authentication; 241 | } 242 | } 243 | catch (Exception) 244 | { 245 | } 246 | // Get database URI from configuration 247 | return ConfigurationManager.AppSettings["Neo4j.ConnectionString.Authentication"]; 248 | } 249 | 250 | } 251 | 252 | } 253 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/CypherQueryCreator.cs: -------------------------------------------------------------------------------- 1 | using Neo4jClient; 2 | using Neo4jClient.Cypher; 3 | using Neo4jClient.Serialization; 4 | using Newtonsoft.Json; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.ComponentModel; 8 | using System.ComponentModel.DataAnnotations; 9 | using System.Diagnostics; 10 | using System.Globalization; 11 | using System.IO; 12 | using System.Linq; 13 | using System.Linq.Expressions; 14 | using System.Net; 15 | using System.Net.Http; 16 | using System.Text; 17 | using System.Text.RegularExpressions; 18 | using System.Threading.Tasks; 19 | using System.Web; 20 | 21 | 22 | namespace PredictiveAutocomplete 23 | { 24 | [JsonObject] 25 | public class Extensions 26 | { 27 | } 28 | 29 | [JsonObject] 30 | public class BatchApiResponseBody 31 | { 32 | [JsonProperty] 33 | public Extensions extensions { get; set; } 34 | [JsonProperty] 35 | public string paged_traverse { get; set; } 36 | [JsonProperty] 37 | public string outgoing_relationships { get; set; } 38 | [JsonProperty] 39 | public string traverse { get; set; } 40 | [JsonProperty] 41 | public string all_typed_relationships { get; set; } 42 | [JsonProperty] 43 | public string all_relationships { get; set; } 44 | [JsonProperty] 45 | public string property { get; set; } 46 | [JsonProperty] 47 | public string self { get; set; } 48 | [JsonProperty] 49 | public string outgoing_typed_relationships { get; set; } 50 | [JsonProperty] 51 | public string properties { get; set; } 52 | [JsonProperty] 53 | public string incoming_relationships { get; set; } 54 | [JsonProperty] 55 | public string incoming_typed_relationships { get; set; } 56 | [JsonProperty] 57 | public string create_relationship { get; set; } 58 | [JsonProperty] 59 | public Data data { get; set; } 60 | public string start { get; set; } 61 | [JsonProperty] 62 | public string type { get; set; } 63 | [JsonProperty] 64 | public string end { get; set; } 65 | [JsonProperty] 66 | public string indexed { get; set; } 67 | } 68 | 69 | [JsonObject] 70 | public class BatchApiResponse 71 | { 72 | [JsonProperty] 73 | public int id { get; set; } 74 | [JsonProperty] 75 | public string location { get; set; } 76 | [JsonProperty] 77 | public BatchApiResponseBody body { get; set; } 78 | [JsonProperty] 79 | public string from { get; set; } 80 | } 81 | 82 | [JsonObject] 83 | public class Data 84 | { 85 | [JsonProperty] 86 | public string since { get; set; } 87 | } 88 | 89 | [JsonObject] 90 | public class Body 91 | { 92 | [JsonProperty] 93 | public string name { get; set; } 94 | [JsonProperty] 95 | public int? age { get; set; } 96 | [JsonProperty] 97 | public string to { get; set; } 98 | [JsonProperty] 99 | public Data data { get; set; } 100 | [JsonProperty] 101 | public string type { get; set; } 102 | [JsonProperty(PropertyName="key")] 103 | public string itemkey { get; set; } 104 | [JsonProperty] 105 | public string Key { get; set; } 106 | [JsonProperty] 107 | public string Content { get; set; } 108 | [JsonProperty] 109 | public string Weight { get; set; } 110 | [JsonProperty] 111 | public string value { get; set; } 112 | [JsonProperty] 113 | public string uri { get; set; } 114 | [JsonProperty] 115 | public string phrase { get; set; } 116 | [JsonProperty] 117 | public string Expression { get; set; } 118 | } 119 | 120 | 121 | 122 | [JsonObject] 123 | public class ApiAction 124 | { 125 | [JsonProperty] 126 | public string method { get; set; } 127 | [JsonProperty] 128 | public string to { get; set; } 129 | [JsonProperty] 130 | public int id { get; set; } 131 | [JsonProperty] 132 | public Body body { get; set; } 133 | } 134 | 135 | public class CypherQueryCreator 136 | { 137 | IDictionary queryParameters = new Dictionary(); 138 | IList startBits = new List(); 139 | string matchText; 140 | string relateText; 141 | string createUniqueText; 142 | string whereText; 143 | string whereMatchText; 144 | IList createBits = new List(); 145 | string deleteText; 146 | string withText; 147 | string returnText; 148 | bool returnDistinct; 149 | CypherResultMode resultMode; 150 | int? limit; 151 | int? skip; 152 | string orderBy; 153 | string setText; 154 | public string queryText = null; 155 | 156 | 157 | CypherQueryCreator Clone() 158 | { 159 | return new CypherQueryCreator() 160 | { 161 | queryParameters = queryParameters, 162 | createBits = createBits, 163 | deleteText = deleteText, 164 | matchText = matchText, 165 | relateText = relateText, 166 | createUniqueText = createUniqueText, 167 | whereText = whereText, 168 | whereMatchText = whereMatchText, 169 | withText = withText, 170 | returnText = returnText, 171 | returnDistinct = returnDistinct, 172 | resultMode = resultMode, 173 | limit = limit, 174 | skip = skip, 175 | startBits = startBits, 176 | orderBy = orderBy, 177 | setText = setText, 178 | queryText = queryText 179 | }; 180 | } 181 | 182 | public CypherQueryCreator() 183 | { 184 | 185 | } 186 | 187 | public CypherQueryCreator(string queryText) 188 | { 189 | this.queryText = queryText; 190 | } 191 | 192 | public CypherQueryCreator AddStartBit(string identity, string startText) 193 | { 194 | var newBuilder = Clone(); 195 | newBuilder.startBits.Add(new RawCypherStartBit(identity, startText)); 196 | return newBuilder; 197 | } 198 | 199 | public CypherQueryCreator AddStartBit(string identity, params NodeReference[] nodeReferences) 200 | { 201 | var newBuilder = Clone(); 202 | newBuilder.startBits.Add(new CypherStartBit(identity, "node", nodeReferences.Select(r => r.Id).ToArray())); 203 | return newBuilder; 204 | } 205 | 206 | public CypherQueryCreator AddStartBit(string identity, params RelationshipReference[] relationshipReferences) 207 | { 208 | var newBuilder = Clone(); 209 | newBuilder.startBits.Add(new CypherStartBit(identity, "relationship", relationshipReferences.Select(r => r.Id).ToArray())); 210 | return newBuilder; 211 | } 212 | 213 | public CypherQueryCreator AddStartBitWithNodeIndexLookup(string identity, string indexName, string parameterText) 214 | { 215 | var newBuilder = Clone(); 216 | newBuilder.startBits.Add(new CypherStartBitWithNodeIndexLookupWithSingleParameter(identity, indexName, parameterText)); 217 | return newBuilder; 218 | } 219 | 220 | public CypherQueryCreator AddStartBitWithNodeIndexLookup(string identity, string indexName, string key, object value) 221 | { 222 | var newBuilder = Clone(); 223 | newBuilder.startBits.Add(new CypherStartBitWithNodeIndexLookup(identity, indexName, key, value)); 224 | return newBuilder; 225 | } 226 | 227 | public CypherQueryCreator SetDeleteText(string text) 228 | { 229 | var newBuilder = Clone(); 230 | newBuilder.deleteText = text; 231 | return newBuilder; 232 | } 233 | 234 | public CypherQueryCreator SetMatchText(string text) 235 | { 236 | var newBuilder = Clone(); 237 | newBuilder.matchText = text; 238 | return newBuilder; 239 | } 240 | 241 | public CypherQueryCreator SetRelateText(string text) 242 | { 243 | var newBuilder = Clone(); 244 | newBuilder.relateText = text; 245 | return newBuilder; 246 | } 247 | 248 | public CypherQueryCreator SetWithText(string text) 249 | { 250 | var newBuilder = Clone(); 251 | newBuilder.withText = text; 252 | return newBuilder; 253 | } 254 | 255 | public CypherQueryCreator SetCreateUniqueText(string text) 256 | { 257 | var newBuilder = Clone(); 258 | newBuilder.createUniqueText = text; 259 | return newBuilder; 260 | } 261 | 262 | public CypherQueryCreator SetCreateText(string text) 263 | { 264 | var newBuilder = Clone(); 265 | newBuilder.createBits.Add(new CypherCreateTextBit(text)); 266 | return newBuilder; 267 | } 268 | 269 | public CypherQueryCreator SetWhere(string text) 270 | { 271 | var newBuilder = Clone(); 272 | newBuilder.whereText += string.Format("({0})", text); 273 | return newBuilder; 274 | } 275 | 276 | public CypherQueryCreator SetWhereMatch(string text) 277 | { 278 | var newBuilder = Clone(); 279 | newBuilder.whereMatchText += string.Format("({0})", text); 280 | return newBuilder; 281 | } 282 | 283 | public CypherQueryCreator SetWhere(LambdaExpression expression) 284 | { 285 | var newBuilder = Clone(); 286 | newBuilder.whereText += whereText = CypherWhereExpressionBuilder.BuildText(expression, new Func(str => (string)queryParameters[str.ToString()])); 287 | return newBuilder; 288 | } 289 | 290 | public CypherQueryCreator SetAnd() 291 | { 292 | var newBuilder = Clone(); 293 | newBuilder.whereText += " AND "; 294 | return newBuilder; 295 | } 296 | 297 | public CypherQueryCreator SetOr() 298 | { 299 | var newBuilder = Clone(); 300 | newBuilder.whereText += " OR "; 301 | return newBuilder; 302 | } 303 | 304 | public CypherQueryCreator SetReturnText(string returnText) 305 | { 306 | var newBuilder = Clone(); 307 | newBuilder.returnText = returnText; 308 | return newBuilder; 309 | } 310 | 311 | public CypherQueryCreator SetReturn(string identity, bool distinct, CypherResultMode mode = CypherResultMode.Set) 312 | { 313 | var newBuilder = Clone(); 314 | newBuilder.returnText = identity; 315 | newBuilder.returnDistinct = distinct; 316 | newBuilder.resultMode = mode; 317 | return newBuilder; 318 | } 319 | 320 | public CypherQueryCreator SetReturn(LambdaExpression expression, bool distinct) 321 | { 322 | var newBuilder = Clone(); 323 | newBuilder.returnText = CypherReturnExpressionBuilder.BuildText(expression).Text; 324 | newBuilder.returnDistinct = distinct; 325 | newBuilder.resultMode = CypherResultMode.Projection; 326 | return newBuilder; 327 | } 328 | 329 | public CypherQueryCreator SetLimit(int? count) 330 | { 331 | var newBuilder = Clone(); 332 | newBuilder.limit = count; 333 | return newBuilder; 334 | } 335 | 336 | public CypherQueryCreator SetSkip(int? count) 337 | { 338 | var newBuilder = Clone(); 339 | newBuilder.skip = count; 340 | return newBuilder; 341 | } 342 | 343 | public CypherQueryCreator SetOrderBy(OrderByType orderByType, params string[] properties) 344 | { 345 | var newBuilder = Clone(); 346 | newBuilder.orderBy = string.Join(", ", properties); 347 | 348 | if (orderByType == OrderByType.Descending) 349 | newBuilder.orderBy += " DESC"; 350 | 351 | return newBuilder; 352 | } 353 | 354 | public CypherQueryCreator SetSetText(string text) 355 | { 356 | var newBuilder = Clone(); 357 | newBuilder.setText = text; 358 | return newBuilder; 359 | } 360 | 361 | public CypherQuery ToQuery() 362 | { 363 | if (queryText != null) 364 | { 365 | return new CypherQuery(queryText, queryParameters, resultMode); 366 | } 367 | else 368 | { 369 | var queryTextBuilder = new StringBuilder(); 370 | WriteStartClause(queryTextBuilder, queryParameters); 371 | WriteMatchClause(queryTextBuilder); 372 | if (!string.IsNullOrEmpty(whereMatchText)) 373 | { 374 | WriteWhereMatchClause(queryTextBuilder); 375 | } 376 | 377 | WriteRelateClause(queryTextBuilder); 378 | WriteWithClause(queryTextBuilder); 379 | WriteCreateUniqueClause(queryTextBuilder); 380 | WriteCreateClause(queryTextBuilder); 381 | WriteWhereClause(queryTextBuilder); 382 | WriteDeleteClause(queryTextBuilder); 383 | WriteSetClause(queryTextBuilder); 384 | WriteReturnClause(queryTextBuilder); 385 | WriteOrderByClause(queryTextBuilder); 386 | WriteSkipClause(queryTextBuilder, queryParameters); 387 | WriteLimitClause(queryTextBuilder, queryParameters); 388 | return new CypherQuery(queryTextBuilder.ToString(), queryParameters, resultMode); 389 | } 390 | 391 | } 392 | 393 | public static string CreateParameter(IDictionary parameters, object paramValue) 394 | { 395 | var paramName = string.Format("p{0}", parameters.Count); 396 | parameters.Add(paramName, paramValue); 397 | return "{" + paramName + "}"; 398 | } 399 | 400 | void WriteStartClause(StringBuilder target, IDictionary paramsDictionary) 401 | { 402 | if (startBits.Any()) { 403 | target.Append("START "); 404 | 405 | var formattedStartBits = startBits.Select(bit => { 406 | var standardStartBit = bit as CypherStartBit; 407 | if (standardStartBit != null) { 408 | var lookupIdParameterNames = standardStartBit 409 | .LookupIds 410 | .Select(i => CreateParameter(paramsDictionary, i)) 411 | .ToArray(); 412 | 413 | var lookupContent = string.Join(", ", lookupIdParameterNames); 414 | return string.Format("{0}={1}({2})", 415 | standardStartBit.Identifier, 416 | standardStartBit.LookupType, 417 | lookupContent); 418 | } 419 | 420 | var rawStartBit = bit as RawCypherStartBit; 421 | if (rawStartBit != null) 422 | { 423 | return string.Format("{0}={1}", rawStartBit.Identifier, rawStartBit.StartText); 424 | } 425 | 426 | var startBithWithNodeIndexLookup = bit as CypherStartBitWithNodeIndexLookup; 427 | if (startBithWithNodeIndexLookup != null) { 428 | var valueParameter = CreateParameter(paramsDictionary, startBithWithNodeIndexLookup.Value); 429 | return string.Format("{0}=node:{1}({2} = {3})", 430 | startBithWithNodeIndexLookup.Identifier, 431 | startBithWithNodeIndexLookup.IndexName, 432 | startBithWithNodeIndexLookup.Key, 433 | valueParameter); 434 | } 435 | 436 | var startBithWithNodeIndexLookupSingleParameter = bit as CypherStartBitWithNodeIndexLookupWithSingleParameter; 437 | if (startBithWithNodeIndexLookupSingleParameter != null) { 438 | var valueParameter = CreateParameter(paramsDictionary, startBithWithNodeIndexLookupSingleParameter.Parameter); 439 | return string.Format("{0}=node:{1}({2})", 440 | startBithWithNodeIndexLookupSingleParameter.Identifier, 441 | startBithWithNodeIndexLookupSingleParameter.IndexName, 442 | valueParameter); 443 | } 444 | 445 | throw new NotSupportedException(string.Format("Start bit of type {0} is not supported.", bit.GetType().FullName)); 446 | }); 447 | 448 | target.Append(string.Join(", ", formattedStartBits)); 449 | } 450 | } 451 | 452 | void WriteMatchClause(StringBuilder target) 453 | { 454 | if (matchText == null) return; 455 | target.AppendFormat("\r\nMATCH {0}", matchText); 456 | } 457 | 458 | void WriteDeleteClause(StringBuilder target) 459 | { 460 | if (deleteText == null) return; 461 | target.AppendFormat("\r\nDELETE {0}", deleteText); 462 | } 463 | 464 | void WriteRelateClause(StringBuilder target) 465 | { 466 | if (relateText == null) return; 467 | target.AppendFormat("\r\nRELATE {0}", relateText); 468 | } 469 | 470 | void WriteWithClause(StringBuilder target) 471 | { 472 | if (withText == null) return; 473 | target.AppendFormat("\r\nWITH {0}", withText); 474 | } 475 | 476 | void WriteCreateUniqueClause(StringBuilder target) 477 | { 478 | if (createUniqueText == null) return; 479 | target.AppendFormat("\r\nCREATE UNIQUE {0}", createUniqueText); 480 | } 481 | 482 | void WriteCreateClause(StringBuilder target) 483 | { 484 | if (createBits.Any()) 485 | { 486 | target.Append("\r\nCREATE "); 487 | var formattedCreateBits = createBits.Select(bit => 488 | { 489 | var createTextbit = bit as CypherCreateTextBit; 490 | if (createTextbit != null) 491 | { 492 | return createTextbit.CreateText; 493 | } 494 | 495 | throw new NotSupportedException(string.Format("Create bit of type {0} is not supported.", bit.GetType().FullName)); 496 | }); 497 | 498 | target.Append(string.Join("", formattedCreateBits)); 499 | } 500 | } 501 | 502 | void WriteWhereClause(StringBuilder target) 503 | { 504 | if (whereText == null) 505 | return; 506 | 507 | target.Append("\r\nWHERE "); 508 | target.Append(whereText); 509 | } 510 | 511 | void WriteWhereMatchClause(StringBuilder target) 512 | { 513 | if (whereMatchText == null) 514 | return; 515 | 516 | target.Append("\r\nWHERE "); 517 | target.Append(whereMatchText); 518 | } 519 | 520 | void WriteReturnClause(StringBuilder target) 521 | { 522 | if (returnText == null) return; 523 | target.Append("\r\nRETURN "); 524 | if (returnDistinct) target.Append("distinct "); 525 | target.Append(returnText); 526 | } 527 | 528 | void WriteLimitClause(StringBuilder target, IDictionary paramsDictionary) 529 | { 530 | if (limit == null) return; 531 | target.AppendFormat("\r\nLIMIT {0}", CreateParameter(paramsDictionary, limit)); 532 | } 533 | 534 | void WriteSkipClause(StringBuilder target, IDictionary paramsDictionary) 535 | { 536 | if (skip == null) return; 537 | target.AppendFormat("\r\nSKIP {0}", CreateParameter(paramsDictionary, skip)); 538 | } 539 | 540 | void WriteOrderByClause(StringBuilder target ) 541 | { 542 | if (string.IsNullOrEmpty(orderBy)) return; 543 | target.AppendFormat("\r\nORDER BY {0}", orderBy); 544 | } 545 | 546 | void WriteSetClause(StringBuilder target) 547 | { 548 | if (setText == null) return; 549 | target.AppendFormat("\r\nSET {0}", setText); 550 | } 551 | } 552 | 553 | internal class CypherCreateTextBit 554 | { 555 | readonly string createText; 556 | 557 | public CypherCreateTextBit(string createText) 558 | { 559 | this.createText = createText; 560 | } 561 | 562 | public string CreateText 563 | { 564 | get { return createText; } 565 | } 566 | } 567 | 568 | internal class CypherStartBitWithNodeIndexLookupWithSingleParameter 569 | { 570 | readonly string identifier; 571 | readonly string indexName; 572 | readonly string parameter; 573 | 574 | public CypherStartBitWithNodeIndexLookupWithSingleParameter(string identifier, string indexName, string parameter) 575 | { 576 | this.identifier = identifier; 577 | this.indexName = indexName; 578 | this.parameter = parameter; 579 | } 580 | 581 | public string Identifier { get { return identifier; } } 582 | public string IndexName { get { return indexName; } } 583 | public string Parameter { get { return parameter; } } 584 | } 585 | 586 | internal class CypherStartBitWithNodeIndexLookup 587 | { 588 | readonly string identifier; 589 | readonly string indexName; 590 | readonly string key; 591 | readonly object value; 592 | 593 | public CypherStartBitWithNodeIndexLookup(string identifier, string indexName, string key, object value) 594 | { 595 | this.identifier = identifier; 596 | this.indexName = indexName; 597 | this.key = key; 598 | this.value = value; 599 | } 600 | 601 | public string Identifier { get { return identifier; } } 602 | public string IndexName { get { return indexName; } } 603 | public string Key { get { return key; } } 604 | public object Value { get { return value; } } 605 | } 606 | 607 | 608 | internal class CypherStartBit 609 | { 610 | readonly string identifier; 611 | readonly string lookupType; 612 | readonly IEnumerable lookupIds; 613 | 614 | public CypherStartBit(string identifier, string lookupType, IEnumerable lookupIds) 615 | { 616 | this.identifier = identifier; 617 | this.lookupType = lookupType; 618 | this.lookupIds = lookupIds; 619 | } 620 | 621 | public string Identifier 622 | { 623 | get { return identifier; } 624 | } 625 | 626 | public string LookupType 627 | { 628 | get { return lookupType; } 629 | } 630 | 631 | public IEnumerable LookupIds 632 | { 633 | get { return lookupIds; } 634 | } 635 | } 636 | 637 | internal class RawCypherStartBit 638 | { 639 | readonly string identifier; 640 | readonly string startText; 641 | 642 | public RawCypherStartBit(string identifier, string startText) 643 | { 644 | this.identifier = identifier; 645 | this.startText = startText; 646 | } 647 | 648 | public string Identifier 649 | { 650 | get { return identifier; } 651 | } 652 | 653 | public string StartText 654 | { 655 | get { return startText; } 656 | } 657 | } 658 | 659 | 660 | 661 | [DebuggerDisplay("{Query.DebugQueryText}")] 662 | public class CypherFluentQueryCreator : 663 | IAttachedReference 664 | { 665 | protected readonly IRawGraphClient Client; 666 | protected readonly CypherQueryCreator Builder; 667 | readonly IHttpClient httpClient; 668 | public Uri CypherQueryDatabaseUri { get; set; } 669 | 670 | public CypherFluentQueryCreator(IGraphClient client, Uri databaseUri) 671 | : this(client, new CypherQueryCreator(), databaseUri) 672 | { 673 | this.CypherQueryDatabaseUri = databaseUri; 674 | httpClient = GetNeo4jAuthenticatedClient(httpClient as HttpClient, this.CypherQueryDatabaseUri); 675 | 676 | } 677 | 678 | private static HttpClientWrapper GetNeo4jAuthenticatedClient(HttpClient httpClient, Uri databaseUri) 679 | { 680 | 681 | if (httpClient == null) 682 | { 683 | httpClient = new HttpClient(); 684 | httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(Configuration.GetAuthorizationHeader()))); 685 | } 686 | 687 | httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(Configuration.GetAuthorizationHeader()))); 688 | httpClient.DefaultRequestHeaders.AcceptEncoding.Remove(new System.Net.Http.Headers.StringWithQualityHeaderValue("UTF-8")); 689 | httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("UTF-8")); 690 | PredictiveAutocomplete.HttpClientWrapper clientWrapper = new PredictiveAutocomplete.HttpClientWrapper(httpClient); 691 | clientWrapper.Uri = databaseUri.ToString(); 692 | 693 | return clientWrapper; 694 | } 695 | 696 | public CypherFluentQueryCreator(IGraphClient client, CypherQueryCreator builder, Uri databaseUri) 697 | { 698 | this.CypherQueryDatabaseUri = databaseUri; 699 | if (!(client is IRawGraphClient)) 700 | throw new ArgumentException("The supplied graph client also needs to implement IRawGraphClient", "client"); 701 | httpClient = new PredictiveAutocomplete.HttpClientWrapper(); 702 | Client = (IRawGraphClient)client; 703 | Builder = builder; 704 | } 705 | 706 | public CypherFluentQueryCreator Start(string identity, string startText) 707 | { 708 | var newBuilder = new CypherQueryCreator(); 709 | newBuilder.AddStartBit(identity, startText); 710 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 711 | } 712 | 713 | public CypherFluentQueryCreator Start(string identity, params NodeReference[] nodeReferences) 714 | { 715 | var newBuilder = new CypherQueryCreator(); 716 | newBuilder.AddStartBit(identity, nodeReferences); 717 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 718 | } 719 | 720 | public CypherFluentQueryCreator Start(string identity, params RelationshipReference[] relationshipReferences) 721 | { 722 | var newBuilder = new CypherQueryCreator(); 723 | newBuilder.AddStartBit(identity, relationshipReferences); 724 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 725 | } 726 | 727 | public CypherFluentQueryCreator StartWithNodeIndexLookup(string identity, string indexName, string key, object value) 728 | { 729 | var newBuilder = new CypherQueryCreator(); 730 | newBuilder.AddStartBitWithNodeIndexLookup(identity, indexName, key, value); 731 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 732 | } 733 | 734 | public CypherFluentQueryCreator StartWithNodeIndexLookup(string identity, string indexName, string parameter) 735 | { 736 | var newBuilder = new CypherQueryCreator(); 737 | newBuilder.AddStartBitWithNodeIndexLookup(identity, indexName, parameter); 738 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 739 | } 740 | 741 | public CypherFluentQueryCreator AddStartPoint(string identity, string startText) 742 | { 743 | var newBuilder = Builder.AddStartBit(identity, startText); 744 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 745 | } 746 | 747 | public CypherFluentQueryCreator AddStartPointWithNodeIndexLookup(string identity, string indexName, string key, object value) 748 | { 749 | var newBuilder = Builder.AddStartBitWithNodeIndexLookup(identity, indexName, key, value); 750 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 751 | } 752 | 753 | public CypherFluentQueryCreator AddStartPoint(string identity, params NodeReference[] nodeReferences) 754 | { 755 | var newBuilder = Builder.AddStartBit(identity, nodeReferences); 756 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 757 | } 758 | 759 | public CypherFluentQueryCreator AddStartPoint(string identity, params RelationshipReference[] relationshipReferences) 760 | { 761 | var newBuilder = Builder.AddStartBit(identity, relationshipReferences); 762 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 763 | } 764 | 765 | public CypherFluentQueryCreator Match(params string[] matchText) 766 | { 767 | var newBuilder = Builder.SetMatchText(string.Join(", ", matchText)); 768 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 769 | } 770 | 771 | public CypherFluentQueryCreator With(string withText) 772 | { 773 | var newBuilder = Builder.SetWithText(withText); 774 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 775 | } 776 | 777 | public CypherFluentQueryCreator Where(string whereText) 778 | { 779 | var newBuilder = Builder.SetWhere(whereText); 780 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 781 | } 782 | 783 | public CypherFluentQueryCreator WhereMatch(string whereMatchText) 784 | { 785 | var newBuilder = Builder.SetWhereMatch(whereMatchText); 786 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 787 | } 788 | 789 | public CypherFluentQueryCreator Limit(int? count) 790 | { 791 | var newBuilder = Builder.SetLimit(count); 792 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 793 | } 794 | 795 | public CypherFluentQueryCreator OrderBy(OrderByType orderByType, string orderByText) 796 | { 797 | var newBuilder = Builder.SetOrderBy(orderByType, orderByText); 798 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 799 | } 800 | 801 | public CypherFluentQueryCreator And() 802 | { 803 | var newBuilder = Builder.SetWhere("and"); 804 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 805 | } 806 | 807 | public CypherFluentQueryCreator Relate(string relateText) 808 | { 809 | if (Client.ServerVersion == new Version(1, 8) || 810 | Client.ServerVersion >= new Version(1, 8, 0, 7)) 811 | throw new NotSupportedException("You're trying to use the RELATE keyword against a Neo4j instance ≥ 1.8M07. In Neo4j 1.8M07, it was renamed from RELATE to CREATE UNIQUE. You need to update your code to use our new CreateUnique method. (We didn't want to just plumb the Relate method to CREATE UNIQUE, because that would introduce a deviation between the .NET wrapper and the Cypher language.)\r\n\r\nSee https://github.com/systay/community/commit/c7dbbb929abfef600266a20f065d760e7a1fff2e for detail."); 812 | 813 | var newBuilder = Builder.SetRelateText(relateText); 814 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 815 | } 816 | 817 | public CypherFluentQueryCreator CreateUnique(string createUniqueText) 818 | { 819 | if (Client.ServerVersion < new Version(1, 8) || 820 | (Client.ServerVersion >= new Version(1, 8, 0, 1) && Client.ServerVersion <= new Version(1, 8, 0, 6))) 821 | throw new NotSupportedException("The CREATE UNIQUE clause was only introduced in Neo4j 1.8M07, but you're querying against an older version of Neo4j. You'll want to upgrade Neo4j, or use the RELATE keyword instead. See https://github.com/systay/community/commit/c7dbbb929abfef600266a20f065d760e7a1fff2e for detail."); 822 | 823 | var newBuilder = Builder.SetCreateUniqueText(createUniqueText); 824 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 825 | } 826 | 827 | public CypherFluentQueryCreator Create(string createText) 828 | { 829 | var newBuilder = Builder.SetCreateText(createText); 830 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 831 | } 832 | 833 | public CypherFluentQueryCreator Return(string returnText) 834 | { 835 | var newBuilder = Builder.SetReturnText(returnText); 836 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 837 | } 838 | 839 | public CypherFluentQueryCreator Create(string identity, TNode node) 840 | where TNode : class 841 | { 842 | if (typeof(TNode).IsGenericType && 843 | typeof(TNode).GetGenericTypeDefinition() == typeof(Node<>)) 844 | { 845 | throw new ArgumentException(string.Format( 846 | "You're trying to pass in a Node<{0}> instance. Just pass the {0} instance instead.", 847 | typeof(TNode).GetGenericArguments()[0].Name), 848 | "node"); 849 | } 850 | 851 | if (node == null) 852 | throw new ArgumentNullException("node"); 853 | 854 | var validationContext = new ValidationContext(node, null, null); 855 | Validator.ValidateObject(node, validationContext); 856 | 857 | var serializer = new CustomJsonSerializer { NullHandling = NullValueHandling.Ignore, QuoteName = false }; 858 | var newBuilder = Builder.SetCreateText(string.Format("({0} {1})", identity, serializer.Serialize(node))); 859 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 860 | } 861 | 862 | public CypherFluentQueryCreator Delete(string identities) 863 | { 864 | var newBuilder = Builder.SetDeleteText(identities); 865 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 866 | } 867 | 868 | public CypherFluentQueryCreator Set(string setText) 869 | { 870 | var newBuilder = Builder.SetSetText(setText); 871 | return new CypherFluentQueryCreator(Client, newBuilder, this.CypherQueryDatabaseUri); 872 | } 873 | 874 | public CypherQuery Query 875 | { 876 | get 877 | { 878 | if (!string.IsNullOrEmpty(Builder.queryText)) 879 | { 880 | return new CypherQuery(Builder.queryText, null, CypherResultMode.Projection); 881 | } 882 | else 883 | { 884 | return Builder.ToQuery(); 885 | } 886 | 887 | } 888 | } 889 | 890 | public void ExecuteWithoutResults() 891 | { 892 | Client.ExecuteCypher(Query); 893 | } 894 | 895 | IGraphClient IAttachedReference.Client 896 | { 897 | get { return Client; } 898 | } 899 | 900 | public async Task> ExecuteGetCypherResults() 901 | { 902 | var task = await ExecuteGetCypherResultsAsync(Query); 903 | return task; 904 | } 905 | 906 | internal RootApiResponse RootApiResponse = new RootApiResponse(); 907 | 908 | public void ExecuteCustomQueryWithoutResults() 909 | { 910 | if (RootApiResponse.neo4j_version == null) 911 | { 912 | Connect(); 913 | } 914 | 915 | var response = SendHttpRequestAsync( 916 | HttpPostAsJson(RootApiResponse.Cypher, new CypherApiQuery(Query)), 917 | string.Format("The query was: {0}", Query.QueryText), 918 | HttpStatusCode.OK); 919 | } 920 | 921 | public async Task> ExecuteGetCypherResultsAsync(CypherQuery query) 922 | { 923 | if (RootApiResponse.neo4j_version == null) 924 | { 925 | Connect(); 926 | } 927 | 928 | var response = SendHttpRequestAsync( 929 | HttpPostAsJson(RootApiResponse.Cypher, new CypherApiQuery(query)), 930 | string.Format("The query was: {0}", query.QueryText), 931 | HttpStatusCode.OK); 932 | 933 | 934 | var content = await response.Result.Content.ReadAsByteArrayAsync(); 935 | string unicodeContent = Encoding.UTF8.GetString(content); 936 | 937 | var deserializer = new CypherJsonDeserializer(Client, CypherResultMode.Projection); 938 | 939 | var results = deserializer 940 | .Deserialize(unicodeContent) 941 | .ToList(); 942 | 943 | return (IEnumerable)results; 944 | } 945 | 946 | Uri RootUri; 947 | 948 | Uri BuildUri(string relativeUri) 949 | { 950 | RootUri = CypherQueryDatabaseUri; 951 | var baseUri = CypherQueryDatabaseUri; 952 | if (!RootUri.AbsoluteUri.EndsWith("/")) 953 | baseUri = new Uri(RootUri.AbsoluteUri + "/"); 954 | 955 | if (relativeUri == null) 956 | { 957 | relativeUri = ""; 958 | } 959 | 960 | if (relativeUri.StartsWith("/")) 961 | relativeUri = relativeUri.Substring(1); 962 | 963 | return new Uri(baseUri, relativeUri); 964 | } 965 | 966 | static CustomJsonSerializer BuildSerializer() 967 | { 968 | return new CustomJsonSerializer(); 969 | } 970 | 971 | public HttpRequestMessage HttpPostAsJson(string relativeUri, object postBody) 972 | { 973 | var absoluteUri = BuildUri(relativeUri); 974 | var postBodyJson = BuildSerializer().Serialize(postBody); 975 | var request = new HttpRequestMessage(HttpMethod.Post, absoluteUri); 976 | request.Content = new StringContent(postBodyJson, Encoding.UTF8, "application/json"); 977 | return request; 978 | } 979 | 980 | public Task SendHttpRequestAsync(HttpRequestMessage request, params HttpStatusCode[] expectedStatusCodes) 981 | { 982 | return SendHttpRequestAsync(request, null, expectedStatusCodes); 983 | } 984 | 985 | public Task SendHttpRequestAsync(HttpRequestMessage request, string commandDescription, params HttpStatusCode[] expectedStatusCodes) 986 | { 987 | if (jsonStreamingAvailable) 988 | { 989 | request.Headers.Accept.Clear(); 990 | request.Headers.Remove("Accept"); 991 | request.Headers.Add("Accept", "application/json;stream=true"); 992 | request.Headers.Remove("Accept-Encoding"); 993 | request.Headers.Add("Accept-Encoding", "UTF-8"); 994 | } 995 | 996 | var assemblyVersion = GetType().Assembly.GetName().Version; 997 | var userAgent = string.Format("Neo4jClient/{0}", "1.0.0.498"); 998 | request.Headers.Add("User-Agent", userAgent); 999 | 1000 | return httpClient.SendAsync(request); 1001 | } 1002 | 1003 | public event OperationCompletedEventHandler OperationCompleted; 1004 | 1005 | protected void OnOperationCompleted(OperationCompletedEventArgs args) 1006 | { 1007 | var eventInstance = OperationCompleted; 1008 | if (eventInstance != null) 1009 | eventInstance(this, args); 1010 | } 1011 | 1012 | public async Task SendHttpRequestAndParseResultAs(HttpRequestMessage request, params HttpStatusCode[] expectedStatusCodes) where T : new() 1013 | { 1014 | return await SendHttpRequestAndParseResultAs(request, null, expectedStatusCodes); 1015 | } 1016 | 1017 | async Task SendHttpRequest(HttpRequestMessage request, params HttpStatusCode[] expectedStatusCodes) 1018 | { 1019 | return await SendHttpRequest(request, null, expectedStatusCodes); 1020 | } 1021 | 1022 | Task SendHttpRequest(HttpRequestMessage request, string commandDescription, params HttpStatusCode[] expectedStatusCodes) 1023 | { 1024 | var task = SendHttpRequestAsync(request, commandDescription, expectedStatusCodes); 1025 | return task; 1026 | } 1027 | 1028 | async Task SendHttpRequestAndParseResultAs(HttpRequestMessage request, string commandDescription, params HttpStatusCode[] expectedStatusCodes) where T : new() 1029 | { 1030 | request.Headers.Remove("Accept-Encoding"); 1031 | request.Headers.Add("Accept-Encoding", "UTF-8"); 1032 | 1033 | var response = SendHttpRequest(request, commandDescription, expectedStatusCodes).Result; 1034 | 1035 | return response.Content == null ? default(T) : await response.Content.ReadAsJson(); 1036 | } 1037 | 1038 | HttpRequestMessage HttpGet(string relativeUri) 1039 | { 1040 | var absoluteUri = BuildUri(relativeUri); 1041 | using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, absoluteUri)) 1042 | { 1043 | return new HttpRequestMessage(HttpMethod.Get, absoluteUri); 1044 | } 1045 | 1046 | } 1047 | 1048 | bool jsonStreamingAvailable; 1049 | 1050 | public void Connect() 1051 | { 1052 | var stopwatch = new Stopwatch(); 1053 | stopwatch.Start(); 1054 | 1055 | HttpRequestMessage request = HttpGet(""); 1056 | 1057 | RootApiResponse = SendHttpRequestAndParseResultAs(request, HttpStatusCode.OK).Result; 1058 | RootApiResponse.Batch = RootApiResponse.Batch.Substring(RootUri.AbsoluteUri.Length); 1059 | RootApiResponse.Node = RootApiResponse.Node.Substring(RootUri.AbsoluteUri.Length); 1060 | RootApiResponse.NodeIndex = RootApiResponse.NodeIndex.Substring(RootUri.AbsoluteUri.Length); 1061 | RootApiResponse.RelationshipIndex = RootApiResponse.RelationshipIndex.Substring(RootUri.AbsoluteUri.Length); 1062 | RootApiResponse.ExtensionsInfo = RootApiResponse.ExtensionsInfo.Substring(RootUri.AbsoluteUri.Length); 1063 | if (RootApiResponse.Extensions != null && RootApiResponse.Extensions.GremlinPlugin != null) 1064 | { 1065 | RootApiResponse.Extensions.GremlinPlugin.ExecuteScript = 1066 | RootApiResponse.Extensions.GremlinPlugin.ExecuteScript.Substring(RootUri.AbsoluteUri.Length); 1067 | } 1068 | 1069 | if (RootApiResponse.Cypher != null) 1070 | { 1071 | RootApiResponse.Cypher = 1072 | RootApiResponse.Cypher.Substring(RootUri.AbsoluteUri.Length); 1073 | } 1074 | 1075 | jsonStreamingAvailable = RootApiResponse.Version >= new Version(1, 8); 1076 | 1077 | stopwatch.Stop(); 1078 | OnOperationCompleted(new OperationCompletedEventArgs 1079 | { 1080 | QueryText = "Connect", 1081 | ResourcesReturned = 0, 1082 | TimeTaken = stopwatch.Elapsed 1083 | }); 1084 | } 1085 | 1086 | public CypherFluentQueryCreator Or() 1087 | { 1088 | throw new NotImplementedException(); 1089 | } 1090 | 1091 | 1092 | } 1093 | 1094 | public class HttpClientWrapper : IHttpClient 1095 | { 1096 | readonly HttpClient client; 1097 | 1098 | public string Uri { get { return client.BaseAddress.ToString(); } set { client.BaseAddress = new Uri(value); } } 1099 | 1100 | public HttpClientWrapper() : this(new HttpClient()) { } 1101 | 1102 | public HttpClientWrapper(HttpClient client) 1103 | { 1104 | this.client = client; 1105 | } 1106 | 1107 | public Task SendAsync(HttpRequestMessage request) 1108 | { 1109 | if (request.RequestUri.ToString().Contains(Configuration.GetDatabaseUri())) 1110 | { 1111 | client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(Configuration.GetAuthorizationHeader()))); 1112 | } 1113 | else 1114 | { 1115 | client.DefaultRequestHeaders.Authorization = null; 1116 | } 1117 | 1118 | try 1119 | { 1120 | if (request.Method == HttpMethod.Post) 1121 | { 1122 | return client.PostAsync(request.RequestUri, request.Content).ContinueWith((requestTask) => 1123 | { 1124 | HttpResponseMessage response = requestTask.Result; 1125 | response.EnsureSuccessStatusCode(); 1126 | return response; 1127 | }); 1128 | } 1129 | else 1130 | { 1131 | return client.SendAsync(request).ContinueWith((requestTask) => 1132 | { 1133 | HttpResponseMessage response = requestTask.Result; 1134 | response.EnsureSuccessStatusCode(); 1135 | 1136 | return response; 1137 | }); 1138 | } 1139 | } 1140 | catch (Exception ex) 1141 | { 1142 | throw ex; 1143 | } 1144 | } 1145 | } 1146 | 1147 | public class CypherApiQuery 1148 | { 1149 | readonly string queryText; 1150 | readonly IDictionary queryParameters; 1151 | 1152 | public CypherApiQuery(CypherQuery query) 1153 | { 1154 | queryParameters = new Dictionary(); 1155 | queryText = query.QueryText; 1156 | queryParameters = query.QueryParameters ?? new Dictionary(); 1157 | } 1158 | 1159 | [JsonProperty("query")] 1160 | public string Query 1161 | { 1162 | get { return queryText; } 1163 | } 1164 | 1165 | [JsonProperty("params")] 1166 | public IDictionary Parameters 1167 | { 1168 | get { return queryParameters; } 1169 | } 1170 | } 1171 | 1172 | public static class HttpContentExtensions 1173 | { 1174 | public static async Task ReadAsString(this HttpContent content) 1175 | { 1176 | var readTask = await content.ReadAsStringAsync(); 1177 | return readTask; 1178 | } 1179 | 1180 | public static async Task ReadAsJson(this HttpContent content) where T : new() 1181 | { 1182 | var stringContent = await content.ReadAsString(); 1183 | return JsonConvert.DeserializeObject(stringContent); 1184 | } 1185 | } 1186 | 1187 | public class RootApiResponse 1188 | { 1189 | [JsonProperty("cypher")] 1190 | public string Cypher { get; set; } 1191 | 1192 | [JsonProperty("batch")] 1193 | public string Batch { get; set; } 1194 | 1195 | [JsonProperty("node")] 1196 | public string Node { get; set; } 1197 | 1198 | [JsonProperty("node_index")] 1199 | public string NodeIndex { get; set; } 1200 | 1201 | [JsonProperty("relationship_index")] 1202 | public string RelationshipIndex { get; set; } 1203 | 1204 | [JsonProperty("reference_node")] 1205 | public string ReferenceNode { get; set; } 1206 | 1207 | [JsonProperty("extensions_info")] 1208 | public string ExtensionsInfo { get; set; } 1209 | 1210 | [JsonProperty("extensions")] 1211 | public ExtensionsApiResponse Extensions { get; set; } 1212 | 1213 | public string neo4j_version { get; set; } 1214 | 1215 | [JsonIgnore] 1216 | public Version Version 1217 | { 1218 | get 1219 | { 1220 | if (string.IsNullOrEmpty(neo4j_version)) 1221 | return new Version(); 1222 | 1223 | switch (neo4j_version) 1224 | { 1225 | case "1.8.RC1": return new Version(1, 8, 0, 8); 1226 | } 1227 | 1228 | var numericalVersionString = Regex.Replace( 1229 | neo4j_version, 1230 | @"(?\d*)[.](?\d*)[.]?M(?\d*).*", 1231 | "${major}.${minor}.0.${build}"); 1232 | 1233 | numericalVersionString = Regex.Replace( 1234 | numericalVersionString, 1235 | @"(?\d*)[.](?\d*)-.*", 1236 | "${major}.${minor}"); 1237 | 1238 | Version result; 1239 | var parsed = Version.TryParse(numericalVersionString, out result); 1240 | 1241 | return parsed ? result : new Version(0, 0); 1242 | } 1243 | } 1244 | 1245 | public class ExtensionsApiResponse 1246 | { 1247 | public GremlinPluginApiResponse GremlinPlugin { get; set; } 1248 | } 1249 | 1250 | public class GremlinPluginApiResponse 1251 | { 1252 | [JsonProperty("execute_script")] 1253 | public string ExecuteScript { get; set; } 1254 | } 1255 | 1256 | [JsonObject] 1257 | public class BatchResponseExtensions 1258 | { 1259 | } 1260 | 1261 | [JsonObject] 1262 | public class BatchResponseData 1263 | { 1264 | [JsonProperty] 1265 | public string Key { get; set; } 1266 | [JsonProperty] 1267 | public string Content { get; set; } 1268 | [JsonProperty] 1269 | public string Weight { get; set; } 1270 | [JsonProperty] 1271 | public string EndPoint { get; set; } 1272 | } 1273 | 1274 | [JsonObject] 1275 | public class BatchResponseBody 1276 | { 1277 | [JsonProperty] 1278 | public BatchResponseExtensions extensions { get; set; } 1279 | [JsonProperty] 1280 | public string paged_traverse { get; set; } 1281 | [JsonProperty] 1282 | public string outgoing_relationships { get; set; } 1283 | [JsonProperty] 1284 | public string all_typed_relationships { get; set; } 1285 | [JsonProperty] 1286 | public string traverse { get; set; } 1287 | [JsonProperty] 1288 | public string all_relationships { get; set; } 1289 | [JsonProperty] 1290 | public string property { get; set; } 1291 | [JsonProperty] 1292 | public string self { get; set; } 1293 | [JsonProperty] 1294 | public string outgoing_typed_relationships { get; set; } 1295 | [JsonProperty] 1296 | public string properties { get; set; } 1297 | [JsonProperty] 1298 | public string incoming_relationships { get; set; } 1299 | [JsonProperty] 1300 | public string incoming_typed_relationships { get; set; } 1301 | [JsonProperty] 1302 | public string create_relationship { get; set; } 1303 | [JsonProperty] 1304 | public BatchResponseData data { get; set; } 1305 | [JsonProperty] 1306 | public string start { get; set; } 1307 | [JsonProperty] 1308 | public string type { get; set; } 1309 | [JsonProperty] 1310 | public string end { get; set; } 1311 | } 1312 | 1313 | [JsonObject] 1314 | public class BatchResponseObject 1315 | { 1316 | [JsonProperty] 1317 | public int id { get; set; } 1318 | [JsonProperty] 1319 | public string from { get; set; } 1320 | [JsonProperty] 1321 | public BatchResponseBody body { get; set; } 1322 | [JsonProperty] 1323 | public string location { get; set; } 1324 | [JsonProperty] 1325 | public int status { get; set; } 1326 | [JsonProperty] 1327 | public string message { get; set; } 1328 | } 1329 | 1330 | 1331 | } 1332 | } -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/License.txt: -------------------------------------------------------------------------------- 1 | http://www.opensource.org/licenses/MS-PL 2 | 3 | Microsoft Public License (MS-PL) 4 | 5 | This license governs use of the accompanying software. If you use the software, you 6 | accept this license. If you do not accept the license, do not use the software. 7 | 8 | 1. Definitions 9 | The terms "reproduce," "reproduction," "derivative works," and "distribution" have the 10 | same meaning here as under U.S. copyright law. 11 | A "contribution" is the original software, or any additions or changes to the software. 12 | A "contributor" is any person that distributes its contribution under this license. 13 | "Licensed patents" are a contributor's patent claims that read directly on its contribution. 14 | 15 | 2. Grant of Rights 16 | (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. 17 | (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 18 | 19 | 3. Conditions and Limitations 20 | (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. 21 | (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. 22 | (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. 23 | (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. 24 | (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 25 | 26 | -- 27 | 28 | Author: Kenny Bastani 29 | Website: https://github.com/kbastani/predictive-autocomplete -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/PredictiveAutocomplete.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9F4BF250-ACCD-4471-91C3-DBC8862E72AC} 8 | Library 9 | Properties 10 | PredictiveAutocomplete 11 | PredictiveAutocomplete 12 | v4.5 13 | 512 14 | SAK 15 | SAK 16 | SAK 17 | SAK 18 | ..\ 19 | true 20 | 21 | 22 | true 23 | full 24 | false 25 | bin\Debug\ 26 | DEBUG;TRACE 27 | prompt 28 | 4 29 | 30 | 31 | pdbonly 32 | true 33 | bin\Release\ 34 | TRACE 35 | prompt 36 | 4 37 | 38 | 39 | 40 | ..\packages\Microsoft.Data.Edm.5.2.0\lib\net40\Microsoft.Data.Edm.dll 41 | 42 | 43 | ..\packages\Microsoft.Data.OData.5.2.0\lib\net40\Microsoft.Data.OData.dll 44 | 45 | 46 | ..\packages\Microsoft.WindowsAzure.ConfigurationManager.2.0.1.0\lib\net40\Microsoft.WindowsAzure.Configuration.dll 47 | 48 | 49 | False 50 | ..\packages\WindowsAzure.Storage.2.1.0.0\lib\net40\Microsoft.WindowsAzure.Storage.dll 51 | 52 | 53 | packages\Neo4jClient.1.0.0.594\lib\net40\Neo4jClient.dll 54 | 55 | 56 | packages\Newtonsoft.Json.5.0.6\lib\net45\Newtonsoft.Json.dll 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | packages\Microsoft.Net.Http.2.2.13\lib\net45\System.Net.Http.Extensions.dll 66 | 67 | 68 | packages\Microsoft.Net.Http.2.2.13\lib\net45\System.Net.Http.Primitives.dll 69 | 70 | 71 | 72 | ..\packages\System.Spatial.5.2.0\lib\net40\System.Spatial.dll 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 107 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/Processor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.WindowsAzure.Storage; 2 | using Neo4jClient; 3 | using PredictiveAutocomplete.Services; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Net.Http; 9 | using System.Text; 10 | using System.Text.RegularExpressions; 11 | using System.Threading.Tasks; 12 | using System.Web.Script.Serialization; 13 | 14 | namespace PredictiveAutocomplete 15 | { 16 | 17 | /// 18 | /// The IGraphNode interface provides contract for the autocomplete query object in the JSON file index. 19 | /// 20 | public interface IGraphNode 21 | { 22 | string label { get; set; } 23 | int size { get; set; } 24 | } 25 | 26 | public class Processor 27 | { 28 | 29 | /// 30 | /// Index an autocomplete query to blob storage container that is accessible over public HTTP. 31 | /// 32 | /// A list of queries to be added to the index. Queries are ranked on A.size. 33 | /// The Windows Azure cloud storage account that will be used for blob storage. 34 | /// The container name that will be used. This container must have public accessibility. 35 | /// 36 | /// The number of results maximum that should be indexed per file. 37 | /// If you only want 5 results maximum to display in your search box then set this value to 5. 38 | /// 39 | /// The max length property is the number of symbols to index per supplied query key. 40 | /// If you do not expect queries to be ambiguous beyond a certain length, it is advisible to set this value to correspond with the volume of query keys in your index. 41 | /// For example if 40 character queries only have 1 result over the entire index then set this property to 40. 42 | /// 43 | public static void IndexAutoCompleteKey(List queryKey, CloudStorageAccount storage, string cacheId, int resultsPerFile, int maxLength) 44 | { 45 | try 46 | { 47 | queryKey.AsParallel().ForAll(phrs => AutoCompleteProcessor(phrs, storage, cacheId, maxLength)); 48 | } 49 | catch (Exception ex) 50 | { 51 | throw ex; 52 | } 53 | 54 | } 55 | 56 | /// 57 | /// This method handles the core workflow for adding a query key to blob storage JSON file autocomplete repository. 58 | /// 59 | /// The query key to be added to the JSON file autocomplete repository. 60 | /// The Windows Azure storage account for blob storage access. 61 | /// The public container's name on Windows Azure storage account. 62 | /// The maximum character length that will be used to index the JSON files per symbol. 63 | private static void AutoCompleteProcessor(IGraphNode queryKey, CloudStorageAccount storage, string cacheId, int maxLength) 64 | { 65 | 66 | string containerId = cacheId; 67 | 68 | // Use paralellization for character combinations up to 5 characters 69 | List keyList = new List(); 70 | 71 | // Key list 72 | for (int i = 0; i < Math.Min(queryKey.label.Length, maxLength); i++) 73 | { 74 | keyList.Add(queryKey.label.Substring(0, i + 1).ToUpperInvariant()); 75 | } 76 | 77 | keyList.AsParallel().ForAll(key => 78 | { 79 | // Retrieve files from cloud storage 80 | Stream blobStream = BlobService.GetBlob(storage, containerId, "cache/" + key.ToLowerInvariant()); 81 | 82 | if (blobStream == null) 83 | { 84 | // Create the blob 85 | blobStream = CreateAutocompleteBlob(queryKey, storage, containerId, key); 86 | } 87 | else 88 | { 89 | // Deserialize the stream from blob storage 90 | JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); 91 | try 92 | { 93 | // Update the blob stream for this key 94 | var acBlock = UpdateBlobStreamForKey(queryKey, maxLength, blobStream, jsSerializer); 95 | 96 | // Acquire lease on the blob and update the blocks in parallel 97 | blobStream = UpdateJsonBlockBlob(storage, containerId, key, jsSerializer, acBlock); 98 | } 99 | catch (Exception) 100 | { 101 | // TODO: LOG EXCEPTION OR HANDLE 102 | 103 | // Attempt to recreate the blob if it has been corrupted 104 | blobStream = CreateAutocompleteBlob(queryKey, storage, containerId, key); 105 | } 106 | } 107 | }); 108 | } 109 | 110 | /// 111 | /// Update the JSON file and its stream on blob storage. 112 | /// 113 | /// The query key to update the JSON file index. 114 | /// The maximum character length to index for each query key. 115 | /// The stream for the JSON file. 116 | /// For JSON serialization and deserialization. 117 | /// 118 | private static GraphNode[] UpdateBlobStreamForKey(IGraphNode queryKey, int maxLength, Stream blobStream, JavaScriptSerializer jsSerializer) 119 | { 120 | var acBlock = jsSerializer.Deserialize(Regex.Replace(new StreamReader(blobStream).ReadToEnd(), @"^dataCallback\(|\)$", "", RegexOptions.IgnoreCase)); 121 | var acKey = new GraphNode() { label = queryKey.label.ToLowerInvariant(), size = queryKey.size }; 122 | 123 | // Check for key phrase 124 | var hasKey = acBlock.ToList().Any(aKey => aKey.label.Equals(acKey.label, StringComparison.InvariantCultureIgnoreCase)); 125 | 126 | // Update key weight and pushed back to storage 127 | if (hasKey) 128 | { 129 | acBlock = UpdateOrderedJsonBlock(maxLength, acKey, acBlock); 130 | } 131 | else 132 | { 133 | acBlock = GetOrderedJsonBlock(maxLength, acKey, acBlock); 134 | } 135 | 136 | return acBlock; 137 | } 138 | 139 | /// 140 | /// Update the JSON block blob using the blob service class. Manages concurrent access conditions for parallel transactions. 141 | /// 142 | /// The cloud storage account on Windows Azure platform. 143 | /// The public container id on the cloud storage account. 144 | /// The partial key query to index for. 145 | /// The serialization library to manage converting the JSON string to raw bytes. 146 | /// The list of graph nodes ordered by size. 147 | /// 148 | private static Stream UpdateJsonBlockBlob(CloudStorageAccount storage, string containerId, string key, JavaScriptSerializer jsSerializer, GraphNode[] acBlock) 149 | { 150 | Stream blobStream; 151 | var jsonString = string.Format("dataCallback({0})", jsSerializer.Serialize(acBlock)); 152 | blobStream = new MemoryStream(); 153 | var bytes = Encoding.UTF8.GetBytes(jsonString); 154 | blobStream.Write(bytes, 0, bytes.Length); 155 | blobStream.Seek(0, SeekOrigin.Begin); 156 | BlobService.PutBlob(storage, containerId, key.ToLowerInvariant(), blobStream, "cache", 0); 157 | return blobStream; 158 | } 159 | 160 | /// 161 | /// Gets an ordered list of graph nodes of a specific length. 162 | /// 163 | /// The maximum character length that will be used for the index. 164 | /// The autocomplete key to potentially be included in this key index. 165 | /// The current list of graph nodes already existing and to be reordered based on the acKey property. 166 | /// Returns an ordered list of key value pairs that represents what will display in the search box for the acKey property. 167 | private static GraphNode[] GetOrderedJsonBlock(int maxLength, GraphNode acKey, GraphNode[] acBlock) 168 | { 169 | List acBlockList = acBlock.ToList(); 170 | 171 | acBlockList.Add(acKey); 172 | 173 | acBlockList = acBlockList 174 | .OrderByDescending(acbk => acbk.size) 175 | .ToList() 176 | .Take(maxLength) 177 | .ToList(); 178 | 179 | acBlock = acBlockList.ToArray(); 180 | return acBlock; 181 | } 182 | 183 | /// 184 | /// Gets an updated and ordered list of graph nodes of a specific length. 185 | /// 186 | /// The maximum character length that will be used for the index. 187 | /// The autocomplete key to potentially be included in this key index. 188 | /// The current list of graph nodes already existing and to be reordered based on the acKey property. 189 | /// Returns an ordered list of key value pairs that represents what will display in the search box for the acKey property. 190 | private static GraphNode[] UpdateOrderedJsonBlock(int maxLength, GraphNode acKey, GraphNode[] acBlock) 191 | { 192 | var keyIndex = acBlock 193 | .ToList() 194 | .IndexOf(acBlock 195 | .Where(aKey => aKey.label.Equals(acKey.label, StringComparison.InvariantCultureIgnoreCase)) 196 | .First()); 197 | 198 | acBlock[keyIndex] = acKey; 199 | 200 | var acBlockList = acBlock.ToList(); 201 | 202 | acBlockList = acBlockList 203 | .OrderByDescending(acbk => acbk.size) 204 | .ToList() 205 | .Take(maxLength) 206 | .ToList(); 207 | 208 | acBlock = acBlockList 209 | .ToArray(); 210 | return acBlock; 211 | } 212 | 213 | /// 214 | /// Create a new autocomplete JSON file for this key value. 215 | /// 216 | /// The new autocomplete result that is unique to this new key index. 217 | /// The Windows Azure storage account. 218 | /// The public container id on Windows Azure. 219 | /// The partial query key to collate autocomplete results for. 220 | /// Returns the blob stream of the JSON file that was just created. Returns null if the operation failed. Make sure to handle memory considerations by disposing or closing the stream. 221 | private static Stream CreateAutocompleteBlob(IGraphNode queryKey, CloudStorageAccount storage, string containerId, string key) 222 | { 223 | Stream blobStream; 224 | // Create new serialized autocomplete model containing phrase and weight data 225 | JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); 226 | var acBlock = new List() { key }.Select(kv => new GraphNode() { label = queryKey.label.ToLowerInvariant(), size = queryKey.size }).ToArray(); 227 | var jsonString = string.Format("dataCallback({0})", jsSerializer.Serialize(acBlock)); 228 | blobStream = new MemoryStream(); 229 | var bytes = Encoding.UTF8.GetBytes(jsonString); 230 | blobStream.Write(bytes, 0, bytes.Length); 231 | blobStream.Seek(0, SeekOrigin.Begin); 232 | BlobService.PutBlob(storage, containerId, key.ToLowerInvariant(), blobStream, "cache", 0); 233 | return blobStream; 234 | } 235 | 236 | /// 237 | /// Get HTTP client wrapper for access to authenticated Neo4j graph database using the Neo4jClient library. 238 | /// 239 | /// 240 | public static Neo4jClient.HttpClientWrapper GetNeo4jAuthenticatedClient() 241 | { 242 | // Get authentication header from configuration 243 | var authentication = Configuration.GetAuthorizationHeader(); 244 | 245 | HttpClient httpClient = new HttpClient(); 246 | httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", Convert.ToBase64String(Encoding.ASCII.GetBytes(authentication))); 247 | Neo4jClient.HttpClientWrapper clientWrapper = new Neo4jClient.HttpClientWrapper(httpClient); 248 | return clientWrapper; 249 | } 250 | 251 | /// 252 | /// Retrieve the GraphClient object for the Neo4j graph database configured in application settings. 253 | /// 254 | /// Returns Neo4jClient .NET wrapper for data store management of a graph database instance managed over HTTP. 255 | public static GraphClient GetNeo4jGraphClient() 256 | { 257 | Neo4jClient.HttpClientWrapper clientWrapper = Processor.GetNeo4jAuthenticatedClient(); 258 | Neo4jClient.GraphClient graphClient = new Neo4jClient.GraphClient(new Uri(Configuration.GetDatabaseUri()), clientWrapper); 259 | return graphClient; 260 | } 261 | 262 | 263 | /// 264 | /// Get ranked nodes from Neo4j graph database using a templated cypher query that queries an index using a supplied valid lucene query. 265 | /// Each node in the index has a weight rating by specifying a relationship name which is used to determine the 266 | /// distinct number of incoming links to each node in your query with that relationship name. 267 | /// You must specify the valid property name that is to be used as the label for the autocomplete search. 268 | /// For example, if you are querying a database of books and wanted to list the names of books in the 269 | /// autocomplete search, then the label property would be "Title" where each book node b has b.Title as the book name. 270 | /// 271 | /// The case sensitive Neo4j node index name that you want to query. 272 | /// The valid lucene query that you want to use to query the supplied index. 273 | /// 274 | /// The relationship name that will be used to determine the number of incoming links to each node you are querying for. 275 | /// Leave blank if you want to query all incoming links regardless of relationship type. 276 | /// The label property name for each of your Neo4j nodes. See method summary for details. 277 | /// Skip a number of a nodes, ordered by the Neo4j assigned node id of each node you are querying for. Use this for processing batches on large graph queries. 278 | /// Limit the number of results you would like returned. Use this in combination with the skip property to process batches on large graph queries. 279 | /// Returns a list of nodes that implements IGraphNode interface, having a label and size property for ranking result order. 280 | public static List GetRankedNodesForQuery(string index, string luceneQuery, string relationshipLabel, string labelPropertyName, int skip, int limit) 281 | { 282 | var sb = new StringBuilder(); 283 | sb.AppendLine("START node=node:{0}(\"{1}\")"); 284 | sb.AppendLine("WITH node"); 285 | sb.AppendLine("SKIP {2}"); 286 | sb.AppendLine("LIMIT {3}"); 287 | sb.AppendLine("WITH node"); 288 | sb.AppendLine("MATCH n-[{4}]->node"); 289 | sb.AppendLine("WITH node, count(distinct n) as size"); 290 | sb.AppendLine("RETURN node.{5}? as label, size"); 291 | sb.AppendLine("ORDER BY id(node)"); 292 | sb.AppendLine("LIMIT {3}"); 293 | 294 | string commandQuery = sb.ToString(); 295 | 296 | commandQuery = string.Format(commandQuery, index, luceneQuery, skip, limit, !string.IsNullOrEmpty(relationshipLabel) ? string.Format(":{0}", relationshipLabel) : string.Empty, labelPropertyName); 297 | 298 | GraphClient graphClient = GetNeo4jGraphClient(); 299 | 300 | var cypher = new CypherFluentQueryCreator(graphClient, new CypherQueryCreator(commandQuery), new Uri(Configuration.GetDatabaseUri())); 301 | 302 | var resulttask = cypher.ExecuteGetCypherResults(); 303 | var graphNodeResults = resulttask.Result.ToList().Select(gn => (IGraphNode)gn).ToList(); 304 | return graphNodeResults; 305 | } 306 | } 307 | 308 | 309 | /// 310 | /// This class represents a graph node that is ranked on size and has a unique label. 311 | /// 312 | public class GraphNode : IGraphNode 313 | { 314 | string _label; 315 | int _size; 316 | 317 | public string label 318 | { 319 | get 320 | { 321 | return _label; 322 | } 323 | set 324 | { 325 | _label = value; 326 | } 327 | } 328 | 329 | public int size 330 | { 331 | get 332 | { 333 | return _size; 334 | } 335 | set 336 | { 337 | _size = value; 338 | } 339 | } 340 | } 341 | } 342 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("PredictiveAutocomplete")] 9 | [assembly: AssemblyDescription("Generates a ranked predictive autocomplete index of JSON files accessible over HTTP for search engine text box query completion using Neo4j graph database and Windows Azure cloud storage account.")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("Socialmoon, Inc.")] 12 | [assembly: AssemblyProduct("PredictiveAutocomplete")] 13 | [assembly: AssemblyCopyright("Copyright © 2013 Socialmoon")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("377cc011-ff8f-46a4-b9d7-8377c9dd61c9")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/Services/BlobService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.WindowsAzure.Storage; 2 | using Microsoft.WindowsAzure.Storage.Blob; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Web; 10 | 11 | namespace PredictiveAutocomplete.Services 12 | { 13 | public class BlobService 14 | { 15 | public static Stream GetBlob(CloudStorageAccount storage, string blobFolder, string query) 16 | { 17 | CloudBlobClient blobClient = storage.CreateCloudBlobClient(); 18 | CloudBlobContainer blobContainer = blobClient.ListContainers(blobFolder, ContainerListingDetails.All).FirstOrDefault(); 19 | if (blobContainer == null) 20 | { 21 | return null; 22 | } 23 | 24 | CloudBlockBlob blob = blobContainer.GetBlockBlobReference(query); 25 | 26 | if (Exists(blob)) 27 | { 28 | Encoding encoding = Encoding.UTF8; 29 | MemoryStream memoryStream = new MemoryStream(); 30 | blob.DownloadToStream(memoryStream); 31 | memoryStream.Seek(0, SeekOrigin.Begin); 32 | return memoryStream; 33 | } 34 | else 35 | { 36 | return null; 37 | } 38 | } 39 | 40 | public static bool PutBlob(CloudStorageAccount storage, string blobFolder, string blobName, Stream blobStream, string query, int tryCount) 41 | { 42 | 43 | try 44 | { 45 | CloudBlobClient blobClient = storage.CreateCloudBlobClient(); 46 | CloudBlobContainer blobContainer = blobClient.ListContainers(blobFolder, ContainerListingDetails.All).FirstOrDefault(); 47 | if (blobContainer == null) 48 | { 49 | blobContainer = blobClient.GetContainerReference(blobFolder); 50 | blobContainer.Create(); 51 | } 52 | CloudBlobDirectory blobDirectory = blobContainer.GetDirectoryReference(HttpUtility.UrlDecode(query)); 53 | CloudBlockBlob cloudBlob = blobDirectory.GetBlockBlobReference(blobName); 54 | 55 | string newLeaseId = Guid.NewGuid().ToString(); 56 | 57 | var accessCondition = AccessCondition.GenerateLeaseCondition(newLeaseId); 58 | 59 | bool cloudBlobExists = false; 60 | 61 | try 62 | { 63 | bool exists = cloudBlob.Exists(); 64 | cloudBlobExists = exists; 65 | } 66 | catch 67 | { 68 | cloudBlobExists = false; 69 | } 70 | 71 | if (cloudBlobExists ? !string.IsNullOrEmpty(cloudBlob.AcquireLease(TimeSpan.FromSeconds(30), accessCondition.LeaseId, accessCondition)) : true) 72 | { 73 | byte[] content = new byte[blobStream.Length]; 74 | blobStream.Read(content, 0, (int)blobStream.Length); 75 | var blockLength = 400 * 1024; 76 | var numberOfBlocks = ((int)content.Length / blockLength) + 1; 77 | string[] blockIds = new string[numberOfBlocks]; 78 | 79 | try 80 | { 81 | Parallel.For(0, numberOfBlocks, x => 82 | { 83 | var blockId = Convert.ToBase64String(Guid.NewGuid().ToByteArray()); 84 | var currentLength = Math.Min(blockLength, content.Length - (x * blockLength)); 85 | 86 | using (var memStream = new MemoryStream(content, x * blockLength, currentLength)) 87 | { 88 | if (cloudBlobExists) 89 | { 90 | try 91 | { 92 | cloudBlob.PutBlock(blockId, memStream, "", accessCondition); 93 | } 94 | catch (Exception) 95 | { 96 | cloudBlob.PutBlock(blockId, memStream, ""); 97 | } 98 | } 99 | else 100 | { 101 | cloudBlob.PutBlock(blockId, memStream, ""); 102 | } 103 | 104 | } 105 | blockIds[x] = blockId; 106 | }); 107 | } 108 | catch (Exception ex) 109 | { 110 | throw new Exception(string.Format("Parallel put block error occurred: {0}", ex.Message), ex); 111 | } 112 | 113 | 114 | if (cloudBlobExists) 115 | { 116 | cloudBlob.AcquireLease(TimeSpan.FromSeconds(30), accessCondition.LeaseId, accessCondition); 117 | 118 | cloudBlob.PutBlockList(blockIds, accessCondition, new BlobRequestOptions() { RetryPolicy = new Microsoft.WindowsAzure.Storage.RetryPolicies.LinearRetry() }); 119 | 120 | // Set properties 121 | cloudBlob.Properties.ContentType = "application/json"; 122 | cloudBlob.SetProperties(accessCondition); 123 | 124 | // Quickly clear this data from memory 125 | blobStream.Dispose(); 126 | 127 | cloudBlob.ReleaseLease(accessCondition); 128 | } 129 | else 130 | { 131 | cloudBlob.PutBlockList(blockIds, null, new BlobRequestOptions() { RetryPolicy = new Microsoft.WindowsAzure.Storage.RetryPolicies.LinearRetry() }); 132 | 133 | // Set properties 134 | cloudBlob.Properties.ContentType = "application/json"; 135 | cloudBlob.SetProperties(); 136 | 137 | // Quickly clear this data from memory 138 | blobStream.Dispose(); 139 | } 140 | } 141 | } 142 | catch 143 | { 144 | if (tryCount < 10) 145 | { 146 | PutBlob(storage, blobFolder, blobName, blobStream, query, tryCount + 1); 147 | } 148 | } 149 | 150 | return (!(tryCount >= 10)); 151 | } 152 | 153 | 154 | public static bool Exists(CloudBlockBlob blob) 155 | { 156 | try 157 | { 158 | blob.FetchAttributes(); 159 | return true; 160 | } 161 | catch (StorageException) 162 | { 163 | return false; 164 | } 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete_Test/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete_Test/PredictiveAutocomplete_Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {D48761DB-F0DC-43C7-8E5B-AB6D8BABA74D} 8 | Exe 9 | Properties 10 | PredictiveAutocomplete_Test 11 | PredictiveAutocomplete_Test 12 | v4.5 13 | 512 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\Microsoft.Data.Edm.5.2.0\lib\net40\Microsoft.Data.Edm.dll 37 | 38 | 39 | ..\packages\Microsoft.Data.OData.5.2.0\lib\net40\Microsoft.Data.OData.dll 40 | 41 | 42 | ..\packages\Microsoft.WindowsAzure.ConfigurationManager.2.0.1.0\lib\net40\Microsoft.WindowsAzure.Configuration.dll 43 | 44 | 45 | False 46 | ..\packages\WindowsAzure.Storage.2.1.0.0\lib\net40\Microsoft.WindowsAzure.Storage.dll 47 | 48 | 49 | 50 | 51 | 52 | ..\packages\System.Spatial.5.2.0\lib\net40\System.Spatial.dll 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | {9f4bf250-accd-4471-91c3-dbc8862e72ac} 71 | PredictiveAutocomplete 72 | 73 | 74 | 75 | 82 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete_Test/Program.cs: -------------------------------------------------------------------------------- 1 | using PredictiveAutocomplete; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace PredictiveAutocomplete_Tests 9 | { 10 | class Program 11 | { 12 | static void Main(string[] args) 13 | { 14 | List results = Processor.GetRankedNodesForQuery("topic", "phrase:(\\\"MATHEMATICS\\\")", string.Empty, "Key", 0, 20).OrderByDescending(g => g.size).ToList(); 15 | 16 | Processor.IndexAutoCompleteKey(results, Configuration.GetDataConnectionString(), Configuration.GetAutoCompleteCacheId(), 10, 40); 17 | 18 | foreach (var item in results) 19 | { 20 | Console.WriteLine(string.Format("{0} : {1}", item.label, item.size)); 21 | } 22 | 23 | Console.ReadLine(); 24 | } 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete_Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("PredictiveAutocomplete_Test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("PredictiveAutocomplete_Test")] 13 | [assembly: AssemblyCopyright("Copyright © 2013")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("25deef41-016c-4a23-8f55-9ce11ed1059e")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /predictive-autocomplete/PredictiveAutocomplete_Test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | --------------------------------------------------------------------------------