Compare commits

...

235 Commits

Author SHA1 Message Date
Sebastiaan Janssen eda7f1e527 Bump version 2017-09-19 14:17:19 +02:00
Sebastiaan Janssen 018a066f86 U4-10428 Can't drag Image in Image Cropper (in Umbraco 7.6.7) 2017-09-19 14:10:20 +02:00
Sebastiaan Janssen e33a28ac19 Making sure we don't build Belle twice for the documentation 2017-09-19 11:38:20 +02:00
Shannon 0ef57d819c removes uneeded null checks from AuthenticationController for raising UserManager events 2017-09-19 13:31:43 +10:00
Sebastiaan Janssen c321d6dd44 Adds files missing from build output 2017-09-18 16:52:43 +02:00
Sebastiaan Janssen 5d74e61bcf Bump version 2017-09-18 14:16:57 +02:00
Shannon 8b39f495e5 Simplifies the UnlockUser method so we don't have to have it in the BackOfficeUserManager 2017-09-18 19:59:23 +10:00
Shannon d468e346f1 reverts changes made to UmbracoMembershipProvider and adds another virtual internal method that the UsersMembershipProvider overrides, so now all of the event raising is done in the user specific provider. 2017-09-18 19:01:00 +10:00
Shannon 2a10eed059 Moves raising events for reseting/changing password out of the MembershipHelper ChangePassword method and to the places where it is being called 2017-09-18 16:56:43 +10:00
Shannon 4ec04c779a Adds notes about the UnlockUser method as we'll need to change this in 7.7 2017-09-18 16:29:29 +10:00
Shannon 26034fa33f Changes ResetAccessFailedCountAsync in BackOfficeUserManager to use Identity APIs 2017-09-18 16:24:23 +10:00
Shannon 97ddbdb1f0 Makes IdentityAuditEventArgs immutable and injects all required values, makes the events strongly typed. 2017-09-18 16:17:54 +10:00
Shannon Deminick 731c51bfc7 Merge pull request #2200 from abjerner/patch-21
Just had to have #2200 (Danish translations for the user section in Umbraco 7.7)
2017-09-18 15:05:43 +10:00
Shannon Deminick 78cb085e00 Merge pull request #2199 from abjerner/patch-20
Added missing Danish translation for "searchNoResult" in "general
2017-09-18 15:05:01 +10:00
Shannon Deminick f2ea4596d7 Merge pull request #2198 from abjerner/patch-19
Added translations for labels when creating a new partial view
2017-09-18 15:04:10 +10:00
Shannon Deminick f9d5de7af4 Merge pull request #2197 from abjerner/patch-18
Added Danish translation for "remove" in "general"
2017-09-18 15:03:38 +10:00
Anders Bjerner 04c6fd0947 Added Danish translation for "enabled" in the "actions" section
Also used in the new users section
2017-09-17 22:47:05 +02:00
Anders Bjerner 8bcf35734d Added some missing Danish translations for the new user section
There appears to be some hardcoded labels here and there, which may be for another pull request.
2017-09-17 22:45:38 +02:00
Anders Bjerner 4de7da2ac1 Added missing translation for "searchNoResult"
Used in Umbraco's list views when the search query doesn't match any items
2017-09-17 22:24:22 +02:00
Anders Bjerner 67d12ae2ca Added translations for labels when creating a new partial view
I think "partial view" and "snippet" still makes sense in Danish, so I've only translated the text around it.
2017-09-17 22:17:37 +02:00
Anders Bjerner e8ba069051 Added Danish translation for "remove" in "general"
The Danish translation is missing in both 7.6 and 7.7 beta. The label is used by the new content picker (and probably other parts of Umbraco as well):

![image](https://user-images.githubusercontent.com/3634580/30523147-64c23ce0-9bdc-11e7-9a48-8d2de93fce72.png)
2017-09-17 19:15:02 +02:00
Sebastiaan Janssen a3457d2498 Merge pull request #1923 from umbraco/temp-U4-8634
U4-8634 Usermanagement - Proper auditing of user events instead of just adding log entries
2017-09-15 15:13:14 +02:00
Sebastiaan Janssen 388d660e11 Raise event when login succeeds after 2FA challenge. Raise event when locked out during 2FA attempts. 2017-09-15 15:12:40 +02:00
Sebastiaan Janssen b6dbc245e2 Merge branch 'dev-v7' into temp-U4-8634 2017-09-15 13:57:46 +02:00
Sebastiaan Janssen 3efba6b576 Update title of preview window 2017-09-15 13:52:26 +02:00
Sebastiaan Janssen 54407a66a4 Fixes canvas designer 2017-09-15 13:50:43 +02:00
Sebastiaan Janssen bca46f11ad Makes the sort order input same size as the one on tabs 2017-09-14 16:11:23 +02:00
Warren Buckley a86b8f786d Merge pull request #1817 from marcemarc/temp-U4-6738
Relates to Issue U4-6738 - Allow viewing/sorting of composition properties.
2017-09-14 14:55:48 +01:00
Warren Buckley ac3eaf43cb Forgot to revert the logic for the extra button/label click to show the sort order on properties 2017-09-14 14:16:47 +01:00
Robert f6d4170010 Merge pull request #1633 from bjarnef/dev-v7-U4-9149
fixes: U4-9149 - Fix z-index of focal point
2017-09-14 15:15:51 +02:00
Warren Buckley 2b0ea45da9 Remove the extra button/click in the UI & show the property sortOrder value when we are sorting 2017-09-14 14:13:42 +01:00
Warren Buckley 07d05c9e0d Revert "toggle the show ordinals label button to hide, when in show ordinal mode"
This reverts commit 51215f11af.
2017-09-14 14:09:00 +01:00
Warren Buckley 26a5682a14 Revert "add language translations keys for showOrdinals and hideOrdinals"
This reverts commit 8ab2f7c257.
2017-09-14 14:08:00 +01:00
Sebastiaan Janssen f3fc2bcfb8 Merge pull request #2177 from umbraco/temp-U4-10384
U4-10384 Error when changing content type on media item
2017-09-14 13:46:32 +02:00
Robert c8d49ed5a7 Merge pull request #2195 from umbraco/temp-U4-10413
fixes: U4-10413 Composition/Reorder bar gets in the way when editing …
2017-09-14 11:41:04 +02:00
Mads Rasmussen 9c2b0a3ef6 fixes: U4-10413 Composition/Reorder bar gets in the way when editing or adding a property 2017-09-14 11:04:34 +02:00
Stephan 9355a81716 comments 2017-09-14 10:08:35 +02:00
Per Ploug 87575e9067 Reverting grid config 2017-09-14 10:04:04 +02:00
Sebastiaan Janssen a5b31e94b6 Merge pull request #2194 from umbraco/temp-U4-10409
temp - vsts troubleshooting
2017-09-14 09:32:04 +02:00
Shannon Deminick f9e094a00a Merge pull request #2193 from gunnim/dev-v7
U4-9562 - HealthCheckResolver from internal to public
2017-09-14 15:36:13 +10:00
Gunnar Már Óttarsson 053175a5a6 Fix http://issues.umbraco.org/issue/U4-9562
Change HealthCheckResolver to public allowing DI
2017-09-13 19:24:46 +00:00
Stephan ce7488a924 temp - vsts troubleshooting 2017-09-13 18:23:19 +02:00
Sebastiaan Janssen f442599633 Merge pull request #2191 from umbraco/temp-U4-10409
U4-10409 UDI Parsing should not require scanning assemblies
2017-09-13 17:28:33 +02:00
Sebastiaan Janssen 37b6b42570 Merge branch 'temp-U4-10409' of https://github.com/umbraco/Umbraco-CMS into temp-U4-10409 2017-09-13 17:20:49 +02:00
Stephan f1149fb826 U4-10409 - revert unwanted files 2017-09-13 17:20:06 +02:00
Sebastiaan Janssen 3f8f96e8c3 Merge branch 'dev-v7' into temp-U4-10409 2017-09-13 17:18:09 +02:00
Sebastiaan Janssen a75181bd7f Update sln to not refer to old build scripts any more 2017-09-13 13:07:22 +02:00
Sebastiaan Janssen 00b469b61b Easy ps script to just update the Umbraco version without having to do a full build 2017-09-13 12:07:29 +02:00
Sebastiaan Janssen 83f08538c2 U4-10407 We should log unhandled exceptions that occur in webapi controllers and always have detailed errors returned to users even when not in debug mode
# Conflicts:
#	src/Umbraco.Web/WebApi/UmbracoAuthorizedApiController.cs
2017-09-13 12:05:02 +02:00
Stephan ef91e152b4 U4-10409 - udi parsing and assembly scanning 2017-09-13 12:00:56 +02:00
Stephan add0685d3f U4-10409 - udi parsing 2017-09-13 09:35:17 +02:00
Shannon 27fc3a9bb3 U4-10409 UDI Parsing should not require scanning assemblies 2017-09-13 14:16:43 +10:00
Claus ac391f3bcd Merge branch 'temp-unittests-for-urls' into dev-v7 2017-09-12 15:04:08 +02:00
Claus 0700e37830 adding unit tests for urls.
adding unit test for creating child content without identity.
cleaning up some usings ...
2017-09-12 14:44:01 +02:00
Shannon Deminick 5f4985b4eb Merge pull request #2185 from tomvanenckevort/U4-10184
U4-10184 - Fixed string splitting in MultipleTextStringValueConverter.
2017-09-12 20:19:32 +10:00
Stephan d179792cc3 perfs - fix IsPublishable silly bug 2017-09-12 11:39:34 +02:00
Sebastiaan Janssen 4cb7b29f60 Try to make build server do the npm/gulp tasks on it's own 2017-09-12 11:20:46 +02:00
Sebastiaan Janssen fb2f9cea64 Make VSTS responsible for padding the build number 2017-09-12 11:03:56 +02:00
Sebastiaan Janssen 394f21f4be Make it possible for the build server to set an alpha build version 2017-09-12 10:38:22 +02:00
Claus 32cd9d44cb Merge pull request #1831 from leekelleher/issue/U4-9678
Fixes U4-9678 - XPath Syntax Parser slowdown
2017-09-12 10:19:36 +02:00
Sebastiaan Janssen 237b7176bf I see, we explicitly need to tell MsBuild not to build belle, fine 2017-09-12 09:19:34 +02:00
Tom van Enckevort 1fa2c16668 U4-10184 - Fixed string splitting in MultipleTextStringValueConverter. 2017-09-12 08:15:14 +01:00
Sebastiaan Janssen 1c5e2b5f73 No need for UmbracoBuild=True - the build scripts already manually build Belle once, this would just cause it to run again during MSBuild 2017-09-12 09:02:57 +02:00
Sebastiaan Janssen 30af8cb928 Only build Belle when UmbracoBuild is set (from powershell input), lib folder doesn't exist or on rebuild 2017-09-12 08:47:36 +02:00
Shannon 65b44137d4 Fixes JS unit test runner 2017-09-12 16:02:40 +10:00
Shannon Deminick 41eeb38c5f Merge pull request #2043 from umbraco/TEMP-u4-10135
Added TruncateByWords method + overloads
2017-09-12 13:36:00 +10:00
Shannon 4356d3f94a publicizes class, fixes up some naming and removes unneeded DirectoryInfo allocations 2017-09-12 13:30:57 +10:00
Shannon Deminick ba072aec7c Merge pull request #2183 from umbraco/temp-U4-10400
U4-10400 Clear CDF temp files during upgrades
2017-09-12 13:26:41 +10:00
Sebastiaan Janssen f1d3b1a6d3 Merge branch 'dev-v7' of https://github.com/umbraco/Umbraco-CMS into dev-v7 2017-09-11 16:23:08 +02:00
Sebastiaan Janssen 45f9919e57 Don't include pdb files in the built zip files 2017-09-11 16:21:51 +02:00
Sebastiaan Janssen 857b7cc608 Merge pull request #2003 from umbraco/temp-u4-10006
U4-10006 - VSTS/PS migration
2017-09-11 15:43:50 +02:00
Sebastiaan Janssen c23160f915 Merge remote-tracking branch 'origin/dev-v7' into temp-u4-10006
# Conflicts:
#	src/Umbraco.Web.UI.Client/test/unit/app/content/edit-content-controller.spec.js
#	src/Umbraco.Web.UI.Client/test/unit/app/media/edit-media-controller.spec.js
#	src/Umbraco.Web.UI.Client/test/unit/app/propertyeditors/content-picker-controller.spec.js
#	src/Umbraco.Web.UI.Client/test/unit/common/services/content-factory.spec.js
2017-09-11 15:08:15 +02:00
Mads Rasmussen 3e3a180fe4 found better check for unit test fixes 2017-09-11 14:35:17 +02:00
Sebastiaan Janssen c55cf75ada Use HttpContext from the controller 2017-09-11 13:30:06 +02:00
Sebastiaan Janssen 23950c0cac U4-10400 Clear CDF temp files during upgrades 2017-09-11 12:22:38 +02:00
Claus 082e399293 Merge pull request #1215 from IurieM/Add-error-calback-handler-for-unpublish-even-in-contetn.edit.controller
Add error callback handler for unpublish event in content.edit.controller
2017-09-11 11:51:09 +02:00
Mads Rasmussen c4ab25f1ac fixing first round of unit tests 2017-09-11 10:50:54 +02:00
Sebastiaan Janssen 3f55abaf59 Create directories only when they don't exist 2017-09-09 16:48:13 +02:00
Sebastiaan Janssen 001e15f83c Documentation build goes through gulp now too 2017-09-09 16:41:02 +02:00
Sebastiaan Janssen 34e3257ddb Ignore failing unit tests to check if VSTS will continue 2017-09-09 15:54:24 +02:00
Sebastiaan Janssen 2b64cfb4b9 Update with the new gulp build 2017-09-09 15:15:56 +02:00
Sebastiaan Janssen a499744084 Move BUILD.md to root, adds build.bat 2017-09-09 15:09:34 +02:00
Sebastiaan Janssen c72ecda18c VS is always install in {major}.0 - currently so when running 15.3, don't use the minor version in the path 2017-09-09 15:08:08 +02:00
Sebastiaan Janssen 3423d8b2cc Merge branch 'dev-v7' into temp-u4-10006
# Conflicts:
#	.gitignore
#	build/Build.bat
#	build/Build.proj
#	build/BuildBelle.bat
#	build/UmbracoVersion.txt
#	src/Umbraco.Web.UI/Umbraco.Web.UI.csproj
2017-09-09 14:54:48 +02:00
Sebastiaan Janssen 37c4fc5f74 Don't try to remove directories that don't exist 2017-09-09 00:02:08 +02:00
Sebastiaan Janssen 406a206b03 Apparently we still have a node_modules folder, but no more xslt folder though! 2017-09-08 23:50:15 +02:00
Sebastiaan Janssen 55e0af118a Weirdly this errored out on 7.7 with a "Task 'cli' is not in your gulpfile" error..
not sure why this exact same file works in this branch
2017-09-08 23:29:16 +02:00
Sebastiaan Janssen 718ed19fb9 Forgot to remove this.. Seb is getting tired! 2017-09-08 15:05:15 +02:00
Sebastiaan Janssen 32999b7e19 Correction, we don't need this file after all :-) 2017-09-08 14:58:50 +02:00
Sebastiaan Janssen ce63251206 Adds missing file to gulp build 2017-09-08 14:53:33 +02:00
Sebastiaan Janssen 7b641f4771 Adds missing files for the build server 2017-09-08 14:45:00 +02:00
Sebastiaan Janssen 708d060c3b Fix up BuildBelle.bat 2017-09-08 14:12:54 +02:00
Sebastiaan Janssen e254dddbd4 Copy the js and lib files from the correct directories 2017-09-08 14:12:54 +02:00
Sebastiaan Janssen 87c2c5455c We don't have node_modules in this directory any more 2017-09-08 14:12:54 +02:00
Sebastiaan Janssen 8544aa685b VS loves managing whitespace.. go ahead then 2017-09-08 14:12:53 +02:00
Sebastiaan Janssen 09c23e93c2 Looks for the build output app.js to determine if we need to call BuildBelle.bat 2017-09-08 14:12:53 +02:00
Sebastiaan Janssen 9946d36d00 Ignore npm-debug.log 2017-09-08 14:12:53 +02:00
Sebastiaan Janssen 7012633fdd Install gulp before gulp-cli 2017-09-08 14:12:53 +02:00
Claus 6e348a3a1a Merge branch 'HarveyWilliams-patch-4' into dev-v7 2017-09-08 13:59:35 +02:00
Claus 733c920867 using string.replace instead of regex.
adding unit test.
2017-09-08 13:57:28 +02:00
Mads Rasmussen 35fc997d9f fix stylesheets for canvas designer/preview 2017-09-08 13:13:26 +02:00
Claus 921e8a2529 Merge pull request #2180 from umbraco/temp-U4-10392
U4-10392 Culture and hostnames with special characters can register a…
2017-09-08 11:27:25 +02:00
Claus 22bd6cd989 U4-10392 Culture and hostnames with special characters can register as collisions 2017-09-08 11:25:41 +02:00
Shannon 0713f12ba6 makes new classes internal 2017-09-08 12:02:20 +10:00
Sebastiaan Janssen dad4eafebd Enable RDP to figure out gulp build problem 2017-09-07 22:25:45 +02:00
Mads Rasmussen 96c9ecbdd7 fix calc functions 2017-09-07 21:39:41 +02:00
Sebastiaan Janssen e7e04de22e Merge pull request #2179 from umbraco/temp-dperfs
deploy-383 - dperfs
2017-09-07 20:46:31 +02:00
Sebastiaan Janssen 7003ef8d26 Remove circular dependency 2017-09-07 20:42:26 +02:00
Shannon Deminick 49a48bbfce Merge pull request #2169 from umbraco/temp-deploy-391
deploy-391 - allow for id reservation
2017-09-07 22:35:21 +10:00
Warren Buckley 663d9fcfe8 Merge pull request #2075 from defsteph/U4-10197
U4-10197 Added missing translations for Swedish
2017-09-07 13:33:55 +01:00
Stephan d6f8b878d2 perfs - cleanup 2017-09-07 13:45:56 +02:00
Claus 598944d3d8 ensuring id is only set if unset. 2017-09-07 13:13:03 +02:00
Claus 3caecf5161 U4-10384 Error when changing content type on media item 2017-09-07 12:57:06 +02:00
Stephan b02b2a61f0 perfs - deploy context isCancelled 2017-09-07 12:44:08 +02:00
Claus 60f7211a80 Merge branch 'patch-4' of git://github.com/HarveyWilliams/Umbraco-CMS into HarveyWilliams-patch-4 2017-09-07 10:36:49 +02:00
Sebastiaan Janssen 56dc10a4f7 Merge pull request #2158 from umbraco/temp-gulp-spike
U4-10261 Change frontend build setup from grunt to gulp
2017-09-06 23:52:48 +02:00
Stephan dbda6689b6 perfs - suspendable 2017-09-06 18:50:54 +02:00
Stephan 8d6c8ef282 perfs - support LocalDb 2017-09-06 18:50:41 +02:00
Warren Buckley df8c75438a Merge pull request #2168 from ronaldbarendse/U4-9374
U4-9374 Navigation panel header and editor panel header don't line up properly in Firefox
2017-09-06 12:37:45 +01:00
Warren Buckley 2d53da55a7 Merge pull request #2173 from tomfulton/u4-8886-2
U4-8886 - TinyMCE - highlight media picker toolbar icon when image selected
2017-09-06 12:25:01 +01:00
Robert 18d0fec014 Added some trimming and test to StripHtmlTags 2017-09-06 12:03:15 +02:00
Robert 851d587d1f Added Html Strip tests 2017-09-06 11:28:44 +02:00
Robert 6a3f94d0e1 Forgot to clean test names 2017-09-06 11:19:30 +02:00
Robert b1358936b4 Cleaning up tests and useless TruncateByWords functions 2017-09-06 11:17:06 +02:00
Robert b2798e38f7 Replaced html stripping with already existing function, removing unused code 2017-09-06 11:12:14 +02:00
Shannon a603fd0c46 Merge branch 'TEMP-u4-10135' of https://github.com/umbraco/Umbraco-CMS into TEMP-u4-10135
# Conflicts:
#	src/Umbraco.Web/HtmlStringUtilities.cs
2017-09-06 10:05:00 +10:00
Shannon 4b5c49907c switches to constant - comments out what seems to be a totally unused variable 2017-09-06 10:01:39 +10:00
Tom Fulton 1578bc8cc7 U4-8886 - TinyMCE - highlight media picker toolbar icon when image selected 2017-09-05 13:20:18 -04:00
Stephan e7c231c5a8 Support IdReservation in IdkMap 2017-09-05 15:23:18 +02:00
Sebastiaan Janssen a9cda9d651 Merge branch 'dev-v7' into temp-gulp-spike 2017-09-04 21:37:49 +02:00
Sebastiaan Janssen ad19eb8dff Update node version and remove unused npm reference 2017-09-04 20:14:31 +02:00
Sebastiaan Janssen e511554a42 Adds less as a dependency so that the build can complete 2017-09-04 20:10:19 +02:00
Stephan 84fd5dc2ee perfs - IContentService.IsPublishable 2017-09-04 19:49:28 +02:00
Stephan 344b52d10f deploy-391 - allow for id reservation 2017-09-04 17:04:48 +02:00
Sebastiaan Janssen 2121b7c8a0 Node version 2017-09-04 14:07:06 +02:00
mikkelhm 895faf41b1 Update version to 7.6.7 2017-09-04 12:28:16 +02:00
Ronald Barendse 207d6b53b5 Fixed .umb-panel-header-content-wrapper height
The .umb-panel-header-content-wrapper was 1 pixel higher than the parent .umb-panel-header, now both heights are 99px.
2017-09-04 11:22:56 +02:00
Robert 972d5f8296 Reverted back to last commit, invalid html check added 2017-09-03 21:17:53 +02:00
Robert 73937172dc Added check for invalid HTML and sanitization on said HTML
Added HtmlSanitization package
Added check for invalid HTML and sanitization on WordsToLength and Truncate methods
Addes some extra comments
2017-08-31 11:43:06 +02:00
Robert 8c1996a7a1 Changed from the String object qualifier to type qualifier 2017-08-31 09:15:02 +02:00
Robert 039ab8f1d2 Null check for firstTrim added and fixed typo 2017-08-30 09:18:45 +02:00
Mads Rasmussen 06a87bc341 update readme 2017-08-29 14:56:17 +02:00
Mads Rasmussen b10e646ade remove grunt file 2017-08-29 14:53:44 +02:00
Mads Rasmussen 110a3b2a12 add small interval to file watcher to keep windows calm 2017-08-29 14:35:54 +02:00
Mads Rasmussen 1bda9f32c1 only copy minified version of font-awesome 2017-08-29 14:27:43 +02:00
Mads Rasmussen ce8390768e Source maps gets cached really hard in the browser so I will remove them for now until we find a solution to clear them 2017-08-29 14:17:41 +02:00
Mads Rasmussen 7ccfc79080 update BuildBelle.bat to use gulp build task 2017-08-29 12:40:57 +02:00
Mads Rasmussen ed850629da Merge branch 'dev-v7' into temp-gulp-spike 2017-08-29 11:47:17 +02:00
Mads Rasmussen 1307cb1173 add themes for tinymce - they are needed for loading it 2017-08-29 11:39:16 +02:00
Mads Rasmussen 70231fcee2 fix codemirror folder structure 2017-08-29 10:26:11 +02:00
Mads Rasmussen aa5d7fc9fc only use source maps when developing 2017-08-28 15:42:31 +02:00
Mads Rasmussen 5cbe2b6ce0 Add tasks for karma testing 2017-08-28 14:41:54 +02:00
Robert 68fd74897f Replaced the Regex parse with HtmlAgilityPack parser 2017-08-28 10:52:53 +02:00
Robert 047a41c05e Having a space in a tag is now taken as a char length and not as a space between words 2017-08-28 10:14:16 +02:00
Mads Rasmussen 0089f79bd7 add tasks for ngdocs 2017-08-25 14:22:42 +02:00
Mads Rasmussen c468e4736e bower name should be lowercase 2017-08-25 14:19:25 +02:00
Robert 84f684ed31 Truncate with trimming should now work, added some mpore tests for truncate by words methods
Fix: Original Truncate method show now be able to trim
Add: Added some more tests for Truncate by words to cater for tagsAsContent parameter
Fix: In original truncate, currentTextLength prop will be increased everytime a tag is added, this will fix an issue when tagsAsContent is set to true (it would have added an extra char per tag, which would have went over to the next word)
2017-08-25 11:39:13 +02:00
Robert 54f86c06f0 Fix TruncateByWords to work with tags 2017-08-21 12:30:16 +02:00
Claus bb01eca7b7 added a few tests for the new UmbracoHelper methods. 2017-08-15 13:08:30 +02:00
Harvey Williams 13f76d2af9 Updated ReplaceLineBreaksForHtml to include \r
I was surprised when this method did not replace a `\r` character with an HTML break. I have updated it to not only replace `\n`, but also `\r\n` and just `\r`.

I think these cases should be considered because of [this SO thread](https://stackoverflow.com/questions/4824621/is-a-new-line-n-or-r-n).

The updated code will not replace `\n\r` with one break but with two.

I used [this SO answer](https://stackoverflow.com/a/8196219/2963111) to update the method.

```
[TestMethod]
public void ReplaceLineBreaksForHtmlTest()
{
    var result = "foo\rbar\nbaz\r\nbiff\n\r".ReplaceLineBreaksForHtml();

    Assert.AreEqual(result, "foo<br />\rbar<br />\nbaz<br />\r\nbiff<br />\n<br />\r");
}
```
2017-08-11 11:42:35 +01:00
Per Ploug babcbd2f7a Updates from dev-v7 2017-08-07 15:29:34 +02:00
Per Ploug ba82885b6d Merge remote-tracking branch 'refs/remotes/origin/dev-v7' into temp-gulp-spike
# Conflicts:
#	build/BuildBelle.bat
2017-08-07 14:05:53 +02:00
Stephan Lonntorp d4a2244190 Added missing translations 2017-07-25 13:28:46 +02:00
Stephan 14de3fee46 Merge branch dev-v7 into temp-u4-10006 2017-07-21 13:27:56 +02:00
Stephan 17d3548bbb Merge branch dev-v7 into temp-u4-10006 2017-07-21 10:04:25 +02:00
Stephan 9754c4511b U4-10006 - temp debug 2017-07-21 09:35:32 +02:00
Stephan 442d359ab0 U4-10006 - temp debug 2017-07-21 09:14:46 +02:00
Stephan bbed2fa8f6 U4-10006 - temp debug 2017-07-21 09:08:21 +02:00
Stephan 3089a0ab3a U4-10006 - temp debug 2017-07-21 08:48:09 +02:00
Stephan b3ac3a03f3 U4-10006 - temp debug 2017-07-17 11:30:33 +02:00
Stephan bd0ca43b83 U4-10006 - use Invoke-WebRequest, misc 2017-07-17 09:46:09 +02:00
Stephan f39531216c U4-10006 - fix npm/node issues 2017-07-14 20:21:29 +02:00
Stephan f24effdf0e U4-10006 - misc fixes 2017-07-14 10:17:40 +02:00
Stephan e9a4321ee8 U4-10006 - revert unwanted changes to tree.config 2017-07-14 10:17:13 +02:00
Warren Buckley 9ea2fa9d8c Couple of tiny typos in the XML Comments/Docs 2017-07-13 10:15:41 +01:00
Robert cddc6f3116 Cleared useless methods 2017-07-12 12:28:40 +02:00
Robert 769f0d97d2 Added TruncateByWords method + overloads 2017-07-12 10:35:09 +02:00
Stephan f7d11bf936 U4-10006 - fix 2017-07-10 17:41:58 +02:00
Stephan 0fc868c9ba U4-10006 - verify NuGet 2017-07-10 15:58:22 +02:00
Stephan a3f4275b30 U4-10006 - build docs 2017-07-09 18:45:29 +02:00
Stephan cfd3301965 U4-10006 - fix build.ps1, update build.md doc 2017-07-09 17:29:06 +02:00
Stephan 48041c3163 U4-10006 - add build.ps1 2017-07-07 16:41:21 +02:00
Stephan 872530296f U4-10006 - fix 2017-06-29 19:26:51 +02:00
Stephan 71b5e5223f U4-10006 - fix 2017-06-28 16:26:27 +02:00
Stephan f3935b5007 Merge branch 'dev-v7' into temp-u4-10006 2017-06-28 13:10:05 +02:00
Per Ploug e35a748c92 Fixes issues with missing angular modules and adds sourcemap support 2017-06-27 17:00:00 +02:00
Stephan a3af1d478d U4-10006 - revert unrelated changes 2017-06-15 16:08:51 +02:00
Stephan 7d8fdff6c1 U4-10006 - adjust projects to new build 2017-06-15 15:50:50 +02:00
Stephan a813c0bfea U4-10006 - import some documentation 2017-06-15 15:15:53 +02:00
Stephan 4870554f47 U4-10006 - from build.bat to Umbraco.Build PS module 2017-06-15 13:32:00 +02:00
Sebastiaan Janssen 547767fc0f Fixes: when valid username is used, don't raise the unknown username event 2017-06-05 17:16:22 +02:00
Sebastiaan Janssen 74126134b1 Some more cleanup 2017-06-05 12:07:45 +02:00
Sebastiaan Janssen 6136118699 Clean up some events being raised, add code comments, shuffle some code around to make it look nicer 2017-06-05 11:52:42 +02:00
Sebastiaan Janssen 114b58c5ca Raise events for failed login attempts for unknown users 2017-06-05 10:43:57 +02:00
Sebastiaan Janssen 3019d67922 Adds forgot password events 2017-06-05 10:25:05 +02:00
Sebastiaan Janssen 97518c837f Merge remote-tracking branch 'origin/dev-v7' into temp-U4-8634 2017-06-04 16:55:42 +02:00
Sebastiaan Janssen 727250d2ab Removing AccountCreated and AccountUpdated for now, is the responsibility of UserService 2017-06-04 16:55:23 +02:00
Sebastiaan Janssen 66e3a00e56 Raise unlocking and saving events from EditUser.aspx 2017-06-04 15:18:24 +02:00
Sebastiaan Janssen aebea2da31 Merge remote-tracking branch 'origin/dev-v7' into temp-U4-8634 2017-06-04 14:35:35 +02:00
Sebastiaan Janssen 1634789641 Fix firing of locked out event 2017-06-04 14:33:13 +02:00
Mads Rasmussen 631a9f92ea fix merge bug + add ignore list 2017-05-05 14:19:37 +02:00
Mads Rasmussen 229a15be4f add nonodes to gulp 2017-05-05 13:10:40 +02:00
Mads Rasmussen 28d7a4a6dc Merge branch 'dev-v7.6' into temp-gulp-spike
# Conflicts:
#	src/Umbraco.Web.UI.Client/bower.json
2017-05-05 13:01:24 +02:00
Mads Rasmussen 21f003e705 clean up ace builds 2017-05-05 12:26:04 +02:00
Sebastiaan Janssen 0d80bf6a84 Alphabetize the events list and wire up the events correctly (instead of sending everything through OnAuthResetAccessFailedCount) 2017-04-30 12:26:33 +02:00
Sebastiaan Janssen e88f5c8fe2 Better way to get current user's IP address 2017-04-30 10:59:00 +02:00
Sebastiaan Janssen 7cb1a497e5 Merge remote-tracking branch 'origin/dev-v7.6' into temp-seb-authevents
# Conflicts:
#	src/Umbraco.Core/Security/BackOfficeSignInManager.cs
2017-04-30 10:17:07 +02:00
Sebastiaan Janssen b72c8ef953 Get userId more easily - also changed the default to -1 just in case we can't determine the Id (at least then changes won't be "blamed" on user 0 2017-04-30 10:15:53 +02:00
Sebastiaan Janssen 04a09bd4d6 Updates comment 2017-04-29 23:19:35 +02:00
Sebastiaan Janssen 311fcfe328 Adds AccountCreated event 2017-04-29 23:17:50 +02:00
Sebastiaan Janssen 33d09b14be Refactor GetBackofficeUserManager calls 2017-04-29 22:21:42 +02:00
Sebastiaan Janssen cdab89062e Make sure to only trigger events on MembershipHelper when we're dealing with backoffice users 2017-04-29 22:10:43 +02:00
Sebastiaan Janssen 38571f2cdd Wire up LoginSuccess and LoginRequiresVerification 2017-04-29 13:43:51 +02:00
Sebastiaan Janssen fcd90aa702 Get IP address from OWIN 2017-04-29 12:51:09 +02:00
Sebastiaan Janssen ae17172126 Attempt to raise events from parts of code that don't hit the BackOfficeUserManager directly 2017-04-29 12:49:56 +02:00
Sebastiaan Janssen ecca480334 Get backoffice identity from cookie instead of grabbing it from database 2017-04-29 12:25:35 +02:00
Sebastiaan Janssen 095a7c0aa7 First attempt at hooking up some events for auditing 2017-04-28 13:20:42 +02:00
leekelleher 169c6b6372 Fixes U4-9678 - XPath Syntax Parser slowdown
http://issues.umbraco.org/issue/U4-9678

Swaps out the base XPath from `"descendant::*[@id={0}]"` to `"id({0})"` - making use of the content-cache's XML DTD ID index.

This will perform better on larger content-trees.
2017-03-25 12:50:53 +00:00
Marc Goodson 8ab2f7c257 add language translations keys for showOrdinals and hideOrdinals 2017-03-24 10:21:01 +00:00
Marc Goodson 51215f11af toggle the show ordinals label button to hide, when in show ordinal mode 2017-03-24 10:20:31 +00:00
Marc Goodson 3df103eae2 In reorder mode, present an additional toggle button, to show the individual property editor sort ordinals, in input boxes, enabling their order to be manually overridden (for curating property order on tabs, when properties come from two different compositions) see U4-6738 2017-03-22 22:35:53 +00:00
Per Ploug 1757e7b4c8 Update gulpfile and buildbelle file
Should now have the right paths for running it from VS
2017-01-16 14:53:07 +01:00
Per Ploug a68eb91c14 update buildbell.bat file to use gulp 2017-01-10 14:58:46 +01:00
Per Ploug 7c9476ca41 Sets the correct root dir for compiling files 2017-01-09 15:27:05 +01:00
Per Ploug 5cee5a27c9 Wraps tasks in a merge-stream
This ensures proper timing and feedback of tasks
2017-01-09 15:26:05 +01:00
Per Ploug 1e34570a1f consistent naming for canvasdesigner js file 2017-01-07 01:28:16 +01:00
Per Ploug 7e930330e2 fixes karma testing config - now runs with "npm test" command instead 2017-01-07 01:27:59 +01:00
Per Ploug cc3355b1f9 fixes issues with bootstrap2 navbar and less2 syntax 2017-01-07 01:27:26 +01:00
Per Ploug ee9deacf92 ignore lib-bower temp folder 2017-01-07 01:26:47 +01:00
Per Ploug 4e9a8623f0 syntax issue in eslintrc 2017-01-07 01:26:35 +01:00
Per Ploug 904265cdf5 replaces gruntfile with gulpfile
Meaner, faster, better
2017-01-07 01:26:13 +01:00
Per Ploug 4a191f0711 Rebuild bower.json to support bower-installer
removes most of the custom bower lib installing we had in gruntfile
2017-01-07 01:25:43 +01:00
Per Ploug 6be9a25d99 new package.json to support gulp 2017-01-07 01:24:32 +01:00
bjarnef 89cbe53b63 Fix z-index of focal point 2016-11-22 23:00:25 +01:00
Iurie Marchitan a58bf507ed Add error callback handler for unpublish event in content.edit.controller. For some cases user may not be allowed to unpublish a content, and he need to get a notification message that explains the reason. 2016-04-05 10:33:36 +02:00
144 changed files with 5755 additions and 2471 deletions
+6 -11
View File
@@ -46,13 +46,7 @@ src/Umbraco.Web.UI/Web.*.config.transformed
umbraco/presentation/umbraco/plugins/uComponents/uComponentsInstaller.ascx
umbraco/presentation/packages/uComponents/MultiNodePicker/CustomTreeService.asmx
_BuildOutput/*
*.ncrunchsolution
build/UmbracoCms.AllBinaries*zip
build/UmbracoCms.WebPI*zip
build/UmbracoCms*zip
build/UmbracoExamine.PDF*zip
build/*.nupkg
src/Umbraco.Tests/config/applications.config
src/Umbraco.Tests/config/trees.config
src/Umbraco.Web.UI/web.config
@@ -68,9 +62,9 @@ src/packages/repositories.config
src/Umbraco.Web.UI/[Ww]eb.config
*.transformed
webpihash.txt
node_modules
lib-bower
src/Umbraco.Web.UI/[Uu]mbraco/[Ll]ib/*
src/Umbraco.Web.UI/[Uu]mbraco/[Jj]s/umbraco.*
@@ -95,7 +89,6 @@ src/Umbraco.Web.UI/[Uu]mbraco/[Aa]ssets/*
src/Umbraco.Web.UI.Client/[Bb]uild/*
src/Umbraco.Web.UI.Client/[Bb]uild/[Bb]elle/
src/Umbraco.Web.UI/[Uu]ser[Cc]ontrols/
build/_BuildOutput/
src/Umbraco.Web.UI.Client/src/[Ll]ess/*.css
tools/NDepend/
@@ -130,7 +123,6 @@ src/*.boltdata/
/src/Umbraco.Web.UI/Umbraco/Js/canvasdesigner.config.js
/src/Umbraco.Web.UI/Umbraco/Js/canvasdesigner.front.js
src/umbraco.sln.ide/*
build/UmbracoCms.*/
src/.vs/
src/Umbraco.Web.UI/umbraco/js/install.loader.js
src/Umbraco.Tests/media
@@ -140,8 +132,11 @@ apidocs/api/*
build/docs.zip
build/ui-docs.zip
build/csharp-docs.zip
build/msbuild.log
.vs/
src/packages/
build/tools/
src/PrecompiledWeb/*
build.out/
build.tmp/
build/Modules/*/temp/
+149
View File
@@ -0,0 +1,149 @@
Umbraco Cms Build
--
----
# Quick!
To build Umbraco, fire PowerShell and move to Umbraco's repository root (the directory that contains `src`, `build`, `README.md`...). There, trigger the build with the following command:
build\build.ps1
By default, this builds the current version. It is possible to specify a different version as a parameter to the build script:
build\build.ps1 7.6.44
Valid version strings are defined in the `Set-UmbracoVersion` documentation below.
## Notes
Git might have issues dealing with long file paths during build. You may want/need to enable `core.longpaths` support (see [this page](https://github.com/msysgit/msysgit/wiki/Git-cannot-create-a-file-or-directory-with-a-long-path) for details).
# Build
The Umbraco Build solution relies on a PowerShell module. The module needs to be imported into PowerShell. From within Umbraco's repository root:
build\build.ps1 -ModuleOnly
Or the abbreviated form:
build\build.ps1 -mo
Once the module has been imported, a set of commands are added to PowerShell.
## Get-UmbracoBuildEnv
Gets the Umbraco build environment ie NuGet, Semver, Visual Studio, etc. Downloads things that can be downloaded such as NuGet. Examples:
$uenv = Get-UmbracoBuildEnv
Write-Host $uenv.SolutionRoot
&$uenv.NuGet help
The object exposes the following properties:
* `SolutionRoot`: the absolute path to the solution root
* `VisualStudio`: a Visual Studio object (see below)
* `NuGet`: the absolute path to the NuGet executable
* `Zip`: the absolute path to the 7Zip executable
* `VsWhere`: the absolute path to the VsWhere executable
* `NodePath`: the absolute path to the Node install
* `NpmPath`: the absolute path to the Npm install
The Visual Studio object is `null` when Visual Studio has not been detected (eg on VSTS). When not null, the object exposes the following properties:
* `Path`: Visual Studio installation path (eg some place under `Program Files`)
* `Major`: Visual Studio major version (eg `15` for VS 2017)
* `Minor`: Visual Studio minor version
* `MsBUild`: the absolute path to the MsBuild executable
## Get-UmbracoVersion
Gets an object representing the current Umbraco version. Example:
$v = Get-UmbracoVersion
Write-Host $v.Semver
The object exposes the following properties:
* `Semver`: the semver object representing the version
* `Release`: the main part of the version (eg `7.6.33`)
* `Comment`: the pre release part of the version (eg `alpha02`)
* `Build`: the build number part of the version (eg `1234`)
## Set-UmbracoVersion
Modifies Umbraco files with the new version.
>This entirely replaces the legacy `UmbracoVersion.txt` file.
The version must be a valid semver version. It can include a *pre release* part (eg `alpha02`) and/or a *build number* (eg `1234`). Examples:
Set-UmbracoVersion 7.6.33
Set-UmbracoVersion 7.6.33-alpha02
Set-UmbracoVersion 7.6.33+1234
Set-UmbracoVersion 7.6.33-beta05+5678
Note that `Set-UmbracoVersion` enforces a slightly more restrictive naming scheme than what semver would tolerate. The pre release part can only be composed of a-z and 0-9, therefore `alpha033` is considered valid but not `alpha.033` nor `alpha033-preview` nor `RC2` (would need to be lowercased `rc2`).
>It is considered best to add trailing zeroes to pre releases, else NuGet gets the order of versions wrong. So if you plan to have more than 10, but no more that 100 alpha versions, number the versions `alpha00`, `alpha01`, etc.
## Build-Umbraco
Builds Umbraco. Temporary files are generated in `build.tmp` while the actual artifacts (zip files, NuGet packages...) are produced in `build.out`. Example:
Build-Umbraco
Some log files, such as MsBuild logs, are produced in `build.tmp` too. The `build` directory should remain clean during a build.
### web.config
Building Umbraco requires a clean `web.config` file in the `Umbraco.Web.UI` project. If a `web.config` file already exists, the `pre-build` task (see below) will save it as `web.config.temp-build` and replace it with a clean copy of `web.Template.config`. The original file is replaced once it is safe to do so, by the `pre-packages` task.
## Build-UmbracoDocs
Builds umbraco documentation. Temporary files are generated in `build.tmp` while the actual artifacts (docs...) are produced in `build.out`. Example:
Build-UmbracoDocs
Some log files, such as MsBuild logs, are produced in `build.tmp` too. The `build` directory should remain clean during a build.
## Verify-NuGet
Verifies that projects all require the same version of their dependencies, and that NuSpec files require versions that are consistent with projects. Example:
Verify-NuGet
# VSTS
Continuous integration, nightly builds and release builds run on VSTS.
VSTS uses the `Build-Umbraco` command several times, each time passing a different *target* parameter. The supported targets are:
* `pre-build`: prepares the build
* `compile-belle`: compiles Belle
* `compile-umbraco`: compiles Umbraco
* `pre-tests`: prepares the tests
* `compile-tests`: compiles the tests
* `pre-packages`: prepares the packages
* `pkg-zip`: creates the zip files
* `pre-nuget`: prepares NuGet packages
* `pkg-nuget`: creates NuGet packages
All these targets are executed when `Build-Umbraco` is invoked without a parameter (or with the `all` parameter). On VSTS, compilations (of Umbraco and tests) are performed by dedicated VSTS tasks. Similarly, creating the NuGet packages is also performed by dedicated VSTS tasks.
Finally, the produced artifacts are published in two containers that can be downloaded from VSTS: `zips` contains the zip files while `nuget` contains the NuGet packages.
>During a VSTS build, some environment `UMBRACO_*` variables are exported by the `pre-build` target and can be reused in other targets *and* in VSTS tasks. The `UMBRACO_TMP` environment variable is used in `Umbraco.Tests` to disable some tests that have issues with VSTS at the moment.
# Notes
*This part needs to be cleaned up*
Nightlies should use some sort of build number.
We should increment versions as soon as a version is released. Ie, as soon as `7.6.33` is released, we should `Set-UmbracoVersion 7.6.34-alpha` and push.
NuGet / NuSpec consistency checks are performed in tests. We should move it so it is done as part of the PowerShell script even before we try to compile and run the tests.
There are still a few commands in `build` (to build docs, install Git or cleanup the install) that will need to be migrated to PowerShell.
/eof
+1 -3
View File
@@ -12,9 +12,7 @@ Umbraco is a free open source Content Management System built on the ASP.NET pla
## Building Umbraco from source ##
The easiest way to get started is to run `build/build.bat` which will build both the backoffice (also known as "Belle") and the Umbraco core. You can then easily start debugging from Visual Studio, or if you need to debug Belle you can run `grunt vs` in `src\Umbraco.Web.UI.Client`.
If you're interested in making changes to Belle without running Visual Studio make sure to read the [Belle ReadMe file](src/Umbraco.Web.UI.Client/README.md).
The easiest way to get started is to run `build/build.bat` which will build both the backoffice (also known as "Belle") and the Umbraco core. You can then easily start debugging from Visual Studio, or if you need to debug Belle you can run `gulp dev` in `src\Umbraco.Web.UI.Client`.
Note that you can always [download a nightly build](http://nightly.umbraco.org/?container=umbraco-750) so you don't have to build the code yourself.
+4
View File
@@ -1,5 +1,9 @@
version: '{build}'
shallow_clone: true
init:
- ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
build_script:
- cmd: >-
SET SLN=%CD%
+15
View File
@@ -0,0 +1,15 @@
@ECHO OFF
powershell .\build\build.ps1
IF ERRORLEVEL 1 (
GOTO :error
) ELSE (
GOTO :EOF
)
:error
ECHO.
ECHO Can not run build\build.ps1.
ECHO If this is due to a SecurityError then make sure to run the following command from an administrator command prompt:
ECHO.
ECHO powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
-207
View File
@@ -1,207 +0,0 @@
@ECHO OFF
:: UMBRACO BUILD FILE
:: ensure we have UmbracoVersion.txt
IF NOT EXIST UmbracoVersion.txt (
ECHO UmbracoVersion.txt is missing!
GOTO error
)
REM Get the version and comment from UmbracoVersion.txt lines 2 and 3
SET RELEASE=
SET COMMENT=
FOR /F "skip=1 delims=" %%i IN (UmbracoVersion.txt) DO IF NOT DEFINED RELEASE SET RELEASE=%%i
FOR /F "skip=2 delims=" %%i IN (UmbracoVersion.txt) DO IF NOT DEFINED COMMENT SET COMMENT=%%i
REM process args
SET INTEGRATION=0
SET nuGetFolder=%CD%\..\src\packages
SET SKIPNUGET=0
:processArgs
:: grab the first parameter as a whole eg "/action:start"
:: end if no more parameter
SET SWITCHPARSE=%1
IF [%SWITCHPARSE%] == [] goto endProcessArgs
:: get switch and value
SET SWITCH=
SET VALUE=
FOR /F "tokens=1,* delims=: " %%a IN ("%SWITCHPARSE%") DO SET SWITCH=%%a& SET VALUE=%%b
:: route arg
IF '%SWITCH%'=='/release' GOTO argRelease
IF '%SWITCH%'=='-release' GOTO argRelease
IF '%SWITCH%'=='/comment' GOTO argComment
IF '%SWITCH%'=='-comment' GOTO argComment
IF '%SWITCH%'=='/integration' GOTO argIntegration
IF '%SWITCH%'=='-integration' GOTO argIntegration
IF '%SWITCH%'=='/nugetfolder' GOTO argNugetFolder
IF '%SWITCH%'=='-nugetfolder' GOTO argNugetFolder
IF '%SWITCH%'=='/skipnuget' GOTO argSkipNuget
IF '%SWITCH%'=='-skipnuget' GOTO argSkipNuget
ECHO "Invalid switch %SWITCH%"
GOTO error
:: handle each arg
:argRelease
set RELEASE=%VALUE%
SHIFT
goto processArgs
:argComment
SET COMMENT=%VALUE%
SHIFT
GOTO processArgs
:argIntegration
SET INTEGRATION=1
SHIFT
GOTO processArgs
:argNugetFolder
SET nuGetFolder=%VALUE%
SHIFT
GOTO processArgs
:argSkipNuget
SET SKIPNUGET=1
SHIFT
GOTO processArgs
:endProcessArgs
REM run
SET VERSION=%RELEASE%
IF [%COMMENT%] EQU [] (SET VERSION=%RELEASE%) ELSE (SET VERSION=%RELEASE%-%COMMENT%)
ECHO ################################################################
ECHO Building Umbraco %VERSION%
ECHO ################################################################
SET MSBUILDPATH=C:\Program Files (x86)\MSBuild\14.0\Bin
SET MSBUILD="%MSBUILDPATH%\MsBuild.exe"
SET PATH="%MSBUILDPATH%";%PATH%
ReplaceIISExpressPortNumber.exe ..\src\Umbraco.Web.UI\Umbraco.Web.UI.csproj %RELEASE%
ECHO.
ECHO Removing the belle build folder and bower_components folder to make sure everything is clean as a whistle
RD ..\src\Umbraco.Web.UI.Client\build /Q /S
RD ..\src\Umbraco.Web.UI.Client\bower_components /Q /S
ECHO.
ECHO Removing existing built files to make sure everything is clean as a whistle
RMDIR /Q /S _BuildOutput
DEL /F /Q UmbracoCms.*.zip 2>NUL
DEL /F /Q UmbracoExamine.*.zip 2>NUL
DEL /F /Q UmbracoCms.*.nupkg 2>NUL
DEL /F /Q webpihash.txt 2>NUL
ECHO.
ECHO Making sure Git is in the path so that the build can succeed
CALL InstallGit.cmd
REM Adding the default Git path so that if it's installed it can actually be found
REM This is necessary because SETLOCAL is on in InstallGit.cmd so that one might find Git,
REM but the path setting is lost due to SETLOCAL
SET PATH="C:\Program Files (x86)\Git\cmd";"C:\Program Files\Git\cmd";%PATH%
SET toolsFolder=%CD%\tools\
IF NOT EXIST "%toolsFolder%" (
MD tools
)
SET nuGetExecutable=%CD%\tools\nuget.exe
IF NOT EXIST "%nuGetExecutable%" (
ECHO Getting NuGet so we can fetch some tools
ECHO Downloading https://dist.nuget.org/win-x86-commandline/latest/nuget.exe to %nuGetExecutable%
powershell -Command "(New-Object Net.WebClient).DownloadFile('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe', '%nuGetExecutable%')"
)
:: We need vswhere.exe for VS2017+
IF NOT EXIST "%toolsFolder%vswhere.exe" (
ECHO vswhere not found - fetching now
"%nuGetExecutable%" install vswhere -OutputDirectory tools -Verbosity quiet
)
FOR /f "delims=" %%A in ('dir "%toolsFolder%vswhere.*" /b') DO SET "vswhereExePath=%toolsFolder%%%A\"
MOVE "%vswhereExePath%tools\vswhere.exe" "%toolsFolder%vswhere.exe"
ECHO.
ECHO Making sure we have a web.config
IF NOT EXIST "%CD%\..\src\Umbraco.Web.UI\web.config" COPY "%CD%\..\src\Umbraco.Web.UI\web.Template.config" "%CD%\..\src\Umbraco.Web.UI\web.config"
for /f "usebackq tokens=1* delims=: " %%i in (`"%CD%\tools\vswhere.exe" -latest -requires Microsoft.Component.MSBuild`) do (
if /i "%%i"=="installationPath" set InstallDir=%%j
)
SET VSWherePath="%InstallDir%\MSBuild"
ECHO.
ECHO Visual Studio is installed in: %InstallDir%
SET MSBUILDPATH=C:\Program Files (x86)\MSBuild\14.0\Bin
SET MSBUILD="%MSBUILDPATH%\MsBuild.exe"
ECHO.
ECHO Reporting NuGet version
"%nuGetExecutable%" help | findstr "^NuGet Version:"
ECHO.
ECHO Restoring NuGet packages
ECHO Into %nuGetFolder%
"%nuGetExecutable%" restore "%CD%\..\src\umbraco.sln" -Verbosity Quiet -NonInteractive -PackagesDirectory "%nuGetFolder%"
IF ERRORLEVEL 1 GOTO :error
ECHO.
ECHO.
ECHO Performing MSBuild and producing Umbraco binaries zip files
ECHO This takes a few minutes and logging is set to report warnings
ECHO and errors only so it might seems like nothing is happening for a while.
ECHO You can check the msbuild.log file for progress.
ECHO.
%MSBUILD% "Build.proj" /p:BUILD_RELEASE=%RELEASE% /p:BUILD_COMMENT=%COMMENT% /p:NugetPackagesDirectory="%nuGetFolder%" /p:VSWherePath=%VSWherePath% /consoleloggerparameters:Summary;ErrorsOnly /fileLogger
IF ERRORLEVEL 1 GOTO error
ECHO.
ECHO Setting node_modules folder to hidden to prevent VS13 from crashing on it while loading the websites project
attrib +h ..\src\Umbraco.Web.UI.Client\node_modules
IF %SKIPNUGET% EQU 1 GOTO success
ECHO.
ECHO Adding Web.config transform files to the NuGet package
REN .\_BuildOutput\WebApp\Views\Web.config Web.config.transform
REN .\_BuildOutput\WebApp\Xslt\Web.config Web.config.transform
ECHO.
ECHO Packing the NuGet release files
..\src\.nuget\NuGet.exe Pack NuSpecs\UmbracoCms.Core.nuspec -Version %VERSION% -Symbols -Verbosity quiet
..\src\.nuget\NuGet.exe Pack NuSpecs\UmbracoCms.nuspec -Version %VERSION% -Verbosity quiet
IF ERRORLEVEL 1 GOTO error
:success
ECHO.
ECHO No errors were detected!
ECHO There may still be some in the output, which you would need to investigate.
ECHO Warnings are usually normal.
ECHO.
ECHO.
GOTO :EOF
:error
ECHO.
ECHO Errors were detected!
ECHO.
REM don't pause if continuous integration else the build server waits forever
REM before cancelling the build (and, there is noone to read the output anyways)
IF %INTEGRATION% NEQ 1 PAUSE
-345
View File
@@ -1,345 +0,0 @@
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!--
****************************************************
INCLUDES
*****************************************************
-->
<PropertyGroup>
<MSBuildCommunityTasksPath>..\MSBuildCommunityTasks</MSBuildCommunityTasksPath>
<UmbracoMSBuildTasksPath>..\UmbracoMSBuildTasks</UmbracoMSBuildTasksPath>
</PropertyGroup>
<Import Project="..\tools\UmbracoMSBuildTasks\Umbraco.MSBuild.Tasks.Targets" />
<Import Project="..\tools\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />
<UsingTask TaskName="GenerateHash" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<InputFiles ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" />
<OutputFile ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Using Namespace="System.IO" />
<Using Namespace="System.Linq" />
<Using Namespace="System.Security.Cryptography" />
<Code Type="Fragment" Language="cs">
<![CDATA[
using (var ms = new MemoryStream())
{
foreach (var item in InputFiles)
{
string path = item.ItemSpec;
using (FileStream stream = new FileStream(path, FileMode.Open))
{
using (var cryptoProvider = new SHA1CryptoServiceProvider())
{
var fileHash = cryptoProvider.ComputeHash(stream);
using (TextWriter w = new StreamWriter(OutputFile, false))
{
w.WriteLine(string.Join("", fileHash.Select(b => b.ToString("x2"))));
}
}
}
}
}
]]>
</Code>
</Task>
</UsingTask>
<!--
****************************************************
VARIABLES
*****************************************************
-->
<!-- NB: BUILD_NUMBER is passed in by the build server -->
<PropertyGroup Condition="'$(BUILD_NUMBER)'!=''">
<DECIMAL_BUILD_NUMBER>.$(BUILD_NUMBER)</DECIMAL_BUILD_NUMBER>
</PropertyGroup>
<PropertyGroup Condition="'$(BUILD_RELEASE)'!=''">
<DECIMAL_BUILD_NUMBER>.$(BUILD_RELEASE)</DECIMAL_BUILD_NUMBER>
</PropertyGroup>
<PropertyGroup Condition="'$(BUILD_RELEASE)'!='' AND '$(BUILD_COMMENT)'!=''">
<DECIMAL_BUILD_NUMBER>.$(BUILD_RELEASE)-$(BUILD_COMMENT)</DECIMAL_BUILD_NUMBER>
</PropertyGroup>
<PropertyGroup Condition="'$(BUILD_RELEASE)'!='' AND '$(BUILD_NIGHTLY)'!=''">
<DECIMAL_BUILD_NUMBER>.$(BUILD_RELEASE)-$(BUILD_NIGHTLY)</DECIMAL_BUILD_NUMBER>
</PropertyGroup>
<PropertyGroup Condition="'$(BUILD_RELEASE)'!='' AND '$(BUILD_COMMENT)'!='' AND '$(BUILD_NIGHTLY)'!=''">
<DECIMAL_BUILD_NUMBER>.$(BUILD_RELEASE)-$(BUILD_COMMENT)-$(BUILD_NIGHTLY)</DECIMAL_BUILD_NUMBER>
</PropertyGroup>
<PropertyGroup>
<BuildConfiguration>Release</BuildConfiguration>
<BuildFolder>_BuildOutput\</BuildFolder>
<BuildZipFileName>UmbracoCms$(DECIMAL_BUILD_NUMBER).zip</BuildZipFileName>
<BuildZipFileNameBin>UmbracoCms.AllBinaries$(DECIMAL_BUILD_NUMBER).zip</BuildZipFileNameBin>
<BuildZipFileNameWebPi>UmbracoCms.WebPI$(DECIMAL_BUILD_NUMBER).zip</BuildZipFileNameWebPi>
<IncludeSymbols>False</IncludeSymbols>
<BuildFolderRelativeToProjects>..\..\build\$(BuildFolder)</BuildFolderRelativeToProjects>
<BuildFolderAbsolutePath>$(MSBuildProjectDirectory)\$(BuildFolder)</BuildFolderAbsolutePath>
<SolutionBinFolder>$(BuildFolder)bin\</SolutionBinFolder>
<WebAppFolder>$(BuildFolder)WebApp\</WebAppFolder>
<WebPiFolder>$(BuildFolder)WebPi\</WebPiFolder>
<ConfigsFolder>$(BuildFolder)Configs\</ConfigsFolder>
<SolutionBinFolderRelativeToProjects>$(BuildFolderRelativeToProjects)bin\</SolutionBinFolderRelativeToProjects>
<SolutionBinFolderAbsolutePath>$(BuildFolderAbsolutePath)bin\</SolutionBinFolderAbsolutePath>
<WebAppFolderRelativeToProjects>$(BuildFolderRelativeToProjects)WebApp\</WebAppFolderRelativeToProjects>
<WebAppFolderAbsolutePath>$(BuildFolderAbsolutePath)WebApp\</WebAppFolderAbsolutePath>
<WebPiFolderRelativeToProjects>$(BuildFolderRelativeToProjects)WebPi\</WebPiFolderRelativeToProjects>
<WebPiFolderAbsolutePath>$(BuildFolderAbsolutePath)WebPi\</WebPiFolderAbsolutePath>
</PropertyGroup>
<ItemGroup>
<SystemFolders Include="$(WebAppFolder)App_Data" />
<SystemFolders Include="$(WebAppFolder)Media" />
<SystemFolders Include="$(WebAppFolder)Views" />
</ItemGroup>
<!--
****************************************************
TARGETS
*****************************************************
-->
<Target Name="Build" DependsOnTargets="GenerateWebPiHash">
<Message Text="Build finished" />
</Target>
<Target Name="GenerateWebPiHash" DependsOnTargets="ZipWebPiApp">
<ItemGroup>
<WebPiFile Include="$(BuildZipFileNameWebPi)" />
</ItemGroup>
<Message Text="Calculating hash for $(BuildZipFileNameWebPi)" />
<GenerateHash InputFiles="@(WebPiFile)" OutputFile="webpihash.txt" />
</Target>
<Target Name="CleanUp" DependsOnTargets="ZipWebPiApp">
<Message Text="Deleting $(BuildFolder)" Importance="high" />
<RemoveDir Directories="$(BuildFolder)" />
<Message Text="Finished deleting $(BuildFolder)" Importance="high" />
</Target>
<Target Name="ZipWebPiApp" DependsOnTargets="ZipWebApp" >
<!-- Clean folders -->
<RemoveDir Directories="$(WebPiFolder)" />
<MakeDir Directories="$(WebPiFolder)" />
<MakeDir Directories="$(WebPiFolder)umbraco" />
<!-- Copy fresh built umbraco files -->
<Exec Command="xcopy %22$(WebAppFolderAbsolutePath)*%22 %22$(WebPiFolderAbsolutePath)umbraco%22 /S /E /Y /I" />
<!-- Copy Web Pi template files -->
<ItemGroup>
<WebPiFiles Include="..\src\WebPi\**\*.*" />
</ItemGroup>
<Copy SourceFiles="@(WebPiFiles)"
DestinationFiles="@(WebPiFiles->'$(WebPiFolder)%(RecursiveDir)%(Filename)%(Extension)')" />
<!-- Zip the files -->
<Exec Command="..\tools\7zip\7za.exe a -r %22$(BuildZipFileNameWebPi)%22 %22$(WebPiFolderAbsolutePath)*%22 -x!dotLess.Core.dll -x![Content_Types].xml >NUL" />
</Target>
<Target Name="ZipWebApp" DependsOnTargets="CreateSystemFolders" >
<Message Text="Starting to zip to $(buildDate)-$(BuildZipFileName)" Importance="high" />
<Exec Command="..\tools\7zip\7za.exe a -r %22$(BuildZipFileNameBin)%22 %22$(SolutionBinFolderAbsolutePath)*%22 -x!dotLess.Core.dll >NUL" />
<Exec Command="..\tools\7zip\7za.exe a -r %22$(BuildZipFileName)%22 %22$(WebAppFolderAbsolutePath)*%22 -x!dotLess.Core.dll -x![Content_Types].xml >NUL" />
<Message Text="Finished zipping to build\$(BuildFolder)\$(buildDate)-$(BuildZipFileName)" Importance="high" />
</Target>
<Target Name="CreateSystemFolders" DependsOnTargets="CopyBelleBuild" Inputs="@(SystemFolders)" Outputs="%(Identity).Dummy">
<MakeDir Directories="@(SystemFolders)" />
</Target>
<Target Name="CopyBelleBuild" DependsOnTargets="CopyLibraries" >
<ItemGroup>
<BelleFiles Include="..\src\Umbraco.Web.UI.Client\build\belle\**\*.*" Exclude="..\src\Umbraco.Web.UI.Client\build\belle\index.html" />
</ItemGroup>
<Copy SourceFiles="@(BelleFiles)"
DestinationFiles="@(BelleFiles->'$(WebAppFolder)umbraco\%(RecursiveDir)%(Filename)%(Extension)')"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
</Target>
<Target Name="CopyLibraries" DependsOnTargets="OffsetTimestamps" >
<!-- Copy SQL CE -->
<ItemGroup>
<SQLCE4Files
Include="..\src\packages\SqlServerCE.4.0.0.1\**\*.*"
Exclude="..\src\packages\SqlServerCE.4.0.0.1\lib\**\*;..\src\packages\SqlServerCE.4.0.0.1\**\*.nu*"
/>
</ItemGroup>
<Copy SourceFiles="@(SQLCE4Files)"
DestinationFiles="@(SQLCE4Files->'$(SolutionBinFolder)%(RecursiveDir)%(Filename)%(Extension)')"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
<Copy SourceFiles="@(SQLCE4Files)"
DestinationFiles="@(SQLCE4Files->'$(WebAppFolder)bin\%(RecursiveDir)%(Filename)%(Extension)')"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
</Target>
<!-- Offset the modified timestamps on all umbraco dlls, as WebResources break if date is in the future, which, due to timezone offsets can happen. -->
<Target Name="OffsetTimestamps" DependsOnTargets="CopyTransformedWebConfig">
<CreateItem Include="$(BuildFolder)**\umbraco.*.dll">
<Output TaskParameter="Include" ItemName="FilesToOffsetTimestamp" />
</CreateItem>
<Message Text="Starting to offset timestamps" Importance="high" />
<Umbraco.MSBuild.Tasks.TimestampOffset Files="@(FilesToOffsetTimestamp)" Offset="-11" />
<Message Text="Finished offsetting timestamps" Importance="high" />
</Target>
<!-- Copy the transformed web.config file to the root -->
<Target Name="CopyTransformedWebConfig" DependsOnTargets="CopyTransformedConfig">
<ItemGroup>
<WebConfigFile Include="..\src\Umbraco.Web.UI\web.$(BuildConfiguration).Config.transformed" />
</ItemGroup>
<Copy SourceFiles="@(WebConfigFile)"
DestinationFiles="$(WebAppFolder)Web.config"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
</Target>
<!-- Copy the config files and rename them to *.config.transform -->
<Target Name="CopyTransformedConfig" DependsOnTargets="CopyXmlDocumentation">
<ItemGroup>
<ConfigFiles Include="$(WebAppFolder)config\*.config;$(WebAppFolder)config\*.js" />
<CustomLanguageFiles Include="$(WebAppFolder)config\lang\*.xml" />
<WebConfigTransformFile Include="$(WebAppFolder)Web.config" />
</ItemGroup>
<Copy SourceFiles="@(ConfigFiles)"
DestinationFiles="@(ConfigFiles->'$(ConfigsFolder)\%(RecursiveDir)%(Filename)%(Extension)')"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
<Copy SourceFiles="@(CustomLanguageFiles)"
DestinationFiles="@(CustomLanguageFiles->'$(ConfigsFolder)Lang\%(RecursiveDir)%(Filename)%(Extension)')"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
<Copy SourceFiles="@(WebConfigTransformFile)"
DestinationFiles="$(ConfigsFolder)Web.config.transform"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
</Target>
<!-- Copy the xml documentation to the bin folder -->
<Target Name="CopyXmlDocumentation" DependsOnTargets="CleanupPresentation">
<ItemGroup>
<XmlDocumentationFiles Include="$(SolutionBinFolder)*.xml" />
</ItemGroup>
<Copy SourceFiles="@(XmlDocumentationFiles)"
DestinationFiles="@(XmlDocumentationFiles->'$(WebAppFolder)bin\%(RecursiveDir)%(Filename)%(Extension)')"
OverwriteReadOnlyFiles="true"
SkipUnchangedFiles="false" />
<Message Text="CopyXmlDocumentation" />
</Target>
<!-- Unlike 2010, the VS2012 build targets file doesn't clean up the umbraco.presentation dir, do it manually -->
<Target Name="CleanupPresentation" DependsOnTargets="CompileProjects">
<ItemGroup>
<PresentationFolderToDelete Include="$(WebAppFolder)umbraco.presentation" />
</ItemGroup>
<RemoveDir Directories="@(PresentationFolderToDelete)" />
</Target>
<Target Name="CompileProjects" DependsOnTargets="SetVersionNumber">
<Message Text="Compiling web project to build\$(BuildFolder)" Importance="high" />
<!-- For UseWPP_CopyWebApplication=True see http://stackoverflow.com/questions/1983575/copywebapplication-with-web-config-transformations -->
<!-- Build the Umbraco.Web.UI project -->
<MSBuild Projects="..\src\Umbraco.Web.UI\Umbraco.Web.UI.csproj" Properties="WarningLevel=0;Configuration=$(BuildConfiguration);UseWPP_CopyWebApplication=True;PipelineDependsOnBuild=False;OutDir=$(SolutionBinFolderAbsolutePath);WebProjectOutputDir=$(WebAppFolderAbsolutePath);Verbosity=minimal" Targets="Clean;Rebuild;" BuildInParallel="False" ToolsVersion="4.0" UnloadProjectsOnCompletion="False" />
<!-- DONE -->
<Message Text="Finished compiling projects" Importance="high" />
</Target>
<Target Name="SetVersionNumber" Condition="'$(BUILD_RELEASE)'!=''">
<PropertyGroup>
<NewVersion>$(BUILD_RELEASE)</NewVersion>
<NewVersion Condition="'$(BUILD_COMMENT)'!=''">$(BUILD_RELEASE)-$(BUILD_COMMENT)</NewVersion>
<NewVersion Condition="'$(BUILD_NIGHTLY)'!=''">$(BUILD_RELEASE)-$(BUILD_NIGHTLY)</NewVersion>
<NewVersion Condition="'$(BUILD_COMMENT)'!='' And '$(BUILD_NIGHTLY)'!=''">$(BUILD_RELEASE)-$(BUILD_COMMENT)-$(BUILD_NIGHTLY)</NewVersion>
</PropertyGroup>
<!-- Match & replace 3 and 4 digit version numbers and -beta and +nightly (if they're there) -->
<FileUpdate
Files="..\src\Umbraco.Core\Configuration\UmbracoVersion.cs"
Regex="(\d+)\.(\d+)\.(\d+)(.(\d+))?"
ReplacementText="$(BUILD_RELEASE)"/>
<FileUpdate Files="..\src\Umbraco.Core\Configuration\UmbracoVersion.cs"
Regex="CurrentComment { get { return &quot;(.+)?&quot;"
ReplacementText="CurrentComment { get { return &quot;$(BUILD_COMMENT)&quot;"/>
<FileUpdate Files="..\src\Umbraco.Core\Configuration\UmbracoVersion.cs"
Condition="'$(BUILD_NIGHTLY)'!=''"
Regex="CurrentComment { get { return &quot;(.+)?&quot;"
ReplacementText="CurrentComment { get { return &quot;$(BUILD_NIGHTLY)&quot;"/>
<FileUpdate Files="..\src\Umbraco.Core\Configuration\UmbracoVersion.cs"
Condition="'$(BUILD_COMMENT)'!='' AND '$(BUILD_NIGHTLY)'!=''"
Regex="CurrentComment { get { return &quot;(.+)?&quot;"
ReplacementText="CurrentComment { get { return &quot;$(BUILD_COMMENT)-$(BUILD_NIGHTLY)&quot;"/>
<!--This updates the AssemblyFileVersion for the solution to the umbraco version-->
<FileUpdate
Files="..\src\SolutionInfo.cs"
Regex="AssemblyFileVersion\(&quot;(.+)?&quot;\)"
ReplacementText="AssemblyFileVersion(&quot;$(BUILD_RELEASE)&quot;)"/>
<!--This updates the AssemblyInformationalVersion for the solution to the umbraco version and comment-->
<FileUpdate
Condition="'$(BUILD_COMMENT)'!=''"
Files="..\src\SolutionInfo.cs"
Regex="AssemblyInformationalVersion\(&quot;(.+)?&quot;\)"
ReplacementText="AssemblyInformationalVersion(&quot;$(BUILD_RELEASE)-$(BUILD_COMMENT)&quot;)"/>
<FileUpdate
Condition="'$(BUILD_COMMENT)'==''"
Files="..\src\SolutionInfo.cs"
Regex="AssemblyInformationalVersion\(&quot;(.+)?&quot;\)"
ReplacementText="AssemblyInformationalVersion(&quot;$(BUILD_RELEASE)&quot;)"/>
<FileUpdate
Condition="'$(BUILD_NIGHTLY)'!=''"
Files="..\src\SolutionInfo.cs"
Regex="AssemblyInformationalVersion\(&quot;(.+)?&quot;\)"
ReplacementText="AssemblyInformationalVersion(&quot;$(BUILD_RELEASE)-$(BUILD_NIGHTLY)&quot;)"/>
<FileUpdate
Condition="'$(BUILD_COMMENT)'!='' AND '$(BUILD_NIGHTLY)'!=''"
Files="..\src\SolutionInfo.cs"
Regex="AssemblyInformationalVersion\(&quot;(.+)?&quot;\)"
ReplacementText="AssemblyInformationalVersion(&quot;$(BUILD_RELEASE)-$(BUILD_COMMENT)-$(BUILD_NIGHTLY)&quot;)"/>
<FileUpdate
Condition="'$(BUILD_COMMENT)'=='' AND '$(BUILD_NIGHTLY)'==''"
Files="..\src\SolutionInfo.cs"
Regex="AssemblyInformationalVersion\(&quot;(.+)?&quot;\)"
ReplacementText="AssemblyInformationalVersion(&quot;$(BUILD_RELEASE)&quot;)"/>
<!--This updates the copyright year-->
<FileUpdate
Files="..\src\SolutionInfo.cs"
Regex="AssemblyCopyright\(&quot;Copyright © Umbraco (\d{4})&quot;\)"
ReplacementText="AssemblyCopyright(&quot;Copyright © Umbraco $([System.DateTime]::Now.ToString(`yyyy`))&quot;)"/>
<XmlPoke XmlInputPath=".\NuSpecs\build\UmbracoCms.props"
Namespaces="&lt;Namespace Prefix='x' Uri='http://schemas.microsoft.com/developer/msbuild/2003' /&gt;"
Query="//x:UmbracoVersion"
Value="$(NewVersion)" />
</Target>
</Project>
-68
View File
@@ -1,68 +0,0 @@
@ECHO OFF
SETLOCAL
:: SETLOCAL is on, so changes to the path not persist to the actual user's path
SET toolsFolder=%CD%\tools\
ECHO Current folder: %CD%
SET nodeFileName=node-v6.9.1-win-x86.7z
SET nodeExtractFolder=%toolsFolder%node.js.691
SET nuGetExecutable=%CD%\tools\nuget.exe
IF NOT EXIST "%nuGetExecutable%" (
ECHO Downloading https://dist.nuget.org/win-x86-commandline/latest/nuget.exe to %nuGetExecutable%
powershell -Command "(New-Object Net.WebClient).DownloadFile('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe', '%nuGetExecutable%')"
)
:: We need 7za.exe for BuildBelle.bat
IF NOT EXIST "%toolsFolder%7za.exe" (
ECHO 7zip not found - fetching now
"%nuGetExecutable%" install 7-Zip.CommandLine -OutputDirectory tools -Verbosity quiet
)
:: Put 7za.exe and vswhere.exe in a predictable path (not version specific)
FOR /f "delims=" %%A in ('dir "%toolsFolder%7-Zip.CommandLine.*" /b') DO SET "sevenZipExePath=%toolsFolder%%%A\"
MOVE "%sevenZipExePath%tools\7za.exe" "%toolsFolder%7za.exe"
IF NOT EXIST "%nodeExtractFolder%" (
ECHO Downloading http://nodejs.org/dist/v6.9.1/%nodeFileName% to %toolsFolder%%nodeFileName%
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://nodejs.org/dist/v6.9.1/%nodeFileName%', '%toolsFolder%%nodeFileName%')"
ECHO Extracting %nodeFileName% to %nodeExtractFolder%
"%toolsFolder%\7za.exe" x "%toolsFolder%\%nodeFileName%" -o"%nodeExtractFolder%" -aos > nul
)
FOR /f "delims=" %%A in ('dir "%nodeExtractFolder%\node*" /b') DO SET "nodePath=%nodeExtractFolder%\%%A"
SET drive=%CD:~0,2%
SET nuGetFolder=%drive%\packages\
FOR /f "delims=" %%A in ('dir "%nuGetFolder%npm.*" /b') DO SET "npmPath=%nuGetFolder%%%A\"
IF [%npmPath%] == [] GOTO :installnpm
IF NOT [%npmPath%] == [] GOTO :build
:installnpm
ECHO Downloading npm
ECHO Configured packages folder: %nuGetFolder%
ECHO Installing Npm NuGet Package
"%nuGetExecutable%" install Npm -OutputDirectory %nuGetFolder% -Verbosity detailed
REM Ensures that we look for the just downloaded NPM, not whatever the user has installed on their machine
FOR /f "delims=" %%A in ('dir %nuGetFolder%npm.* /b') DO SET "npmPath=%nuGetFolder%%%A\"
GOTO :build
:build
ECHO Adding Npm and Node to path
REM SETLOCAL is on, so changes to the path not persist to the actual user's path
PATH="%npmPath%";"%nodePath%";%PATH%
SET buildFolder=%CD%
ECHO Change directory to %CD%\..\src\Umbraco.Web.UI.Client\
CD %CD%\..\src\Umbraco.Web.UI.Client\
ECHO Do npm install and the grunt build of Belle
call npm cache clean --quiet
call npm install --quiet
call npm install -g grunt-cli --quiet
call npm install -g bower --quiet
call grunt build --buildversion=%release%
ECHO Move back to the build folder
CD "%buildFolder%"
-20
View File
@@ -1,20 +0,0 @@
@ECHO OFF
SETLOCAL
SET release=%1
ECHO Installing Npm NuGet Package
SET nuGetFolder=%CD%\..\src\packages\
ECHO Configured packages folder: %nuGetFolder%
ECHO Current folder: %CD%
%CD%\..\src\.nuget\NuGet.exe install Npm.js -OutputDirectory %nuGetFolder% -Verbosity quiet
for /f "delims=" %%A in ('dir %nuGetFolder%node.js.* /b') do set "nodePath=%nuGetFolder%%%A\"
for /f "delims=" %%A in ('dir %nuGetFolder%npm.js.* /b') do set "npmPath=%nuGetFolder%%%A\tools\"
ECHO Adding Npm and Node to path
REM SETLOCAL is on, so changes to the path not persist to the actual user's path
PATH=%npmPath%;%nodePath%;%PATH%
Powershell.exe -ExecutionPolicy Unrestricted -File .\BuildDocs.ps1
-114
View File
@@ -1,114 +0,0 @@
$PSScriptFilePath = (Get-Item $MyInvocation.MyCommand.Path);
$RepoRoot = (get-item $PSScriptFilePath).Directory.Parent.FullName;
$SolutionRoot = Join-Path -Path $RepoRoot "src";
$ToolsRoot = Join-Path -Path $RepoRoot "tools";
$DocFx = Join-Path -Path $ToolsRoot "docfx\docfx.exe"
$DocFxFolder = (Join-Path -Path $ToolsRoot "docfx")
$DocFxJson = Join-Path -Path $RepoRoot "apidocs\docfx.json"
$7Zip = Join-Path -Path $ToolsRoot "7zip\7za.exe"
$DocFxSiteOutput = Join-Path -Path $RepoRoot "apidocs\_site\*.*"
$NgDocsSiteOutput = Join-Path -Path $RepoRoot "src\Umbraco.Web.UI.Client\docs\api\*.*"
$ProgFiles86 = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)");
$MSBuild = "$ProgFiles86\MSBuild\14.0\Bin\MSBuild.exe"
################ Do the UI docs
"Changing to Umbraco.Web.UI.Client folder"
cd ..
cd src\Umbraco.Web.UI.Client
Write-Host $(Get-Location)
"Creating build folder so MSBuild doesn't run the whole grunt build"
if (-Not (Test-Path "build")) {
md "build"
}
"Installing node"
# Check if Install-Product exists, should only exist on the build server
if (Get-Command Install-Product -errorAction SilentlyContinue)
{
Install-Product node ''
}
"Installing node modules"
& npm install
"Installing grunt"
& npm install -g grunt-cli
"Moving back to build folder"
cd ..
cd ..
cd build
Write-Host $(Get-Location)
& grunt --gruntfile ../src/umbraco.web.ui.client/gruntfile.js docs
# change baseUrl
$BaseUrl = "https://our.umbraco.org/apidocs/ui/"
$IndexPath = "../src/umbraco.web.ui.client/docs/api/index.html"
(Get-Content $IndexPath).replace('location.href.replace(rUrl, indexFile)', "`'" + $BaseUrl + "`'") | Set-Content $IndexPath
# zip it
& $7Zip a -tzip ui-docs.zip $NgDocsSiteOutput -r
################ Do the c# docs
# Build the solution in debug mode
$SolutionPath = Join-Path -Path $SolutionRoot -ChildPath "umbraco.sln"
# Go get nuget.exe if we don't hae it
$NuGet = "$ToolsRoot\nuget.exe"
$FileExists = Test-Path $NuGet
If ($FileExists -eq $False) {
Write-Host "Retrieving nuget.exe..."
$SourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
Invoke-WebRequest $SourceNugetExe -OutFile $NuGet
}
#restore nuget packages
Write-Host "Restoring nuget packages..."
& $NuGet restore $SolutionPath
& $MSBuild "$SolutionPath" /p:Configuration=Debug /maxcpucount /t:Clean
if (-not $?)
{
throw "The MSBuild process returned an error code."
}
& $MSBuild "$SolutionPath" /p:Configuration=Debug /maxcpucount
if (-not $?)
{
throw "The MSBuild process returned an error code."
}
# Go get docfx if we don't hae it
$FileExists = Test-Path $DocFx
If ($FileExists -eq $False) {
If(!(Test-Path $DocFxFolder))
{
New-Item $DocFxFolder -type directory
}
$DocFxZip = Join-Path -Path $ToolsRoot "docfx\docfx.zip"
$DocFxSource = "https://github.com/dotnet/docfx/releases/download/v1.9.4/docfx.zip"
Invoke-WebRequest $DocFxSource -OutFile $DocFxZip
#unzip it
& $7Zip e $DocFxZip "-o$DocFxFolder"
}
#clear site
If(Test-Path(Join-Path -Path $RepoRoot "apidocs\_site"))
{
Remove-Item $DocFxSiteOutput -recurse
}
# run it!
& $DocFx metadata $DocFxJson
& $DocFx build $DocFxJson
# zip it
& $7Zip a -tzip csharp-docs.zip $DocFxSiteOutput -r
@@ -0,0 +1,117 @@
#
function Build-UmbracoDocs
{
$uenv = Get-UmbracoBuildEnv
$src = "$($uenv.SolutionRoot)\src"
$out = "$($uenv.SolutionRoot)\build.out"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$buildTemp = "$PSScriptRoot\temp"
$cache = 2
Prepare-Build -keep $uenv
################ Do the UI docs
# No need to build belle again if it exists
$belleAppJs = "$src\Umbraco.Web.UI\Umbraco\js\app.js"
if(-not (Test-Path $belleAppJs))
{
# get a temp clean node env (will restore)
Sandbox-Node $uenv
push-location "$($uenv.SolutionRoot)\src\Umbraco.Web.UI.Client"
write "node version is:" > $tmp\belle.log
&node -v >> $tmp\belle.log 2>&1
write "npm version is:" >> $tmp\belle.log 2>&1
&npm -v >> $tmp\belle.log 2>&1
write "cleaning npm cache" >> $tmp\belle.log 2>&1
&npm cache clean >> $tmp\belle.log 2>&1
write "installing bower" >> $tmp\belle.log 2>&1
&npm install -g bower >> $tmp\belle.log 2>&1
write "installing gulp" >> $tmp\belle.log 2>&1
&npm install -g gulp >> $tmp\belle.log 2>&1
write "installing gulp-cli" >> $tmp\belle.log 2>&1
&npm install -g gulp-cli --quiet >> $tmp\belle.log 2>&1
write "executing npm install" >> $tmp\belle.log 2>&1
&npm install >> $tmp\belle.log 2>&1
write "building docs using gulp" >> $tmp\belle.log 2>&1
&gulp docs >> $tmp\belle.log 2>&1
pop-location
# fixme - should we filter the log to find errors?
#get-content .\build.tmp\belle-docs.log | %{ if ($_ -match "build") { write $_}}
} else {
Write-Host "Skipping belle build, $belleAppJs already exists"
}
# change baseUrl
$baseUrl = "https://our.umbraco.org/apidocs/ui/"
$indexPath = "$src/Umbraco.Web.UI.Client/docs/api/index.html"
(Get-Content $indexPath).Replace("location.href.replace(rUrl, indexFile)", "'$baseUrl'") `
| Set-Content $indexPath
# restore
Restore-Node
# zip
&$uenv.Zip a -tzip -r "$out\ui-docs.zip" "$src\Umbraco.Web.UI.Client\docs\api\*.*" `
> $null
################ Do the c# docs
Write-Host "Build C# documentation"
# Build the solution in debug mode
# FIXME no only a simple compilation should be enough!
# FIXME we MUST handle msbuild & co error codes!
# FIXME deal with weird things in gitconfig?
#Build-Umbraco -Configuration Debug
Restore-NuGet $uenv
Compile-Umbraco $uenv "Debug" # FIXME different log file!
Restore-WebConfig "$src\Umbraco.Web.UI"
# ensure we have docfx
Get-DocFx $uenv $buildTemp
# clear
$docFxOutput = "$($uenv.SolutionRoot)\apidocs\_site"
if (test-path($docFxOutput))
{
Remove-Directory $docFxOutput
}
# run
$docFxJson = "$($uenv.SolutionRoot)\apidocs\docfx.json"
push-location "$($uenv.SolutionRoot)\build" # silly docfx.json wants this
Write-Host "Run DocFx metadata"
Write-Host "Logging to $tmp\docfx.metadata.log"
&$uenv.DocFx metadata $docFxJson > "$tmp\docfx.metadata.log"
Write-Host "Run DocFx build"
Write-Host "Logging to $tmp\docfx.build.log"
&$uenv.DocFx build $docFxJson > "$tmp\docfx.build.log"
pop-location
# zip
&$uenv.Zip a -tzip -r "$out\csharp-docs.zip" "$docFxOutput\*.*" `
> $null
}
function Get-DocFx($uenv, $buildTemp)
{
$docFx = "$buildTemp\docfx"
if (-not (test-path $docFx))
{
Write-Host "Download DocFx..."
$source = "https://github.com/dotnet/docfx/releases/download/v2.19.2/docfx.zip"
Invoke-WebRequest $source -OutFile "$buildTemp\docfx.zip"
&$uenv.Zip x "$buildTemp\docfx.zip" -o"$buildTemp\docfx" -aos > $nul
Remove-File "$buildTemp\docfx.zip"
}
$uenv | add-member -memberType NoteProperty -name DocFx -value "$docFx\docfx.exe"
}
@@ -0,0 +1,180 @@
#
# Get-UmbracoBuildEnv
# Gets the Umbraco build environment
# Downloads tools if necessary
#
function Get-UmbracoBuildEnv
{
# store tools in the module's directory
# and cache them for two days
$path = "$PSScriptRoot\temp"
$cache = 2
if (-not (test-path $path))
{
mkdir $path > $null
}
# ensure we have NuGet
$nuget = "$path\nuget.exe"
$source = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe"
if ((test-path $nuget) -and ((ls $nuget).CreationTime -lt [DateTime]::Now.AddDays(-$cache)))
{
Remove-File $nuget
}
if (-not (test-path $nuget))
{
Write-Host "Download NuGet..."
Invoke-WebRequest $source -OutFile $nuget
}
# ensure we have 7-Zip
$sevenZip = "$path\7za.exe"
if ((test-path $sevenZip) -and ((ls $sevenZip).CreationTime -lt [DateTime]::Now.AddDays(-$cache)))
{
Remove-File $sevenZip
}
if (-not (test-path $sevenZip))
{
Write-Host "Download 7-Zip..."
&$nuget install 7-Zip.CommandLine -OutputDirectory $path -Verbosity quiet
$dir = ls "$path\7-Zip.CommandLine.*" | sort -property Name -descending | select -first 1
$file = ls -path "$dir" -name 7za.exe -recurse
mv "$dir\$file" $sevenZip
Remove-Directory $dir
}
# ensure we have vswhere
$vswhere = "$path\vswhere.exe"
if ((test-path $vswhere) -and ((ls $vswhere).CreationTime -lt [DateTime]::Now.AddDays(-$cache)))
{
Remove-File $vswhere
}
if (-not (test-path $vswhere))
{
Write-Host "Download VsWhere..."
&$nuget install vswhere -OutputDirectory $path -Verbosity quiet
$dir = ls "$path\vswhere.*" | sort -property Name -descending | select -first 1
$file = ls -path "$dir" -name vswhere.exe -recurse
mv "$dir\$file" $vswhere
Remove-Directory $dir
}
# ensure we have semver
$semver = "$path\Semver.dll"
if ((test-path $semver) -and ((ls $semver).CreationTime -lt [DateTime]::Now.AddDays(-$cache)))
{
Remove-File $semver
}
if (-not (test-path $semver))
{
Write-Host "Download Semver..."
&$nuget install semver -OutputDirectory $path -Verbosity quiet
$dir = ls "$path\semver.*" | sort -property Name -descending | select -first 1
$file = "$dir\lib\net452\Semver.dll"
if (-not (test-path $file))
{
Write-Error "Failed to file $file"
return
}
mv "$file" $semver
Remove-Directory $dir
}
try
{
[Reflection.Assembly]::LoadFile($semver) > $null
}
catch
{
Write-Error -Exception $_.Exception -Message "Failed to load $semver"
break
}
# ensure we have node
$node = "$path\node-v6.9.1-win-x86"
$source = "http://nodejs.org/dist/v6.9.1/node-v6.9.1-win-x86.7z"
if (-not (test-path $node))
{
Write-Host "Download Node..."
Invoke-WebRequest $source -OutFile "$path\node-v6.9.1-win-x86.7z"
&$sevenZip x "$path\node-v6.9.1-win-x86.7z" -o"$path" -aos > $nul
Remove-File "$path\node-v6.9.1-win-x86.7z"
}
# note: why? node already brings everything we need!
## ensure we have npm
#$npm = "$path\npm.*"
#$getNpm = $true
#if (test-path $npm)
#{
# $getNpm = $false
# $tmpNpm = ls "$path\npm.*" | sort -property Name -descending | select -first 1
# if ($tmpNpm.CreationTime -lt [DateTime]::Now.AddDays(-$cache))
# {
# $getNpm = $true
# }
# else
# {
# $npm = $tmpNpm.ToString()
# }
#}
#if ($getNpm)
#{
# Write-Host "Download Npm..."
# &$nuget install npm -OutputDirectory $path -Verbosity quiet
# $npm = ls "$path\npm.*" | sort -property Name -descending | select -first 1
# $npm.CreationTime = [DateTime]::Now
# $npm = $npm.ToString()
#}
# find visual studio
# will not work on VSO but VSO does not need it
$vsPath = ""
$vsVer = ""
$msBuild = $null
&$vswhere | foreach {
if ($_.StartsWith("installationPath:")) { $vsPath = $_.SubString("installationPath:".Length).Trim() }
if ($_.StartsWith("installationVersion:")) { $vsVer = $_.SubString("installationVersion:".Length).Trim() }
}
if ($vsPath -ne "")
{
$vsVerParts = $vsVer.Split('.')
$vsMajor = [int]::Parse($vsVerParts[0])
$vsMinor = [int]::Parse($vsVerParts[1])
if ($vsMajor -eq 15) {
$msBuild = "$vsPath\MSBuild\$vsMajor.0\Bin"
}
elseif ($vsMajor -eq 14) {
$msBuild = "c:\Program Files (x86)\MSBuild\$vsMajor\Bin"
}
else
{
$msBuild = $null
}
}
$vs = $null
if ($msBuild)
{
$vs = new-object -typeName PsObject
$vs | add-member -memberType NoteProperty -name Path -value $vsPath
$vs | add-member -memberType NoteProperty -name Major -value $vsMajor
$vs | add-member -memberType NoteProperty -name Minor -value $vsMinor
$vs | add-member -memberType NoteProperty -name MsBuild -value "$msBuild\MsBuild.exe"
}
$solutionRoot = Get-FullPath "$PSScriptRoot\..\..\.."
$uenv = new-object -typeName PsObject
$uenv | add-member -memberType NoteProperty -name SolutionRoot -value $solutionRoot
$uenv | add-member -memberType NoteProperty -name VisualStudio -value $vs
$uenv | add-member -memberType NoteProperty -name NuGet -value $nuget
$uenv | add-member -memberType NoteProperty -name Zip -value $sevenZip
$uenv | add-member -memberType NoteProperty -name VsWhere -value $vswhere
$uenv | add-member -memberType NoteProperty -name Semver -value $semver
$uenv | add-member -memberType NoteProperty -name NodePath -value $node
#$uenv | add-member -memberType NoteProperty -name NpmPath -value $npm
return $uenv
}
@@ -0,0 +1,26 @@
#
# Get-UmbracoVersion
# Gets the Umbraco version
#
function Get-UmbracoVersion
{
$uenv = Get-UmbracoBuildEnv
# parse SolutionInfo and retrieve the version string
$filepath = "$($uenv.SolutionRoot)\src\SolutionInfo.cs"
$text = [System.IO.File]::ReadAllText($filepath)
$match = [System.Text.RegularExpressions.Regex]::Matches($text, "AssemblyInformationalVersion\(`"(.+)?`"\)")
$version = $match.Groups[1]
# semver-parse the version string
$semver = [SemVer.SemVersion]::Parse($version)
$release = "" + $semver.Major + "." + $semver.Minor + "." + $semver.Patch
$versions = new-object -typeName PsObject
$versions | add-member -memberType NoteProperty -name Semver -value $semver
$versions | add-member -memberType NoteProperty -name Release -value $release
$versions | add-member -memberType NoteProperty -name Comment -value $semver.PreRelease
$versions | add-member -memberType NoteProperty -name Build -value $semver.Build
return $versions
}
@@ -0,0 +1,30 @@
# finds msbuild
function Get-VisualStudio($vswhere)
{
$vsPath = ""
$vsVer = ""
&$vswhere | foreach {
if ($_.StartsWith("installationPath:")) { $vsPath = $_.SubString("installationPath:".Length).Trim() }
if ($_.StartsWith("installationVersion:")) { $vsVer = $_.SubString("installationVersion:".Length).Trim() }
}
if ($vsPath -eq "") { return $null }
$vsVerParts = $vsVer.Split('.')
$vsMajor = [int]::Parse($vsVerParts[0])
$vsMinor = [int]::Parse($vsVerParts[1])
if ($vsMajor -eq 15) {
$msBuild = "$vsPath\MSBuild\$vsMajor.$vsMinor\Bin"
}
elseif ($vsMajor -eq 14) {
$msBuild = "c:\Program Files (x86)\MSBuild\$vsMajor\Bin"
}
else { return $null }
$msBuild = "$msBuild\MsBuild.exe"
$vs = new-object -typeName PsObject
$vs | add-member -memberType NoteProperty -name Path -value $vsPath
$vs | add-member -memberType NoteProperty -name Major -value $vsMajor
$vs | add-member -memberType NoteProperty -name Minor -value $vsMinor
$vs | add-member -memberType NoteProperty -name MsBuild -value $msBuild
return $vs
}
@@ -0,0 +1,30 @@
#
# Set-UmbracoContinuousVersion
# Sets the Umbraco version for continuous integration
#
# -Version <version>
# where <version> is a Semver valid version
# eg 1.2.3, 1.2.3-alpha, 1.2.3-alpha+456
#
# -BuildNumber <buildNumber>
# where <buildNumber> is a string coming from the build server
# eg 34, 126, 1
#
function Set-UmbracoContinuousVersion
{
param (
[Parameter(Mandatory=$true)]
[string]
$version,
[Parameter(Mandatory=$true)]
[string]
$buildNumber
)
Write-Host "Version is currently set to $version"
$umbracoVersion = "$($version.Trim())-alpha$($buildNumber)"
Write-Host "Setting Umbraco Version to $umbracoVersion"
Set-UmbracoVersion $umbracoVersion
}
@@ -0,0 +1,117 @@
#
# Set-UmbracoVersion
# Sets the Umbraco version
#
# -Version <version>
# where <version> is a Semver valid version
# eg 1.2.3, 1.2.3-alpha, 1.2.3-alpha+456
#
function Set-UmbracoVersion
{
param (
[Parameter(Mandatory=$true)]
[string]
$version
)
$uenv = Get-UmbracoBuildEnv
try
{
[Reflection.Assembly]::LoadFile($uenv.Semver) > $null
}
catch
{
Write-Error "Failed to load $uenv.Semver"
break
}
# validate input
$ok = [Regex]::Match($version, "^[0-9]+\.[0-9]+\.[0-9]+(\-[a-z0-9]+)?(\+[0-9]+)?$")
if (-not $ok.Success)
{
Write-Error "Invalid version $version"
break
}
# parse input
try
{
$semver = [SemVer.SemVersion]::Parse($version)
}
catch
{
Write-Error "Invalid version $version"
break
}
#
$release = "" + $semver.Major + "." + $semver.Minor + "." + $semver.Patch
# edit files and set the proper versions and dates
Write-Host "Update UmbracoVersion.cs"
Replace-FileText "$($uenv.SolutionRoot)\src\Umbraco.Core\Configuration\UmbracoVersion.cs" `
"(\d+)\.(\d+)\.(\d+)(.(\d+))?" `
"$release"
Replace-FileText "$($uenv.SolutionRoot)\src\Umbraco.Core\Configuration\UmbracoVersion.cs" `
"CurrentComment { get { return `"(.+)`"" `
"CurrentComment { get { return `"$($semver.PreRelease)`""
Write-Host "Update SolutionInfo.cs"
Replace-FileText "$($uenv.SolutionRoot)\src\SolutionInfo.cs" `
"AssemblyFileVersion\(`"(.+)?`"\)" `
"AssemblyFileVersion(`"$release`")"
Replace-FileText "$($uenv.SolutionRoot)\src\SolutionInfo.cs" `
"AssemblyInformationalVersion\(`"(.+)?`"\)" `
"AssemblyInformationalVersion(`"$semver`")"
$year = [System.DateTime]::Now.ToString("yyyy")
Replace-FileText "$($uenv.SolutionRoot)\src\SolutionInfo.cs" `
"AssemblyCopyright\(`"Copyright © Umbraco (\d{4})`"\)" `
"AssemblyCopyright(`"Copyright © Umbraco $year`")"
# edit csproj and set IIS Express port number
# this is a raw copy of ReplaceIISExpressPortNumber.exe
# it probably can be achieved in a much nicer way - l8tr
$source = @"
using System;
using System.IO;
using System.Xml;
using System.Globalization;
namespace Umbraco
{
public static class PortUpdater
{
public static void Update(string path, string release)
{
XmlDocument xmlDocument = new XmlDocument();
string fullPath = Path.GetFullPath(path);
xmlDocument.Load(fullPath);
int result = 1;
int.TryParse(release.Replace(`".`", `"`"), out result);
while (result < 1024)
result *= 10;
XmlNode xmlNode1 = xmlDocument.GetElementsByTagName(`"IISUrl`").Item(0);
if (xmlNode1 != null)
xmlNode1.InnerText = `"http://localhost:`" + (object) result;
XmlNode xmlNode2 = xmlDocument.GetElementsByTagName(`"DevelopmentServerPort`").Item(0);
if (xmlNode2 != null)
xmlNode2.InnerText = result.ToString((IFormatProvider) CultureInfo.InvariantCulture);
xmlDocument.Save(fullPath);
}
}
}
"@
$assem = (
"System.Xml",
"System.IO",
"System.Globalization"
)
Write-Host "Update Umbraco.Web.UI.csproj"
add-type -referencedAssemblies $assem -typeDefinition $source -language CSharp
$csproj = "$($uenv.SolutionRoot)\src\Umbraco.Web.UI\Umbraco.Web.UI.csproj"
[Umbraco.PortUpdater]::Update($csproj, $release)
return $semver
}
@@ -0,0 +1,605 @@
# Umbraco.Build.psm1
#
# $env:PSModulePath = "$pwd\build\Modules\;$env:PSModulePath"
# Import-Module Umbraco.Build -Force -DisableNameChecking
#
# PowerShell Modules:
# https://msdn.microsoft.com/en-us/library/dd878324%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
#
# PowerShell Module Manifest:
# https://msdn.microsoft.com/en-us/library/dd878337%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
#
# See also
# http://www.powershellmagazine.com/2014/08/15/pstip-taking-control-of-verbose-and-debug-output-part-5/
. "$PSScriptRoot\Utilities.ps1"
. "$PSScriptRoot\Get-VisualStudio.ps1"
. "$PSScriptRoot\Get-UmbracoBuildEnv.ps1"
. "$PSScriptRoot\Set-UmbracoVersion.ps1"
. "$PSScriptRoot\Set-UmbracoContinuousVersion.ps1"
. "$PSScriptRoot\Get-UmbracoVersion.ps1"
. "$PSScriptRoot\Verify-NuGet.ps1"
. "$PSScriptRoot\Build-UmbracoDocs.ps1"
#
# Prepares the build
#
function Prepare-Build
{
param (
$uenv, # an Umbraco build environment (see Get-UmbracoBuildEnv)
[Alias("k")]
[switch]
$keep = $false
)
Write-Host ">> Prepare Build"
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$out = "$($uenv.SolutionRoot)\build.out"
# clear
Write-Host "Clear folders and files"
Remove-Directory "$src\Umbraco.Web.UI.Client\bower_components"
if (-not $keep)
{
Remove-Directory "$tmp"
mkdir "$tmp" > $null
Remove-Directory "$out"
mkdir "$out" > $null
}
# ensure proper web.config
$webUi = "$src\Umbraco.Web.UI"
Store-WebConfig $webUi
Write-Host "Create clean web.config"
Copy-File "$webUi\web.Template.config" "$webUi\web.config"
}
function Clear-EnvVar($var)
{
$value = [Environment]::GetEnvironmentVariable($var)
if (test-path "env:$var") { rm "env:$var" }
return $value
}
function Set-EnvVar($var, $value)
{
if ($value)
{
[Environment]::SetEnvironmentVariable($var, $value)
}
else
{
if (test-path "env:$var") { rm "env:$var" }
}
}
function Sandbox-Node
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
$global:node_path = $env:path
$nodePath = $uenv.NodePath
$gitExe = (get-command git).Source
$gitPath = [System.IO.Path]::GetDirectoryName($gitExe)
$env:path = "$nodePath;$gitPath"
$global:node_nodepath = Clear-EnvVar "NODEPATH"
$global:node_npmcache = Clear-EnvVar "NPM_CONFIG_CACHE"
$global:node_npmprefix = Clear-EnvVar "NPM_CONFIG_PREFIX"
}
function Restore-Node
{
$env:path = $node_path
Set-EnvVar "NODEPATH" $node_nodepath
Set-EnvVar "NPM_CONFIG_CACHE" $node_npmcache
Set-EnvVar "NPM_CONFIG_PREFIX" $node_npmprefix
}
#
# Builds the Belle UI project
#
function Compile-Belle
{
param (
$uenv, # an Umbraco build environment (see Get-UmbracoBuildEnv)
$version # an Umbraco version object (see Get-UmbracoVersion)
)
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$src = "$($uenv.SolutionRoot)\src"
Write-Host ">> Compile Belle"
Write-Host "Logging to $tmp\belle.log"
# get a temp clean node env (will restore)
Sandbox-Node $uenv
push-location "$($uenv.SolutionRoot)\src\Umbraco.Web.UI.Client"
write "node version is:" > $tmp\belle.log
&node -v >> $tmp\belle.log 2>&1
write "npm version is:" >> $tmp\belle.log 2>&1
&npm -v >> $tmp\belle.log 2>&1
write "cleaning npm cache" >> $tmp\belle.log 2>&1
&npm cache clean >> $tmp\belle.log 2>&1
write "installing bower" >> $tmp\belle.log 2>&1
&npm install -g bower >> $tmp\belle.log 2>&1
write "installing gulp" >> $tmp\belle.log 2>&1
&npm install -g gulp >> $tmp\belle.log 2>&1
write "installing gulp-cli" >> $tmp\belle.log 2>&1
&npm install -g gulp-cli --quiet >> $tmp\belle.log 2>&1
write "executing npm install" >> $tmp\belle.log 2>&1
&npm install >> $tmp\belle.log 2>&1
write "executing gulp build for version $version" >> $tmp\belle.log 2>&1
&gulp build --buildversion=$version.Release >> $tmp\belle.log 2>&1
pop-location
# fixme - should we filter the log to find errors?
#get-content .\build.tmp\belle.log | %{ if ($_ -match "build") { write $_}}
# restore
Restore-Node
# setting node_modules folder to hidden
# used to prevent VS13 from crashing on it while loading the websites project
# also makes sure aspnet compiler does not try to handle rogue files and chokes
# in VSO with Microsoft.VisualC.CppCodeProvider -related errors
# use get-item -force 'cos it might be hidden already
write "Set hidden attribute on node_modules"
$dir = get-item -force "$src\Umbraco.Web.UI.Client\node_modules"
$dir.Attributes = $dir.Attributes -bor ([System.IO.FileAttributes]::Hidden)
}
#
# Compiles Umbraco
#
function Compile-Umbraco
{
param (
$uenv, # an Umbraco build environment (see Get-UmbracoBuildEnv)
[string] $buildConfiguration = "Release"
)
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$out = "$($uenv.SolutionRoot)\build.out"
if ($uenv.VisualStudio -eq $null)
{
Write-Error "Build environment does not provide VisualStudio."
break
}
$toolsVersion = "4.0"
if ($uenv.VisualStudio.Major -eq 15)
{
$toolsVersion = "15.0"
}
Write-Host ">> Compile Umbraco"
Write-Host "Logging to $tmp\msbuild.umbraco.log"
# beware of the weird double \\ at the end of paths
# see http://edgylogic.com/blog/powershell-and-external-commands-done-right/
&$uenv.VisualStudio.MsBuild "$src\Umbraco.Web.UI\Umbraco.Web.UI.csproj" `
/p:WarningLevel=0 `
/p:Configuration=$buildConfiguration `
/p:Platform=AnyCPU `
/p:UseWPP_CopyWebApplication=True `
/p:PipelineDependsOnBuild=False `
/p:OutDir=$tmp\bin\\ `
/p:WebProjectOutputDir=$tmp\WebApp\\ `
/p:Verbosity=minimal `
/t:Clean`;Rebuild `
/tv:$toolsVersion `
/p:UmbracoBuild=True `
> $tmp\msbuild.umbraco.log
# /p:UmbracoBuild tells the csproj that we are building from PS
}
#
# Prepare Tests
#
function Prepare-Tests
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
Write-Host ">> Prepare Tests"
# fixme - idea is to avoid rebuilding everything for tests
# but because of our weird assembly versioning (with .* stuff)
# everything gets rebuilt all the time...
#Copy-Files "$tmp\bin" "." "$tmp\tests"
# data
Write-Host "Copy data files"
if( -Not (Test-Path -Path "$tmp\tests\Packaging" ) )
{
Write-Host "Create packaging directory"
New-Item -ItemType directory -Path "$tmp\tests\Packaging"
}
Copy-Files "$src\Umbraco.Tests\Packaging\Packages" "*" "$tmp\tests\Packaging\Packages"
# required for package install tests
if( -Not (Test-Path -Path "$tmp\tests\bin" ) )
{
Write-Host "Create bin directory"
New-Item -ItemType directory -Path "$tmp\tests\bin"
}
}
#
# Compiles Tests
#
function Compile-Tests
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$out = "$tmp\tests"
$buildConfiguration = "Release"
if ($uenv.VisualStudio -eq $null)
{
Write-Error "Build environment does not provide VisualStudio."
break
}
$toolsVersion = "4.0"
if ($uenv.VisualStudio.Major -eq 15)
{
$toolsVersion = "15.0"
}
Write-Host ">> Compile Tests"
Write-Host "Logging to $tmp\msbuild.tests.log"
# beware of the weird double \\ at the end of paths
# see http://edgylogic.com/blog/powershell-and-external-commands-done-right/
&$uenv.VisualStudio.MsBuild "$src\Umbraco.Tests\Umbraco.Tests.csproj" `
/p:WarningLevel=0 `
/p:Configuration=$buildConfiguration `
/p:Platform=AnyCPU `
/p:UseWPP_CopyWebApplication=True `
/p:PipelineDependsOnBuild=False `
/p:OutDir=$out\\ `
/p:Verbosity=minimal `
/t:Build `
/tv:$toolsVersion `
/p:UmbracoBuild=True `
/p:NugetPackages=$src\packages `
> $tmp\msbuild.tests.log
# /p:UmbracoBuild tells the csproj that we are building from PS
}
#
# Cleans things up and prepare files after compilation
#
function Prepare-Packages
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
Write-Host ">> Prepare Packages"
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$out = "$($uenv.SolutionRoot)\build.out"
$buildConfiguration = "Release"
# restore web.config
Restore-WebConfig "$src\Umbraco.Web.UI"
# cleanup build
Write-Host "Clean build"
Remove-File "$tmp\bin\*.dll.config"
Remove-File "$tmp\WebApp\bin\*.dll.config"
# cleanup presentation
Write-Host "Cleanup presentation"
Remove-Directory "$tmp\WebApp\umbraco.presentation"
# create directories
Write-Host "Create directories"
mkdir "$tmp\Configs" > $null
mkdir "$tmp\Configs\Lang" > $null
mkdir "$tmp\WebApp\App_Data" > $null
#mkdir "$tmp\WebApp\Media" > $null
#mkdir "$tmp\WebApp\Views" > $null
# copy various files
Write-Host "Copy xml documentation"
cp -force "$tmp\bin\*.xml" "$tmp\WebApp\bin"
Write-Host "Copy transformed configs and langs"
# note: exclude imageprocessor/*.config as imageprocessor pkg installs them
Copy-Files "$tmp\WebApp\config" "*.config" "$tmp\Configs" `
{ -not $_.RelativeName.StartsWith("imageprocessor") }
Copy-Files "$tmp\WebApp\config" "*.js" "$tmp\Configs"
Copy-Files "$tmp\WebApp\config\lang" "*.xml" "$tmp\Configs\Lang"
Copy-File "$tmp\WebApp\web.config" "$tmp\Configs\web.config.transform"
Write-Host "Copy transformed web.config"
Copy-File "$src\Umbraco.Web.UI\web.$buildConfiguration.Config.transformed" "$tmp\WebApp\web.config"
# offset the modified timestamps on all umbraco dlls, as WebResources
# break if date is in the future, which, due to timezone offsets can happen.
Write-Host "Offset dlls timestamps"
ls -r "$tmp\*.dll" | foreach {
$_.CreationTime = $_.CreationTime.AddHours(-11)
$_.LastWriteTime = $_.LastWriteTime.AddHours(-11)
}
# copy libs
Write-Host "Copy SqlCE libraries"
Copy-Files "$src\packages\SqlServerCE.4.0.0.1" "*.*" "$tmp\bin" `
{ -not $_.Extension.StartsWith(".nu") -and -not $_.RelativeName.StartsWith("lib\") }
Copy-Files "$src\packages\SqlServerCE.4.0.0.1" "*.*" "$tmp\WebApp\bin" `
{ -not $_.Extension.StartsWith(".nu") -and -not $_.RelativeName.StartsWith("lib\") }
# copy Belle
Write-Host "Copy Belle"
Copy-Files "$src\Umbraco.Web.UI\umbraco\assets" "*" "$tmp\WebApp\umbraco\assets"
Copy-Files "$src\Umbraco.Web.UI\umbraco\js" "*" "$tmp\WebApp\umbraco\js"
Copy-Files "$src\Umbraco.Web.UI\umbraco\lib" "*" "$tmp\WebApp\umbraco\lib"
Copy-Files "$src\Umbraco.Web.UI\umbraco\views" "*" "$tmp\WebApp\umbraco\views"
Copy-Files "$src\Umbraco.Web.UI\umbraco\preview" "*" "$tmp\WebApp\umbraco\preview"
# prepare WebPI
Write-Host "Prepare WebPI"
Remove-Directory "$tmp\WebPi"
mkdir "$tmp\WebPi" > $null
mkdir "$tmp\WebPi\umbraco" > $null
Copy-Files "$tmp\WebApp" "*" "$tmp\WebPi\umbraco"
Copy-Files "$src\WebPi" "*" "$tmp\WebPi"
}
#
# Creates the Zip packages
#
function Package-Zip
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
Write-Host ">> Create Zip packages"
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$out = "$($uenv.SolutionRoot)\build.out"
Write-Host "Zip all binaries"
&$uenv.Zip a -r "$out\UmbracoCms.AllBinaries.$($version.Semver).zip" `
"$tmp\bin\*" `
"-x!dotless.Core.*" `
> $null
Write-Host "Zip cms"
&$uenv.Zip a -r "$out\UmbracoCms.$($version.Semver).zip" `
"$tmp\WebApp\*" `
"-x!dotless.Core.*" "-x!Content_Types.xml" "-x!*.pdb"`
> $null
Write-Host "Zip WebPI"
&$uenv.Zip a -r "$out\UmbracoCms.WebPI.$($version.Semver).zip" "-x!*.pdb"`
"$tmp\WebPi\*" `
"-x!dotless.Core.*" `
> $null
# hash the webpi file
Write-Host "Hash WebPI"
$hash = Get-FileHash "$out\UmbracoCms.WebPI.$($version.Semver).zip"
Write $hash | out-file "$out\webpihash.txt" -encoding ascii
}
#
# Prepares NuGet
#
function Prepare-NuGet
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
Write-Host ">> Prepare NuGet"
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$out = "$($uenv.SolutionRoot)\build.out"
# add Web.config transform files to the NuGet package
Write-Host "Add web.config transforms to NuGet package"
mv "$tmp\WebApp\Views\Web.config" "$tmp\WebApp\Views\Web.config.transform"
# fixme - that one does not exist in .bat build either?
#mv "$tmp\WebApp\Xslt\Web.config" "$tmp\WebApp\Xslt\Web.config.transform"
}
#
# Restores NuGet
#
function Restore-NuGet
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
Write-Host ">> Restore NuGet"
Write-Host "Logging to $tmp\nuget.restore.log"
&$uenv.NuGet restore "$src\Umbraco.sln" > "$tmp\nuget.restore.log"
}
#
# Creates the NuGet packages
#
function Package-NuGet
{
param (
$uenv, # an Umbraco build environment (see Get-UmbracoBuildEnv)
$version # an Umbraco version object (see Get-UmbracoVersion)
)
$src = "$($uenv.SolutionRoot)\src"
$tmp = "$($uenv.SolutionRoot)\build.tmp"
$out = "$($uenv.SolutionRoot)\build.out"
$nuspecs = "$($uenv.SolutionRoot)\build\NuSpecs"
Write-Host ">> Create NuGet packages"
# see https://docs.microsoft.com/en-us/nuget/schema/nuspec
# note - warnings about SqlCE native libs being outside of 'lib' folder,
# nothing much we can do about it as it's intentional yet there does not
# seem to be a way to disable the warning
&$uenv.NuGet Pack "$nuspecs\UmbracoCms.Core.nuspec" `
-Properties BuildTmp="$tmp" `
-Version $version.Semver.ToString() `
-Symbols -Verbosity quiet -outputDirectory $out
&$uenv.NuGet Pack "$nuspecs\UmbracoCms.nuspec" `
-Properties BuildTmp="$tmp" `
-Version $version.Semver.ToString() `
-Verbosity quiet -outputDirectory $out
}
#
# Builds Umbraco
#
function Build-Umbraco
{
[CmdletBinding()]
param (
[string]
$target = "all",
[string]
$buildConfiguration = "Release"
)
$target = $target.ToLowerInvariant()
Write-Host ">> Build-Umbraco <$target> <$buildConfiguration>"
Write-Host "Get Build Environment"
$uenv = Get-UmbracoBuildEnv
Write-Host "Get Version"
$version = Get-UmbracoVersion
Write-Host "Version $($version.Semver)"
if ($target -eq "pre-build")
{
Prepare-Build $uenv
#Compile-Belle $uenv $version
# set environment variables
$env:UMBRACO_VERSION=$version.Semver.ToString()
$env:UMBRACO_RELEASE=$version.Release
$env:UMBRACO_COMMENT=$version.Comment
$env:UMBRACO_BUILD=$version.Build
# set environment variable for VSO
# https://github.com/Microsoft/vsts-tasks/issues/375
# https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
Write-Host ("##vso[task.setvariable variable=UMBRACO_VERSION;]$($version.Semver.ToString())")
Write-Host ("##vso[task.setvariable variable=UMBRACO_RELEASE;]$($version.Release)")
Write-Host ("##vso[task.setvariable variable=UMBRACO_COMMENT;]$($version.Comment)")
Write-Host ("##vso[task.setvariable variable=UMBRACO_BUILD;]$($version.Build)")
Write-Host ("##vso[task.setvariable variable=UMBRACO_TMP;]$($uenv.SolutionRoot)\build.tmp")
}
elseif ($target -eq "pre-tests")
{
Prepare-Tests $uenv
}
elseif ($target -eq "compile-tests")
{
Compile-Tests $uenv
}
elseif ($target -eq "compile-umbraco")
{
Compile-Umbraco $uenv $buildConfiguration
}
elseif ($target -eq "pre-packages")
{
Prepare-Packages $uenv
}
elseif ($target -eq "pre-nuget")
{
Prepare-NuGet $uenv
}
elseif ($target -eq "restore-nuget")
{
Restore-NuGet $uenv
}
elseif ($target -eq "pkg-zip")
{
Package-Zip $uenv
}
elseif ($target -eq "compile-belle")
{
Compile-Belle $uenv $version
}
elseif ($target -eq "all")
{
Prepare-Build $uenv
Restore-NuGet $uenv
Compile-Belle $uenv $version
Compile-Umbraco $uenv $buildConfiguration
Prepare-Tests $uenv
Compile-Tests $uenv
# not running tests...
Prepare-Packages $uenv
Package-Zip $uenv
Verify-NuGet $uenv
Prepare-NuGet $uenv
Package-NuGet $uenv $version
}
else
{
Write-Error "Unsupported target `"$target`"."
}
}
#
# export functions
#
Export-ModuleMember -function Get-UmbracoBuildEnv
Export-ModuleMember -function Set-UmbracoVersion
Export-ModuleMember -function Set-UmbracoContinuousVersion
Export-ModuleMember -function Get-UmbracoVersion
Export-ModuleMember -function Build-Umbraco
Export-ModuleMember -function Build-UmbracoDocs
Export-ModuleMember -function Verify-NuGet
#eof
+120
View File
@@ -0,0 +1,120 @@
# returns a string containing the hash of $file
function Get-FileHash($file)
{
try
{
$crypto = new-object System.Security.Cryptography.SHA1CryptoServiceProvider
$stream = [System.IO.File]::OpenRead($file)
$hash = $crypto.ComputeHash($stream)
$text = ""
$hash | foreach `
{
$text = $text + $_.ToString("x2")
}
return $text
}
finally
{
if ($stream)
{
$stream.Dispose()
}
$crypto.Dispose()
}
}
# returns the full path if $file is relative to $pwd
function Get-FullPath($file)
{
$path = [System.IO.Path]::Combine($pwd, $file)
$path = [System.IO.Path]::GetFullPath($path)
return $path
}
# removes a directory, doesn't complain if it does not exist
function Remove-Directory($dir)
{
remove-item $dir -force -recurse -errorAction SilentlyContinue > $null
}
# removes a file, doesn't complain if it does not exist
function Remove-File($file)
{
remove-item $file -force -errorAction SilentlyContinue > $null
}
# copies a file, creates target dir if needed
function Copy-File($source, $target)
{
$ignore = new-item -itemType file -path $target -force
cp -force $source $target
}
# copies files to a directory
function Copy-Files($source, $select, $target, $filter)
{
$files = ls -r "$source\$select"
$files | foreach {
$relative = $_.FullName.SubString($source.Length+1)
$_ | add-member -memberType NoteProperty -name RelativeName -value $relative
}
if ($filter -ne $null) {
$files = $files | where $filter
}
$files |
foreach {
if ($_.PsIsContainer) {
$ignore = new-item -itemType directory -path "$target\$($_.RelativeName)" -force
}
else {
Copy-File $_.FullName "$target\$($_.RelativeName)"
}
}
}
# regex-replaces content in a file
function Replace-FileText($filename, $source, $replacement)
{
$filepath = Get-FullPath $filename
$text = [System.IO.File]::ReadAllText($filepath)
$text = [System.Text.RegularExpressions.Regex]::Replace($text, $source, $replacement)
$utf8bom = New-Object System.Text.UTF8Encoding $true
[System.IO.File]::WriteAllText($filepath, $text, $utf8bom)
}
# store web.config
function Store-WebConfig($webUi)
{
if (test-path "$webUi\web.config")
{
if (test-path "$webUi\web.config.temp-build")
{
Write-Host "Found existing web.config.temp-build"
$i = 0
while (test-path "$webUi\web.config.temp-build.$i")
{
$i = $i + 1
}
Write-Host "Save existing web.config as web.config.temp-build.$i"
Write-Host "(WARN: the original web.config.temp-build will be restored during post-build)"
mv "$webUi\web.config" "$webUi\web.config.temp-build.$i"
}
else
{
Write-Host "Save existing web.config as web.config.temp-build"
Write-Host "(will be restored during post-build)"
mv "$webUi\web.config" "$webUi\web.config.temp-build"
}
}
}
# restore web.config
function Restore-WebConfig($webUi)
{
if (test-path "$webUi\web.config.temp-build")
{
Write-Host "Restoring existing web.config"
Remove-File "$webUi\web.config"
mv "$webUi\web.config.temp-build" "$webUi\web.config"
}
}
@@ -0,0 +1,444 @@
#
# Verify-NuGet
#
function Format-Dependency
{
param ( $d )
$m = $d.Id + " "
if ($d.MinInclude) { $m = $m + "[" }
else { $m = $m + "(" }
$m = $m + $d.MinVersion
if ($d.MaxVersion -ne $d.MinVersion) { $m = $m + "," + $d.MaxVersion }
if ($d.MaxInclude) { $m = $m + "]" }
else { $m = $m + ")" }
return $m
}
function Write-NuSpec
{
param ( $name, $deps )
Write-Host ""
Write-Host "$name NuSpec dependencies:"
foreach ($d in $deps)
{
$m = Format-Dependency $d
Write-Host " $m"
}
}
function Write-Package
{
param ( $name, $pkgs )
Write-Host ""
Write-Host "$name packages:"
foreach ($p in $pkgs)
{
Write-Host " $($p.Id) $($p.Version)"
}
}
function Verify-NuGet
{
param (
$uenv # an Umbraco build environment (see Get-UmbracoBuildEnv)
)
if ($uenv -eq $null)
{
$uenv = Get-UmbracoBuildEnv
}
$source = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Semver;
namespace Umbraco.Build
{
public class NuGet
{
public static Dependency[] GetNuSpecDependencies(string filename)
{
NuSpec nuspec;
var serializer = new XmlSerializer(typeof(NuSpec));
using (var reader = new StreamReader(filename))
{
nuspec = (NuSpec) serializer.Deserialize(reader);
}
var nudeps = nuspec.Metadata.Dependencies;
var deps = new List<Dependency>();
foreach (var nudep in nudeps)
{
var dep = new Dependency();
dep.Id = nudep.Id;
var parts = nudep.Version.Split(',');
if (parts.Length == 1)
{
dep.MinInclude = parts[0].StartsWith("[");
dep.MaxInclude = parts[0].EndsWith("]");
SemVersion version;
if (!SemVersion.TryParse(parts[0].Substring(1, parts[0].Length-2).Trim(), out version)) continue;
dep.MinVersion = dep.MaxVersion = version; //parts[0].Substring(1, parts[0].Length-2).Trim();
}
else
{
SemVersion version;
if (!SemVersion.TryParse(parts[0].Substring(1).Trim(), out version)) continue;
dep.MinVersion = version; //parts[0].Substring(1).Trim();
if (!SemVersion.TryParse(parts[1].Substring(0, parts[1].Length-1).Trim(), out version)) continue;
dep.MaxVersion = version; //parts[1].Substring(0, parts[1].Length-1).Trim();
dep.MinInclude = parts[0].StartsWith("[");
dep.MaxInclude = parts[1].EndsWith("]");
}
deps.Add(dep);
}
return deps.ToArray();
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(/*this*/ IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> knownKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (knownKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
public static Package[] GetProjectsPackages(string src, string[] projects)
{
var l = new List<Package>();
foreach (var project in projects)
{
var path = Path.Combine(src, project);
var packageConfig = Path.Combine(path, "packages.config");
if (File.Exists(packageConfig))
ReadPackagesConfig(packageConfig, l);
var csprojs = Directory.GetFiles(path, "*.csproj");
foreach (var csproj in csprojs)
{
ReadCsProj(csproj, l);
}
}
IEnumerable<Package> p = l.OrderBy(x => x.Id);
p = DistinctBy(p, x => x.Id + ":::" + x.Version);
return p.ToArray();
}
public static object[] GetPackageErrors(Package[] pkgs)
{
return pkgs
.GroupBy(x => x.Id)
.Where(x => x.Count() > 1)
.ToArray();
}
public static object[] GetNuSpecErrors(Package[] pkgs, Dependency[] deps)
{
var d = pkgs.ToDictionary(x => x.Id, x => x.Version);
return deps
.Select(x =>
{
SemVersion v;
if (!d.TryGetValue(x.Id, out v)) return null;
var ok = true;
/*
if (x.MinInclude)
{
if (v < x.MinVersion) ok = false;
}
else
{
if (v <= x.MinVersion) ok = false;
}
if (x.MaxInclude)
{
if (v > x.MaxVersion) ok = false;
}
else
{
if (v >= x.MaxVersion) ok = false;
}
*/
if (!x.MinInclude || v != x.MinVersion) ok = false;
return ok ? null : new { Dependency = x, Version = v };
})
.Where(x => x != null)
.ToArray();
}
/*
public static Package[] GetProjectPackages(string path)
{
var l = new List<Package>();
var packageConfig = Path.Combine(path, "packages.config");
if (File.Exists(packageConfig))
ReadPackagesConfig(packageConfig, l);
var csprojs = Directory.GetFiles(path, "*.csproj");
foreach (var csproj in csprojs)
{
ReadCsProj(csproj, l);
}
return l.ToArray();
}
*/
public static string GetDirectoryName(string filename)
{
return Path.GetFileName(Path.GetDirectoryName(filename));
}
public static void ReadPackagesConfig(string filename, List<Package> packages)
{
//Console.WriteLine("read " + filename);
PackagesConfigPackages pkgs;
var serializer = new XmlSerializer(typeof(PackagesConfigPackages));
using (var reader = new StreamReader(filename))
{
pkgs = (PackagesConfigPackages) serializer.Deserialize(reader);
}
foreach (var p in pkgs.Packages)
{
SemVersion version;
if (!SemVersion.TryParse(p.Version, out version)) continue;
packages.Add(new Package { Id = p.Id, Version = version, Project = GetDirectoryName(filename) });
}
}
public static void ReadCsProj(string filename, List<Package> packages)
{
//Console.WriteLine("read " + filename);
// if xmlns then it's not a VS2017 with PackageReference
var text = File.ReadAllLines(filename);
var line = text.FirstOrDefault(x => x.Contains("<Project"));
if (line == null) return;
if (line.Contains("xmlns")) return;
CsProjProject proj;
var serializer = new XmlSerializer(typeof(CsProjProject));
using (var reader = new StreamReader(filename))
{
proj = (CsProjProject) serializer.Deserialize(reader);
}
foreach (var p in proj.ItemGroups.Where(x => x.Packages != null).SelectMany(x => x.Packages))
{
var sversion = p.VersionE ?? p.VersionA;
SemVersion version;
if (!SemVersion.TryParse(sversion, out version)) continue;
packages.Add(new Package { Id = p.Id, Version = version, Project = GetDirectoryName(filename) });
}
}
public class Dependency
{
public string Id { get; set; }
public SemVersion MinVersion { get; set; }
public SemVersion MaxVersion { get; set; }
public bool MinInclude { get; set; }
public bool MaxInclude { get; set; }
}
public class Package
{
public string Id { get; set; }
public SemVersion Version { get; set; }
public string Project { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd")]
[XmlRoot(Namespace = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd", IsNullable = false, ElementName = "package")]
public class NuSpec
{
[XmlElement("metadata")]
public NuSpecMetadata Metadata { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd", TypeName = "metadata")]
public class NuSpecMetadata
{
[XmlArray("dependencies")]
[XmlArrayItem("dependency", IsNullable = false)]
public NuSpecDependency[] Dependencies { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd", TypeName = "dependencies")]
public class NuSpecDependency
{
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
}
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false, ElementName = "packages")]
public class PackagesConfigPackages
{
[XmlElement("package")]
public PackagesConfigPackage[] Packages { get; set; }
}
[XmlType(AnonymousType = true, TypeName = "package")]
public class PackagesConfigPackage
{
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
}
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false, ElementName = "Project")]
public class CsProjProject
{
[XmlElement("ItemGroup")]
public CsProjItemGroup[] ItemGroups { get; set; }
}
[XmlType(AnonymousType = true, TypeName = "ItemGroup")]
public class CsProjItemGroup
{
[XmlElement("PackageReference")]
public CsProjPackageReference[] Packages { get; set; }
}
[XmlType(AnonymousType = true, TypeName = "PackageReference")]
public class CsProjPackageReference
{
[XmlAttribute(AttributeName = "Include")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "Version")]
public string VersionA { get; set; }
[XmlElement("Version")]
public string VersionE { get; set;}
}
}
}
"@
Write-Host ">> Verify NuGet consistency"
$assem = (
"System.Xml",
"System.Core", # "System.Collections.Generic"
"System.Linq",
"System.Xml.Serialization",
"System.IO",
"System.Globalization",
$uenv.Semver
)
try
{
# as long as the code hasn't changed it's fine to re-add, but if the code
# has changed this will throw - better warn the dev that we have an issue
add-type -referencedAssemblies $assem -typeDefinition $source -language CSharp
}
catch
{
if ($_.FullyQualifiedErrorId.StartsWith("TYPE_ALREADY_EXISTS,"))
{ Write-Error "Failed to add type, did you change the code?" }
else
{ Write-Error $_ }
}
if (-not $?) { break }
$nuspecs = (
"UmbracoCms",
"UmbracoCms.Core"
)
$projects = (
"Umbraco.Core",
"Umbraco.Web",
"Umbraco.Web.UI",
"UmbracoExamine"#,
#"Umbraco.Tests",
#"Umbraco.Tests.Benchmarks"
)
$src = "$($uenv.SolutionRoot)\src"
$pkgs = [Umbraco.Build.NuGet]::GetProjectsPackages($src, $projects)
if (-not $?) { break }
#Write-Package "All" $pkgs
$errs = [Umbraco.Build.NuGet]::GetPackageErrors($pkgs)
if (-not $?) { break }
if ($errs.Length -gt 0)
{
Write-Host ""
}
foreach ($err in $errs)
{
Write-Host $err.Key
foreach ($e in $err)
{
Write-Host " $($e.Version) required by $($e.Project)"
}
}
if ($errs.Length -gt 0)
{
Write-Error "Found non-consolidated package dependencies"
break
}
$nuerr = $false
$nupath = "$($uenv.SolutionRoot)\build\NuSpecs"
foreach ($nuspec in $nuspecs)
{
$deps = [Umbraco.Build.NuGet]::GetNuSpecDependencies("$nupath\$nuspec.nuspec")
if (-not $?) { break }
#Write-NuSpec $nuspec $deps
$errs = [Umbraco.Build.NuGet]::GetNuSpecErrors($pkgs, $deps)
if (-not $?) { break }
if ($errs.Length -gt 0)
{
Write-Host ""
Write-Host "$nuspec requires:"
$nuerr = $true
}
foreach ($err in $errs)
{
$m = Format-Dependency $err.Dependency
Write-Host " $m but projects require $($err.Version)"
}
}
if ($nuerr)
{
Write-Error "Found inconsistent NuGet dependencies"
break
}
}
+44 -44
View File
@@ -44,65 +44,65 @@
</dependencies>
</metadata>
<files>
<file src="..\_BuildOutput\WebApp\bin\businesslogic.dll" target="lib\net45\businesslogic.dll" />
<file src="..\_BuildOutput\WebApp\bin\businesslogic.xml" target="lib\net45\businesslogic.xml" />
<file src="..\_BuildOutput\WebApp\bin\cms.dll" target="lib\net45\cms.dll" />
<file src="..\_BuildOutput\WebApp\bin\cms.xml" target="lib\net45\cms.xml" />
<file src="..\_BuildOutput\WebApp\bin\controls.dll" target="lib\net45\controls.dll" />
<file src="..\_BuildOutput\WebApp\bin\controls.xml" target="lib\net45\controls.xml" />
<file src="..\_BuildOutput\WebApp\bin\interfaces.dll" target="lib\net45\interfaces.dll" />
<file src="..\_BuildOutput\WebApp\bin\interfaces.xml" target="lib\net45\interfaces.xml" />
<file src="..\_BuildOutput\WebApp\bin\log4net.dll" target="lib\net45\log4net.dll" />
<file src="..\_BuildOutput\WebApp\bin\Microsoft.ApplicationBlocks.Data.dll" target="lib\net45\Microsoft.ApplicationBlocks.Data.dll" />
<file src="..\_BuildOutput\WebApp\bin\SQLCE4Umbraco.dll" target="lib\net45\SQLCE4Umbraco.dll" />
<file src="..\_BuildOutput\WebApp\bin\SQLCE4Umbraco.xml" target="lib\net45\SQLCE4Umbraco.xml" />
<file src="..\_BuildOutput\WebApp\bin\System.Data.SqlServerCe.dll" target="lib\net45\System.Data.SqlServerCe.dll" />
<file src="..\_BuildOutput\WebApp\bin\System.Data.SqlServerCe.Entity.dll" target="lib\net45\System.Data.SqlServerCe.Entity.dll" />
<file src="..\_BuildOutput\WebApp\bin\TidyNet.dll" target="lib\net45\TidyNet.dll" />
<file src="..\_BuildOutput\WebApp\bin\Umbraco.Core.dll" target="lib\net45\Umbraco.Core.dll" />
<file src="..\_BuildOutput\WebApp\bin\Umbraco.Core.xml" target="lib\net45\Umbraco.Core.xml" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.DataLayer.dll" target="lib\net45\umbraco.DataLayer.dll" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.DataLayer.xml" target="lib\net45\umbraco.DataLayer.xml" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.dll" target="lib\net45\umbraco.dll" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.xml" target="lib\net45\umbraco.xml" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.editorControls.dll" target="lib\net45\umbraco.editorControls.dll" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.editorControls.xml" target="lib\net45\umbraco.editorControls.xml" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.MacroEngines.dll" target="lib\net45\umbraco.MacroEngines.dll" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.MacroEngines.xml" target="lib\net45\umbraco.MacroEngines.xml" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.providers.dll" target="lib\net45\umbraco.providers.dll" />
<file src="..\_BuildOutput\WebApp\bin\umbraco.providers.xml" target="lib\net45\umbraco.providers.xml" />
<file src="..\_BuildOutput\WebApp\bin\Umbraco.Web.UI.dll" target="lib\net45\Umbraco.Web.UI.dll" />
<file src="..\_BuildOutput\WebApp\bin\Umbraco.Web.UI.xml" target="lib\net45\Umbraco.Web.UI.xml" />
<file src="..\_BuildOutput\WebApp\bin\UmbracoExamine.dll" target="lib\net45\UmbracoExamine.dll" />
<file src="..\_BuildOutput\WebApp\bin\UmbracoExamine.xml" target="lib\net45\UmbracoExamine.xml" />
<file src="$BuildTmp$\WebApp\bin\businesslogic.dll" target="lib\net45\businesslogic.dll" />
<file src="$BuildTmp$\WebApp\bin\businesslogic.xml" target="lib\net45\businesslogic.xml" />
<file src="$BuildTmp$\WebApp\bin\cms.dll" target="lib\net45\cms.dll" />
<file src="$BuildTmp$\WebApp\bin\cms.xml" target="lib\net45\cms.xml" />
<file src="$BuildTmp$\WebApp\bin\controls.dll" target="lib\net45\controls.dll" />
<file src="$BuildTmp$\WebApp\bin\controls.xml" target="lib\net45\controls.xml" />
<file src="$BuildTmp$\WebApp\bin\interfaces.dll" target="lib\net45\interfaces.dll" />
<file src="$BuildTmp$\WebApp\bin\interfaces.xml" target="lib\net45\interfaces.xml" />
<file src="$BuildTmp$\WebApp\bin\log4net.dll" target="lib\net45\log4net.dll" />
<file src="$BuildTmp$\WebApp\bin\Microsoft.ApplicationBlocks.Data.dll" target="lib\net45\Microsoft.ApplicationBlocks.Data.dll" />
<file src="$BuildTmp$\WebApp\bin\SQLCE4Umbraco.dll" target="lib\net45\SQLCE4Umbraco.dll" />
<file src="$BuildTmp$\WebApp\bin\SQLCE4Umbraco.xml" target="lib\net45\SQLCE4Umbraco.xml" />
<file src="$BuildTmp$\WebApp\bin\System.Data.SqlServerCe.dll" target="lib\net45\System.Data.SqlServerCe.dll" />
<file src="$BuildTmp$\WebApp\bin\System.Data.SqlServerCe.Entity.dll" target="lib\net45\System.Data.SqlServerCe.Entity.dll" />
<file src="$BuildTmp$\WebApp\bin\TidyNet.dll" target="lib\net45\TidyNet.dll" />
<file src="$BuildTmp$\WebApp\bin\Umbraco.Core.dll" target="lib\net45\Umbraco.Core.dll" />
<file src="$BuildTmp$\WebApp\bin\Umbraco.Core.xml" target="lib\net45\Umbraco.Core.xml" />
<file src="$BuildTmp$\WebApp\bin\umbraco.DataLayer.dll" target="lib\net45\umbraco.DataLayer.dll" />
<file src="$BuildTmp$\WebApp\bin\umbraco.DataLayer.xml" target="lib\net45\umbraco.DataLayer.xml" />
<file src="$BuildTmp$\WebApp\bin\umbraco.dll" target="lib\net45\umbraco.dll" />
<file src="$BuildTmp$\WebApp\bin\umbraco.xml" target="lib\net45\umbraco.xml" />
<file src="$BuildTmp$\WebApp\bin\umbraco.editorControls.dll" target="lib\net45\umbraco.editorControls.dll" />
<file src="$BuildTmp$\WebApp\bin\umbraco.editorControls.xml" target="lib\net45\umbraco.editorControls.xml" />
<file src="$BuildTmp$\WebApp\bin\umbraco.MacroEngines.dll" target="lib\net45\umbraco.MacroEngines.dll" />
<file src="$BuildTmp$\WebApp\bin\umbraco.MacroEngines.xml" target="lib\net45\umbraco.MacroEngines.xml" />
<file src="$BuildTmp$\WebApp\bin\umbraco.providers.dll" target="lib\net45\umbraco.providers.dll" />
<file src="$BuildTmp$\WebApp\bin\umbraco.providers.xml" target="lib\net45\umbraco.providers.xml" />
<file src="$BuildTmp$\WebApp\bin\Umbraco.Web.UI.dll" target="lib\net45\Umbraco.Web.UI.dll" />
<file src="$BuildTmp$\WebApp\bin\Umbraco.Web.UI.xml" target="lib\net45\Umbraco.Web.UI.xml" />
<file src="$BuildTmp$\WebApp\bin\UmbracoExamine.dll" target="lib\net45\UmbracoExamine.dll" />
<file src="$BuildTmp$\WebApp\bin\UmbracoExamine.xml" target="lib\net45\UmbracoExamine.xml" />
<file src="tools\install.core.ps1" target="tools\install.ps1" />
<!-- Added to be able to produce a symbols package -->
<file src="..\_BuildOutput\bin\SQLCE4Umbraco.pdb" target="lib" />
<file src="$BuildTmp$\bin\SQLCE4Umbraco.pdb" target="lib" />
<file src="..\..\src\SQLCE4Umbraco\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\SQLCE4Umbraco" />
<file src="..\_BuildOutput\bin\businesslogic.pdb" target="lib" />
<file src="$BuildTmp$\bin\businesslogic.pdb" target="lib" />
<file src="..\..\src\umbraco.businesslogic\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.businesslogic" />
<file src="..\_BuildOutput\bin\cms.pdb" target="lib" />
<file src="$BuildTmp$\bin\cms.pdb" target="lib" />
<file src="..\..\src\umbraco.cms\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.cms" />
<file src="..\_BuildOutput\bin\controls.pdb" target="lib" />
<file src="$BuildTmp$\bin\controls.pdb" target="lib" />
<file src="..\..\src\umbraco.controls\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.controls" />
<file src="..\_BuildOutput\bin\interfaces.pdb" target="lib" />
<file src="$BuildTmp$\bin\interfaces.pdb" target="lib" />
<file src="..\..\src\umbraco.interfaces\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.interfaces" />
<file src="..\_BuildOutput\bin\Umbraco.Core.pdb" target="lib" />
<file src="$BuildTmp$\bin\Umbraco.Core.pdb" target="lib" />
<file src="..\..\src\Umbraco.Core\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\Umbraco.Core" />
<file src="..\_BuildOutput\bin\umbraco.DataLayer.pdb" target="lib" />
<file src="$BuildTmp$\bin\umbraco.DataLayer.pdb" target="lib" />
<file src="..\..\src\umbraco.datalayer\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.datalayer" />
<file src="..\_BuildOutput\bin\umbraco.editorControls.pdb" target="lib" />
<file src="$BuildTmp$\bin\umbraco.editorControls.pdb" target="lib" />
<file src="..\..\src\umbraco.editorControls\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.editorControls" />
<file src="..\_BuildOutput\bin\umbraco.MacroEngines.pdb" target="lib" />
<file src="$BuildTmp$\bin\umbraco.MacroEngines.pdb" target="lib" />
<file src="..\..\src\umbraco.MacroEngines\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.MacroEngines" />
<file src="..\_BuildOutput\bin\umbraco.providers.pdb" target="lib" />
<file src="$BuildTmp$\bin\umbraco.providers.pdb" target="lib" />
<file src="..\..\src\umbraco.providers\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\umbraco.providers" />
<file src="..\_BuildOutput\bin\umbraco.pdb" target="lib" />
<file src="$BuildTmp$\bin\umbraco.pdb" target="lib" />
<file src="..\..\src\Umbraco.Web\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\Umbraco.Web" />
<file src="..\_BuildOutput\bin\Umbraco.Web.UI.pdb" target="lib" />
<file src="$BuildTmp$\bin\Umbraco.Web.UI.pdb" target="lib" />
<file src="..\..\src\Umbraco.Web.UI\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\Umbraco.Web.UI" />
<file src="..\_BuildOutput\bin\UmbracoExamine.pdb" target="lib" />
<file src="$BuildTmp$\bin\UmbracoExamine.pdb" target="lib" />
<file src="..\..\src\UmbracoExamine\**\*.cs" exclude="..\..\src\**\TemporaryGeneratedFile*.cs" target="src\UmbracoExamine" />
</files>
</package>
+13 -13
View File
@@ -19,22 +19,22 @@
<dependency id="Newtonsoft.Json" version="[10.0.2, 11.0.0)" />
<dependency id="Umbraco.ModelsBuilder" version="[3.0.7, 4.0.0)" />
<dependency id="Microsoft.AspNet.SignalR.Core" version="[2.2.1, 3.0.0)" />
<dependency id="ImageProcessor.Web.Config" version="[2.3.0, 3.0.0)" />
<dependency id="ImageProcessor.Web.Config" version="[2.3.0, 3.0.0)" />
</dependencies>
</metadata>
<files>
<file src="..\_BuildOutput\Configs\**" target="Content\Config" exclude="..\_BuildOutput\Configs\Web.config.transform" />
<file src="..\_BuildOutput\WebApp\Views\**" target="Content\Views" exclude="..\_BuildOutput\WebApp\Views\Web.config" />
<file src="..\_BuildOutput\WebApp\default.aspx" target="Content\default.aspx" />
<file src="..\_BuildOutput\WebApp\Global.asax" target="Content\Global.asax" />
<file src="..\_BuildOutput\WebApp\Web.config" target="UmbracoFiles\Web.config" />
<file src="..\_BuildOutput\WebApp\App_Browsers\**" target="UmbracoFiles\App_Browsers" />
<file src="..\_BuildOutput\WebApp\bin\amd64\**" target="UmbracoFiles\bin\amd64" />
<file src="..\_BuildOutput\WebApp\bin\x86\**" target="UmbracoFiles\bin\x86" />
<file src="..\_BuildOutput\WebApp\config\splashes\**" target="UmbracoFiles\Config\splashes" />
<file src="..\_BuildOutput\WebApp\umbraco\**" target="UmbracoFiles\umbraco" />
<file src="..\_BuildOutput\WebApp\umbraco_client\**" target="UmbracoFiles\umbraco_client" />
<file src="..\_BuildOutput\WebApp\Media\Web.config" target="Content\Media\Web.config" />
<file src="$BuildTmp$\Configs\**" target="Content\Config" exclude="$BuildTmp$\Configs\Web.config.transform" />
<file src="$BuildTmp$\WebApp\Views\**" target="Content\Views" exclude="$BuildTmp$\WebApp\Views\Web.config" />
<file src="$BuildTmp$\WebApp\default.aspx" target="Content\default.aspx" />
<file src="$BuildTmp$\WebApp\Global.asax" target="Content\Global.asax" />
<file src="$BuildTmp$\WebApp\Web.config" target="UmbracoFiles\Web.config" />
<file src="$BuildTmp$\WebApp\App_Browsers\**" target="UmbracoFiles\App_Browsers" />
<file src="$BuildTmp$\WebApp\bin\amd64\**" target="UmbracoFiles\bin\amd64" />
<file src="$BuildTmp$\WebApp\bin\x86\**" target="UmbracoFiles\bin\x86" />
<file src="$BuildTmp$\WebApp\config\splashes\**" target="UmbracoFiles\Config\splashes" />
<file src="$BuildTmp$\WebApp\umbraco\**" target="UmbracoFiles\umbraco" />
<file src="$BuildTmp$\WebApp\umbraco_client\**" target="UmbracoFiles\umbraco_client" />
<file src="$BuildTmp$\WebApp\Media\Web.config" target="Content\Media\Web.config" />
<file src="tools\install.ps1" target="tools\install.ps1" />
<file src="tools\Readme.txt" target="tools\Readme.txt" />
<file src="tools\ReadmeUpgrade.txt" target="tools\ReadmeUpgrade.txt" />
Binary file not shown.
-2
View File
@@ -1,2 +0,0 @@
# Usage: on line 2 put the release version, on line 3 put the version comment (example: beta)
7.6.6
+67
View File
@@ -0,0 +1,67 @@
param (
[Parameter(Mandatory=$false)]
[string]
$version,
[Parameter(Mandatory=$false)]
[Alias("mo")]
[switch]
$moduleOnly = $false
)
# the script can run either from the solution root,
# or from the ./build directory - anything else fails
if ([System.IO.Path]::GetFileName($pwd) -eq "build")
{
$mpath = [System.IO.Path]::GetDirectoryName($pwd) + "\build\Modules\"
}
else
{
$mpath = "$pwd\build\Modules\"
}
# look for the module and throw if not found
if (-not [System.IO.Directory]::Exists($mpath + "Umbraco.Build"))
{
Write-Error "Could not locate Umbraco build Powershell module."
break
}
# add the module path (if not already there)
if (-not $env:PSModulePath.Contains($mpath))
{
$env:PSModulePath = "$mpath;$env:PSModulePath"
}
# force-import (or re-import) the module
Write-Host "Import Umbraco build Powershell module"
Import-Module Umbraco.Build -Force -DisableNameChecking
# module only?
if ($moduleOnly)
{
if (-not [string]::IsNullOrWhiteSpace($version))
{
Write-Host "(module only: ignoring version parameter)"
}
else
{
Write-Host "(module only)"
}
break
}
# get build environment
Write-Host "Setup Umbraco build Environment"
$uenv = Get-UmbracoBuildEnv
# set the version if any
if (-not [string]::IsNullOrWhiteSpace($version))
{
Write-Host "Set Umbraco version to $version"
Set-UmbracoVersion $version
}
# full umbraco build
Write-Host "Build Umbraco"
Build-Umbraco
+18
View File
@@ -0,0 +1,18 @@
# Usage: powershell .\setversion.ps1 7.6.8
# Or: powershell .\setversion 7.6.8-beta001
param (
[Parameter(Mandatory=$true)]
[string]
$version
)
# report
Write-Host "Setting Umbraco version to $version"
# import Umbraco Build PowerShell module - $pwd is ./build
$env:PSModulePath = "$pwd\Modules\;$env:PSModulePath"
Import-Module Umbraco.Build -Force -DisableNameChecking
# run commands
$version = Set-UmbracoVersion -Version $version
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
Binary file not shown.
-138
View File
@@ -1,138 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>
<!-- Enable the restore command to run before builds -->
<RestorePackages Condition=" '$(RestorePackages)' == '' ">false</RestorePackages>
<!-- Property that enables building a package from a project -->
<BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>
<!-- Determines if package restore consent is required to restore packages -->
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>
<!-- Download NuGet.exe if it does not already exist -->
<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
</PropertyGroup>
<ItemGroup Condition=" '$(PackageSources)' == '' ">
<!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used -->
<!-- The official NuGet package source (https://www.nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list -->
<!--
<PackageSource Include="https://www.nuget.org/api/v2/" />
<PackageSource Include="https://my-nuget-source/nuget/" />
-->
<PackageSource Include="https://nuget.org/api/v2/" />
<PackageSource Include="http://www.myget.org/F/umbracocore/" />
</ItemGroup>
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
<!-- Windows specific commands -->
<NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
<PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
<!-- We need to launch nuget.exe with the mono command if we're not on windows -->
<NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
<PackagesConfig>packages.config</PackagesConfig>
</PropertyGroup>
<PropertyGroup>
<!-- NuGet command -->
<NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\NuGet.exe</NuGetExePath>
<PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>
<NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
<NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 $(NuGetExePath)</NuGetCommand>
<PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>
<RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
<NonInteractiveSwitch Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' ">-NonInteractive</NonInteractiveSwitch>
<PaddedSolutionDir Condition=" '$(OS)' == 'Windows_NT'">"$(SolutionDir) "</PaddedSolutionDir>
<PaddedSolutionDir Condition=" '$(OS)' != 'Windows_NT' ">"$(SolutionDir)"</PaddedSolutionDir>
<!-- Commands -->
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>
<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>
<!-- We need to ensure packages are restored prior to assembly resolve -->
<BuildDependsOn Condition="$(RestorePackages) == 'true'">
RestorePackages;
$(BuildDependsOn);
</BuildDependsOn>
<!-- Make the build depend on restore packages -->
<BuildDependsOn Condition="$(BuildPackage) == 'true'">
$(BuildDependsOn);
BuildPackage;
</BuildDependsOn>
</PropertyGroup>
<Target Name="CheckPrerequisites">
<!-- Raise an error if we're unable to locate nuget.exe -->
<Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
<!--
Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once.
This effectively acts as a lock that makes sure that the download operation will only happen once and all
parallel builds will have to wait for it to complete.
-->
<MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT;DownloadNuGetExe=$(DownloadNuGetExe)" />
</Target>
<Target Name="_DownloadNuGet">
<DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
</Target>
<Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(RestoreCommand)"
Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />
<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target>
<Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(BuildCommand)"
Condition=" '$(OS)' != 'Windows_NT' " />
<Exec Command="$(BuildCommand)"
LogStandardErrorAsError="true"
Condition=" '$(OS)' == 'Windows_NT' " />
</Target>
<UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<OutputFilename ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Core" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Net" />
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try {
OutputFilename = Path.GetFullPath(OutputFilename);
Log.LogMessage("Downloading latest version of NuGet.exe...");
WebClient webClient = new WebClient();
webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);
return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
-1
View File
@@ -93,7 +93,6 @@
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
+2 -2
View File
@@ -11,5 +11,5 @@ using System.Resources;
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("7.6.6")]
[assembly: AssemblyInformationalVersion("7.6.6")]
[assembly: AssemblyFileVersion("7.6.8")]
[assembly: AssemblyInformationalVersion("7.6.8")]
@@ -0,0 +1,104 @@
using System;
using System.Threading;
using System.Web;
using Umbraco.Core.Security;
namespace Umbraco.Core.Auditing
{
/// <summary>
/// This class is used by events raised from hthe BackofficeUserManager
/// </summary>
public class IdentityAuditEventArgs : EventArgs
{
/// <summary>
/// The action that got triggered from the audit event
/// </summary>
public AuditEvent Action { get; private set; }
/// <summary>
/// Current date/time in UTC format
/// </summary>
public DateTime DateTimeUtc { get; private set; }
/// <summary>
/// The source IP address of the user performing the action
/// </summary>
public string IpAddress { get; private set; }
/// <summary>
/// The user affected by the event raised
/// </summary>
public int AffectedUser { get; private set; }
/// <summary>
/// If a user is perfoming an action on a different user, then this will be set. Otherwise it will be -1
/// </summary>
public int PerformingUser { get; private set; }
/// <summary>
/// An optional comment about the action being logged
/// </summary>
public string Comment { get; private set; }
/// <summary>
/// This property is always empty except in the LoginFailed event for an unknown user trying to login
/// </summary>
public string Username { get; private set; }
/// <summary>
/// Sets the properties on the event being raised, all parameters are optional except for the action being performed
/// </summary>
/// <param name="action">An action based on the AuditEvent enum</param>
/// <param name="ipAddress">The client's IP address. This is usually automatically set but could be overridden if necessary</param>
/// <param name="performingUser">The Id of the user performing the action (if different from the user affected by the action)</param>
public IdentityAuditEventArgs(AuditEvent action, string ipAddress, int performingUser = -1)
{
DateTimeUtc = DateTime.UtcNow;
Action = action;
IpAddress = ipAddress;
PerformingUser = performingUser == -1
? GetCurrentRequestBackofficeUserId()
: performingUser;
}
public IdentityAuditEventArgs(AuditEvent action, string ipAddress, string username, string comment)
{
DateTimeUtc = DateTime.UtcNow;
Action = action;
IpAddress = ipAddress;
Username = username;
Comment = comment;
}
/// <summary>
/// Returns the current logged in backoffice user's Id logging if there is one
/// </summary>
/// <returns></returns>
protected int GetCurrentRequestBackofficeUserId()
{
var userId = -1;
var backOfficeIdentity = Thread.CurrentPrincipal.GetUmbracoIdentity();
if (backOfficeIdentity != null)
int.TryParse(backOfficeIdentity.Id.ToString(), out userId);
return userId;
}
}
public enum AuditEvent
{
AccountLocked,
AccountUnlocked,
ForgotPasswordRequested,
ForgotPasswordChangedSuccess,
LoginFailed,
LoginRequiresVerification,
LoginSucces,
LogoutSuccess,
PasswordChanged,
PasswordReset,
ResetAccessFailedCount
}
}
@@ -1,12 +1,19 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Xml.Linq;
using ClientDependency.Core.CompositeFiles.Providers;
using ClientDependency.Core.Config;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
namespace Umbraco.Core.Configuration
{
internal class ClientDependencyConfiguration
{
/// <summary>
/// A utility class for working with CDF config and cache files - use sparingly!
/// </summary>
public class ClientDependencyConfiguration
{
private readonly ILogger _logger;
private readonly string _fileName;
@@ -21,7 +28,7 @@ namespace Umbraco.Core.Configuration
/// <summary>
/// Changes the version number in ClientDependency.config to a random value to avoid stale caches
/// </summary>
internal bool IncreaseVersionNumber()
public bool IncreaseVersionNumber()
{
try
{
@@ -49,5 +56,55 @@ namespace Umbraco.Core.Configuration
return false;
}
/// <summary>
/// Clears the temporary files stored for the ClientDependency folder
/// </summary>
/// <param name="currentHttpContext"></param>
public bool ClearTempFiles(HttpContextBase currentHttpContext)
{
var cdfTempDirectories = new HashSet<string>();
foreach (BaseCompositeFileProcessingProvider provider in ClientDependencySettings.Instance
.CompositeFileProcessingProviderCollection)
{
var path = provider.CompositeFilePath.FullName;
cdfTempDirectories.Add(path);
}
try
{
var fullPath = currentHttpContext.Server.MapPath(XmlFileMapper.FileMapVirtualFolder);
if (fullPath != null)
{
cdfTempDirectories.Add(fullPath);
}
}
catch (Exception ex)
{
//invalid path format or something... try/catch to be safe
LogHelper.Error<ClientDependencyConfiguration>("Could not get path from ClientDependency.config", ex);
}
var success = true;
foreach (var directory in cdfTempDirectories)
{
var directoryInfo = new DirectoryInfo(directory);
if (directoryInfo.Exists == false)
continue;
try
{
directoryInfo.Delete(true);
}
catch (Exception ex)
{
// Something could be locking the directory or the was another error, making sure we don't break the upgrade installer
LogHelper.Error<ClientDependencyConfiguration>("Could not clear temp files", ex);
success = false;
}
}
return success;
}
}
}
@@ -6,7 +6,7 @@ namespace Umbraco.Core.Configuration
{
public class UmbracoVersion
{
private static readonly Version Version = new Version("7.6.6");
private static readonly Version Version = new Version("7.6.8");
/// <summary>
/// Gets the current version of Umbraco.
+10
View File
@@ -222,6 +222,16 @@ namespace Umbraco.Core
/// Guid for a Forms DataSource.
/// </summary>
public static readonly Guid LanguageGuid = new Guid(Language);
/// <summary>
/// Guid for an Identifier Reservation.
/// </summary>
public const string IdReservation = "92849B1E-3904-4713-9356-F646F87C25F4";
/// <summary>
/// Guid for an Identifier Reservation.
/// </summary>
public static readonly Guid IdReservationGuid = new Guid(IdReservation);
}
}
}
+23
View File
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using AutoMapper;
@@ -399,6 +400,28 @@ namespace Umbraco.Core
if (ApplicationContext.IsConfigured == false) return;
if (ApplicationContext.DatabaseContext.IsDatabaseConfigured == false) return;
// deal with localdb
var databaseContext = ApplicationContext.DatabaseContext;
var localdbex = new Regex(@"\(localdb\)\\([a-zA-Z0-9-_]+)(;|$)");
var m = localdbex.Match(databaseContext.ConnectionString);
if (m.Success)
{
var instanceName = m.Groups[1].Value;
ProfilingLogger.Logger.Info<CoreBootManager>(string.Format("LocalDb instance \"{0}\"", instanceName));
var localDb = new LocalDb();
if (localDb.IsAvailable == false)
throw new UmbracoStartupFailedException("Umbraco cannot start. LocalDb is not available.");
if (localDb.InstanceExists(m.Groups[1].Value) == false)
{
if (localDb.CreateInstance(instanceName) == false)
throw new UmbracoStartupFailedException(string.Format("Umbraco cannot start. LocalDb cannot create instance \"{0}\".", instanceName));
if (localDb.StartInstance(instanceName) == false)
throw new UmbracoStartupFailedException(string.Format("Umbraco cannot start. LocalDb cannot start instance \"{0}\".", instanceName));
}
}
//try now
if (ApplicationContext.DatabaseContext.CanConnect)
return;
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace Umbraco.Core.Deploy
{
@@ -38,5 +39,10 @@ namespace Umbraco.Core.Deploy
/// <param name="key">The key of the item.</param>
/// <returns>The item with the specified key and type, if any, else null.</returns>
T Item<T>(string key) where T : class;
///// <summary>
///// Gets the global deployment cancellation token.
///// </summary>
//CancellationToken CancellationToken { get; }
}
}
+11
View File
@@ -295,5 +295,16 @@ namespace Umbraco.Core
return list1Groups.Count == list2Groups.Count
&& list1Groups.All(g => g.Count() == list2Groups[g.Key].Count());
}
public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source)
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext() == false) yield break;
for (var value = e.Current; e.MoveNext(); value = e.Current)
yield return value;
}
}
}
}
+10 -6
View File
@@ -32,7 +32,11 @@ namespace Umbraco.Core
public GuidUdi(Uri uriValue)
: base(uriValue)
{
Guid = Guid.Parse(uriValue.AbsolutePath.TrimStart('/'));
Guid guid;
if (Guid.TryParse(uriValue.AbsolutePath.TrimStart('/'), out guid) == false)
throw new FormatException("Url \"" + uriValue + "\" is not a guid entity id.");
Guid = guid;
}
/// <summary>
@@ -43,16 +47,17 @@ namespace Umbraco.Core
public new static GuidUdi Parse(string s)
{
var udi = Udi.Parse(s);
if (!(udi is GuidUdi))
if (udi is GuidUdi == false)
throw new FormatException("String \"" + s + "\" is not a guid entity id.");
return (GuidUdi)udi;
return (GuidUdi) udi;
}
public static bool TryParse(string s, out GuidUdi udi)
{
Udi tmp;
udi = null;
if (!TryParse(s, out tmp)) return false;
if (TryParse(s, out tmp) == false) return false;
udi = tmp as GuidUdi;
return udi != null;
}
@@ -75,10 +80,9 @@ namespace Umbraco.Core
get { return Guid == Guid.Empty; }
}
/// <inheritdoc/>
public GuidUdi EnsureClosed()
{
base.EnsureNotRoot();
EnsureNotRoot();
return this;
}
}
-3
View File
@@ -1,8 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
+2 -3
View File
@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
@@ -278,10 +277,10 @@ namespace Umbraco.Core.Models
if (Properties.Contains(propertyTypeAlias) == false)
{
return default(TPassType);
}
}
var convertAttempt = Properties[propertyTypeAlias].Value.TryConvertTo<TPassType>();
return convertAttempt.Success ? convertAttempt.Result : default(TPassType);
return convertAttempt.Success ? convertAttempt.Result : default(TPassType);
}
/// <summary>
+1 -4
View File
@@ -1,10 +1,7 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
namespace Umbraco.Core.Models.EntityBase
{
@@ -102,7 +99,7 @@ namespace Umbraco.Core.Models.EntityBase
}
[IgnoreDataMember]
public DateTime? DeletedDate { get; set; }
public DateTime? DeletedDate { get; set; }
internal virtual void ResetIdentity()
{
@@ -93,6 +93,10 @@ namespace Umbraco.Core.Models
//NOTE: Consider checking type before value is set: item.PropertyType.DataTypeId == property.PropertyType.DataTypeId
//Transfer the existing value to the new property
var property = this[key];
if (item.Id == 0 && property.Id != 0)
{
item.Id = property.Id;
}
if (item.Value == null && property.Value != null)
{
item.Value = property.Value;
@@ -185,6 +185,13 @@ namespace Umbraco.Core.Models
/// </summary>
[UmbracoObjectType(Constants.ObjectTypes.Language)]
[FriendlyName("Language")]
Language
Language,
/// <summary>
/// Reserved Identifier
/// </summary>
[UmbracoObjectType(Constants.ObjectTypes.IdReservation)]
[FriendlyName("Identifier Reservation")]
IdReservation
}
}
+959
View File
@@ -0,0 +1,959 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Umbraco.Core.Persistence
{
/// <summary>
/// Manages LocalDB databases.
/// </summary>
/// <remarks>
/// <para>Latest version is SQL Server 2016 Express LocalDB,
/// see https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/sql-server-2016-express-localdb
/// which can be installed by downloading the Express installer from https://www.microsoft.com/en-us/sql-server/sql-server-downloads
/// (about 5MB) then select 'download media' to download SqlLocalDB.msi (about 44MB), which you can execute. This installs
/// LocalDB only. Though you probably want to install the full Express. You may also want to install SQL Server Management
/// Studio which can be used to connect to LocalDB databases.</para>
/// <para>See also https://github.com/ritterim/automation-sql which is a somewhat simpler version of this.</para>
/// </remarks>
internal class LocalDb
{
private int _version;
private bool _hasVersion;
#region Availability & Version
/// <summary>
/// Gets the LocalDb installed version.
/// </summary>
/// <remarks>If more than one version is installed, returns the highest available. Returns
/// the major version as an integer e.g. 11, 12...</remarks>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
public int Version
{
get
{
EnsureVersion();
if (_version <= 0)
throw new InvalidOperationException("LocalDb is not available.");
return _version;
}
}
/// <summary>
/// Ensures that the LocalDb version is detected.
/// </summary>
private void EnsureVersion()
{
if (_hasVersion) return;
DetectVersion();
_hasVersion = true;
}
/// <summary>
/// Gets a value indicating whether LocalDb is available.
/// </summary>
public bool IsAvailable
{
get
{
EnsureVersion();
return _version > 0;
}
}
/// <summary>
/// Ensures that LocalDb is available.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
private void EnsureAvailable()
{
if (IsAvailable == false)
throw new InvalidOperationException("LocalDb is not available.");
}
/// <summary>
/// Detects LocalDb installed version.
/// </summary>
/// <remarks>If more than one version is installed, the highest available is detected.</remarks>
private void DetectVersion()
{
_hasVersion = true;
_version = -1;
var programFiles = Environment.GetEnvironmentVariable("ProgramFiles");
if (programFiles == null) return;
// detect 14, 13, 12, 11
for (var i = 14; i > 10; i--)
{
var path = Path.Combine(programFiles, string.Format(@"Microsoft SQL Server\{0}0\Tools\Binn\SqlLocalDB.exe", i));
if (File.Exists(path) == false) continue;
_version = i;
break;
}
}
#endregion
#region Instances
/// <summary>
/// Gets the name of existing LocalDb instances.
/// </summary>
/// <returns>The name of existing LocalDb instances.</returns>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
public string[] GetInstances()
{
EnsureAvailable();
string output, error;
var rc = ExecuteSqlLocalDb("i", out output, out error); // info
if (rc != 0 || error != string.Empty) return null;
return output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// Gets a value indicating whether a LocalDb instance exists.
/// </summary>
/// <param name="instanceName">The name of the instance.</param>
/// <returns>A value indicating whether a LocalDb instance with the specified name exists.</returns>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
public bool InstanceExists(string instanceName)
{
EnsureAvailable();
var instances = GetInstances();
return instances != null && instances.Contains(instanceName);
}
/// <summary>
/// Creates a LocalDb instance.
/// </summary>
/// <param name="instanceName">The name of the instance.</param>
/// <returns>A value indicating whether the instance was created without errors.</returns>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
public bool CreateInstance(string instanceName)
{
EnsureAvailable();
string output, error;
return ExecuteSqlLocalDb(string.Format("c \"{0}\"", instanceName), out output, out error) == 0 && error == string.Empty;
}
/// <summary>
/// Drops a LocalDb instance.
/// </summary>
/// <param name="instanceName">The name of the instance.</param>
/// <returns>A value indicating whether the instance was dropped without errors.</returns>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
/// <remarks>
/// When an instance is dropped all the attached database files are deleted.
/// Successful if the instance does not exist.
/// </remarks>
public bool DropInstance(string instanceName)
{
EnsureAvailable();
var instance = GetInstance(instanceName);
if (instance == null) return true;
instance.DropDatabases(); // else the files remain
// -i force NOWAIT, -k kills
string output, error;
return ExecuteSqlLocalDb(string.Format("p \"{0}\" -i", instanceName), out output, out error) == 0 && error == string.Empty
&& ExecuteSqlLocalDb(string.Format("d \"{0}\"", instanceName), out output, out error) == 0 && error == string.Empty;
}
/// <summary>
/// Stops a LocalDb instance.
/// </summary>
/// <param name="instanceName">The name of the instance.</param>
/// <returns>A value indicating whether the instance was stopped without errors.</returns>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
/// <remarks>
/// Successful if the instance does not exist.
/// </remarks>
public bool StopInstance(string instanceName)
{
EnsureAvailable();
if (InstanceExists(instanceName) == false) return true;
// -i force NOWAIT, -k kills
string output, error;
return ExecuteSqlLocalDb(string.Format("p \"{0}\" -i", instanceName), out output, out error) == 0 && error == string.Empty;
}
/// <summary>
/// Stops a LocalDb instance.
/// </summary>
/// <param name="instanceName">The name of the instance.</param>
/// <returns>A value indicating whether the instance was started without errors.</returns>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
/// <remarks>
/// Failed if the instance does not exist.
/// </remarks>
public bool StartInstance(string instanceName)
{
EnsureAvailable();
if (InstanceExists(instanceName) == false) return false;
string output, error;
return ExecuteSqlLocalDb(string.Format("s \"{0}\"", instanceName), out output, out error) == 0 && error == string.Empty;
}
/// <summary>
/// Gets a LocalDb instance.
/// </summary>
/// <param name="instanceName">The name of the instance.</param>
/// <returns>The instance with the specified name if it exists, otherwise null.</returns>
/// <exception cref="InvalidOperationException">Thrown when LocalDb is not available.</exception>
public Instance GetInstance(string instanceName)
{
EnsureAvailable();
return InstanceExists(instanceName) ? new Instance(instanceName) : null;
}
#endregion
#region Databases
/// <summary>
/// Represents a LocalDb instance.
/// </summary>
/// <remarks>
/// LocalDb is assumed to be available, and the instance is assumed to exist.
/// </remarks>
public class Instance
{
private readonly string _masterCstr;
/// <summary>
/// Gets the name of the instance.
/// </summary>
public string InstanceName { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Instance"/> class.
/// </summary>
/// <param name="instanceName"></param>
public Instance(string instanceName)
{
InstanceName = instanceName;
_masterCstr = string.Format(@"Server=(localdb)\{0};Integrated Security=True;", instanceName);
}
/// <summary>
/// Gets a LocalDb connection string.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <returns>The connection string for the specified database.</returns>
/// <remarks>
/// The database should exist in the LocalDb instance.
/// </remarks>
public string GetConnectionString(string databaseName)
{
return _masterCstr + string.Format(@"Database={0};", databaseName);
}
/// <summary>
/// Gets a LocalDb connection string for an attached database.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <param name="filesPath">The directory containing database files.</param>
/// <returns>The connection string for the specified database.</returns>
/// <remarks>
/// The database should not exist in the LocalDb instance.
/// It will be attached with its name being its MDF filename (full path), uppercased, when
/// the first connection is opened, and remain attached until explicitely detached.
/// </remarks>
public string GetAttachedConnectionString(string databaseName, string filesPath)
{
string logName, baseFilename, baseLogFilename, mdfFilename, ldfFilename;
GetDatabaseFiles(databaseName, filesPath, out logName, out baseFilename, out baseLogFilename, out mdfFilename, out ldfFilename);
return _masterCstr + string.Format(@"AttachDbFileName='{0}';", mdfFilename);
}
/// <summary>
/// Gets the name of existing databases.
/// </summary>
/// <returns>The name of existing databases.</returns>
public string[] GetDatabases()
{
var userDatabases = new List<string>();
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var databases = new Dictionary<string, string>();
SetCommand(cmd, @"
SELECT name, filename FROM sys.sysdatabases");
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
databases[reader.GetString(0)] = reader.GetString(1);
}
}
foreach (var database in databases)
{
var dbname = database.Key;
if (dbname == "master" || dbname == "tempdb" || dbname == "model" || dbname == "msdb")
continue;
// fixme - shall we deal with stale databases?
// fixme - is it always ok to assume file names?
//var mdf = database.Value;
//var ldf = mdf.Replace(".mdf", "_log.ldf");
//if (staleOnly && File.Exists(mdf) && File.Exists(ldf))
// continue;
//ExecuteDropDatabase(cmd, dbname, mdf, ldf);
//count++;
userDatabases.Add(dbname);
}
}
return userDatabases.ToArray();
}
/// <summary>
/// Gets a value indicating whether a database exists.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <returns>A value indicating whether a database with the specified name exists.</returns>
/// <remarks>
/// A database exists if it is registered in the instance, and its files exist. If the database
/// is registered but some of its files are missing, the database is dropped.
/// </remarks>
public bool DatabaseExists(string databaseName)
{
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var mdf = GetDatabase(cmd, databaseName);
if (mdf == null) return false;
// it can exist, even though its files have been deleted
// if files exist assume all is ok (should we try to connect?)
var ldf = GetLogFilename(mdf);
if (File.Exists(mdf) && File.Exists(ldf))
return true;
ExecuteDropDatabase(cmd, databaseName, mdf, ldf);
}
return false;
}
/// <summary>
/// Creates a new database.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <param name="filesPath">The directory containing database files.</param>
/// <returns>A value indicating whether the database was created without errors.</returns>
/// <remarks>
/// Failed if a database with the specified name already exists in the instance,
/// or if the database files already exist in the specified directory.
/// </remarks>
public bool CreateDatabase(string databaseName, string filesPath)
{
string logName, baseFilename, baseLogFilename, mdfFilename, ldfFilename;
GetDatabaseFiles(databaseName, filesPath, out logName, out baseFilename, out baseLogFilename, out mdfFilename, out ldfFilename);
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var mdf = GetDatabase(cmd, databaseName);
if (mdf != null) return false;
// cannot use parameters on CREATE DATABASE
// ie "CREATE DATABASE @0 ..." does not work
SetCommand(cmd, string.Format(@"
CREATE DATABASE {0}
ON (NAME=N{1}, FILENAME={2})
LOG ON (NAME=N{3}, FILENAME={4})",
QuotedName(databaseName),
QuotedName(databaseName, '\''), QuotedName(mdfFilename, '\''),
QuotedName(logName, '\''), QuotedName(ldfFilename, '\'')));
var unused = cmd.ExecuteNonQuery();
}
return true;
}
/// <summary>
/// Drops a database.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <returns>A value indicating whether the database was dropped without errors.</returns>
/// <remarks>
/// Successful if the database does not exist.
/// Deletes the database files.
/// </remarks>
public bool DropDatabase(string databaseName)
{
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
SetCommand(cmd, @"
SELECT name, filename FROM master.dbo.sysdatabases WHERE ('[' + name + ']' = @0 OR name = @0)",
databaseName);
var mdf = GetDatabase(cmd, databaseName);
if (mdf == null) return true;
ExecuteDropDatabase(cmd, databaseName, mdf);
}
return true;
}
/// <summary>
/// Drops stale databases.
/// </summary>
/// <returns>The number of databases that were dropped.</returns>
/// <remarks>
/// A database is considered stale when its files cannot be found.
/// </remarks>
public int DropStaleDatabases()
{
return DropDatabases(true);
}
/// <summary>
/// Drops databases.
/// </summary>
/// <param name="staleOnly">A value indicating whether to delete only stale database.</param>
/// <returns>The number of databases that were dropped.</returns>
/// <remarks>
/// A database is considered stale when its files cannot be found.
/// </remarks>
public int DropDatabases(bool staleOnly = false)
{
var count = 0;
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var databases = new Dictionary<string, string>();
SetCommand(cmd, @"
SELECT name, filename FROM sys.sysdatabases");
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
databases[reader.GetString(0)] = reader.GetString(1);
}
}
foreach (var database in databases)
{
var dbname = database.Key;
if (dbname == "master" || dbname == "tempdb" || dbname == "model" || dbname == "msdb")
continue;
var mdf = database.Value;
var ldf = mdf.Replace(".mdf", "_log.ldf");
if (staleOnly && File.Exists(mdf) && File.Exists(ldf))
continue;
ExecuteDropDatabase(cmd, dbname, mdf, ldf);
count++;
}
}
return count;
}
/// <summary>
/// Detaches a database.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <returns>The directory containing the database files.</returns>
/// <exception cref="InvalidOperationException">Thrown when a database with the specified name does not exist.</exception>
public string DetachDatabase(string databaseName)
{
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var mdf = GetDatabase(cmd, databaseName);
if (mdf == null)
throw new InvalidOperationException("Database does not exist.");
DetachDatabase(cmd, databaseName);
return Path.GetDirectoryName(mdf);
}
}
/// <summary>
/// Attaches a database.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <param name="filesPath">The directory containing database files.</param>
/// <exception cref="InvalidOperationException">Thrown when a database with the specified name already exists.</exception>
public void AttachDatabase(string databaseName, string filesPath)
{
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
var mdf = GetDatabase(cmd, databaseName);
if (mdf != null)
throw new InvalidOperationException("Database already exists.");
AttachDatabase(cmd, databaseName, filesPath);
}
}
/// <summary>
/// Gets the file names of a database.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <param name="mdfName">The MDF logical name.</param>
/// <param name="ldfName">The LDF logical name.</param>
/// <param name="mdfFilename">The MDF filename.</param>
/// <param name="ldfFilename">The LDF filename.</param>
public void GetFilenames(string databaseName,
out string mdfName, out string ldfName,
out string mdfFilename, out string ldfFilename)
{
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
GetFilenames(cmd, databaseName, out mdfName, out ldfName, out mdfFilename, out ldfFilename);
}
}
/// <summary>
/// Kills all existing connections.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
public void KillConnections(string databaseName)
{
using (var conn = new SqlConnection(_masterCstr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
SetCommand(cmd, @"
DECLARE @sql VARCHAR(MAX);
SELECT @sql = COALESCE(@sql,'') + 'kill ' + CONVERT(VARCHAR, SPId) + ';'
FROM master.sys.sysprocesses
WHERE DBId = DB_ID(@0) AND SPId <> @@SPId;
EXEC(@sql);",
databaseName);
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Gets a database.
/// </summary>
/// <param name="cmd">The Sql Command.</param>
/// <param name="databaseName">The name of the database.</param>
/// <returns>The full filename of the MDF file, if the database exists, otherwise null.</returns>
private static string GetDatabase(SqlCommand cmd, string databaseName)
{
SetCommand(cmd, @"
SELECT name, filename FROM master.dbo.sysdatabases WHERE ('[' + name + ']' = @0 OR name = @0)",
databaseName);
string mdf = null;
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
mdf = reader.GetString(1) ?? string.Empty;
while (reader.Read())
{
}
}
return mdf;
}
/// <summary>
/// Drops a database and its files.
/// </summary>
/// <param name="cmd">The Sql command.</param>
/// <param name="databaseName">The name of the database.</param>
/// <param name="mdf">The name of the database (MDF) file.</param>
/// <param name="ldf">The name of the log (LDF) file.</param>
private static void ExecuteDropDatabase(SqlCommand cmd, string databaseName, string mdf, string ldf = null)
{
try
{
// cannot use parameters on ALTER DATABASE
// ie "ALTER DATABASE @0 ..." does not work
SetCommand(cmd, string.Format(@"
ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE",
QuotedName(databaseName)));
var unused1 = cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
if (e.Message.Contains("Unable to open the physical file") && e.Message.Contains("Operating system error 2:"))
{
// quite probably, the files were missing
// yet, it should be possible to drop the database anyways
// but we'll have to deal with the files
}
else
{
// no idea, throw
throw;
}
}
// cannot use parameters on DROP DATABASE
// ie "DROP DATABASE @0 ..." does not work
SetCommand(cmd, string.Format(@"
DROP DATABASE {0}",
QuotedName(databaseName)));
var unused2 = cmd.ExecuteNonQuery();
// be absolutely sure
if (File.Exists(mdf)) File.Delete(mdf);
ldf = ldf ?? GetLogFilename(mdf);
if (File.Exists(ldf)) File.Delete(ldf);
}
/// <summary>
/// Gets the log (LDF) filename corresponding to a database (MDF) filename.
/// </summary>
/// <param name="mdfFilename">The MDF filename.</param>
/// <returns></returns>
private static string GetLogFilename(string mdfFilename)
{
if (mdfFilename.EndsWith(".mdf") == false)
throw new ArgumentException("Not a valid MDF filename (no .mdf extension).", "mdfFilename");
return mdfFilename.Substring(0, mdfFilename.Length - ".mdf".Length) + "_log.ldf";
}
/// <summary>
/// Detaches a database.
/// </summary>
/// <param name="cmd">The Sql command.</param>
/// <param name="databaseName">The name of the database.</param>
private static void DetachDatabase(SqlCommand cmd, string databaseName)
{
// cannot use parameters on ALTER DATABASE
// ie "ALTER DATABASE @0 ..." does not work
SetCommand(cmd, string.Format(@"
ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE",
QuotedName(databaseName)));
var unused1 = cmd.ExecuteNonQuery();
SetCommand(cmd, @"
EXEC sp_detach_db @dbname=@0",
databaseName);
var unused2 = cmd.ExecuteNonQuery();
}
/// <summary>
/// Attaches a database.
/// </summary>
/// <param name="cmd">The Sql command.</param>
/// <param name="databaseName">The name of the database.</param>
/// <param name="filesPath">The directory containing database files.</param>
private static void AttachDatabase(SqlCommand cmd, string databaseName, string filesPath)
{
string logName, baseFilename, baseLogFilename, mdfFilename, ldfFilename;
GetDatabaseFiles(databaseName, filesPath, out logName, out baseFilename, out baseLogFilename, out mdfFilename, out ldfFilename);
// cannot use parameters on CREATE DATABASE
// ie "CREATE DATABASE @0 ..." does not work
SetCommand(cmd, string.Format(@"
CREATE DATABASE {0}
ON (NAME=N{1}, FILENAME={2})
LOG ON (NAME=N{3}, FILENAME={4})
FOR ATTACH",
QuotedName(databaseName),
QuotedName(databaseName, '\''), QuotedName(mdfFilename, '\''),
QuotedName(logName, '\''), QuotedName(ldfFilename, '\'')));
var unused = cmd.ExecuteNonQuery();
}
/// <summary>
/// Sets a database command.
/// </summary>
/// <param name="cmd">The command.</param>
/// <param name="sql">The command text.</param>
/// <param name="args">The command arguments.</param>
/// <remarks>
/// The command text must refer to arguments as @0, @1... each referring
/// to the corresponding position in <paramref name="args"/>.
/// </remarks>
private static void SetCommand(SqlCommand cmd, string sql, params object[] args)
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.Clear();
for (var i = 0; i < args.Length; i++)
cmd.Parameters.AddWithValue("@" + i, args[i]);
}
/// <summary>
/// Gets the file names of a database.
/// </summary>
/// <param name="cmd">The Sql command.</param>
/// <param name="databaseName">The name of the database.</param>
/// <param name="mdfName">The MDF logical name.</param>
/// <param name="ldfName">The LDF logical name.</param>
/// <param name="mdfFilename">The MDF filename.</param>
/// <param name="ldfFilename">The LDF filename.</param>
private void GetFilenames(SqlCommand cmd, string databaseName,
out string mdfName, out string ldfName,
out string mdfFilename, out string ldfFilename)
{
mdfName = ldfName = mdfFilename = ldfFilename = null;
SetCommand(cmd, @"
SELECT DB_NAME(database_id), type_desc, name, physical_name
FROM master.sys.master_files
WHERE database_id=DB_ID(@0)",
databaseName);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var type = reader.GetString(1);
if (type == "ROWS")
{
mdfName = reader.GetString(2);
ldfName = reader.GetString(3);
}
else if (type == "LOG")
{
ldfName = reader.GetString(2);
ldfFilename = reader.GetString(3);
}
}
}
}
}
/// <summary>
/// Copy database files.
/// </summary>
/// <param name="databaseName">The name of the source database.</param>
/// <param name="filesPath">The directory containing source database files.</param>
/// <param name="targetDatabaseName">The name of the target database.</param>
/// <param name="targetFilesPath">The directory containing target database files.</param>
/// <param name="sourceExtension">The source database files extension.</param>
/// <param name="targetExtension">The target database files extension.</param>
/// <param name="overwrite">A value indicating whether to overwrite the target files.</param>
/// <param name="delete">A value indicating whether to delete the source files.</param>
/// <remarks>
/// The <paramref name="targetDatabaseName"/>, <paramref name="targetFilesPath"/>, <paramref name="sourceExtension"/>
/// and <paramref name="targetExtension"/> parameters are optional. If they result in target being identical
/// to source, no copy is performed. If <paramref name="delete"/> is false, nothing happens, otherwise the source
/// files are deleted.
/// If target is not identical to source, files are copied or moved, depending on the value of <paramref name="delete"/>.
/// Extensions are used eg to copy MyDatabase.mdf to MyDatabase.mdf.temp.
/// </remarks>
public void CopyDatabaseFiles(string databaseName, string filesPath,
string targetDatabaseName = null, string targetFilesPath = null,
string sourceExtension = null, string targetExtension = null,
bool overwrite = false, bool delete = false)
{
var nop = (targetFilesPath == null || targetFilesPath == filesPath)
&& (targetDatabaseName == null || targetDatabaseName == databaseName)
&& (sourceExtension == null && targetExtension == null || sourceExtension == targetExtension);
if (nop && delete == false) return;
string logName, baseFilename, baseLogFilename, mdfFilename, ldfFilename;
GetDatabaseFiles(databaseName, filesPath,
out logName, out baseFilename, out baseLogFilename, out mdfFilename, out ldfFilename);
if (sourceExtension != null)
{
mdfFilename += "." + sourceExtension;
ldfFilename += "." + sourceExtension;
}
if (nop)
{
// delete
if (File.Exists(mdfFilename)) File.Delete(mdfFilename);
if (File.Exists(ldfFilename)) File.Delete(ldfFilename);
}
else
{
// copy or copy+delete ie move
string targetLogName, targetBaseFilename, targetLogFilename, targetMdfFilename, targetLdfFilename;
GetDatabaseFiles(targetDatabaseName ?? databaseName, targetFilesPath ?? filesPath,
out targetLogName, out targetBaseFilename, out targetLogFilename, out targetMdfFilename, out targetLdfFilename);
if (targetExtension != null)
{
targetMdfFilename += "." + targetExtension;
targetLdfFilename += "." + targetExtension;
}
if (delete)
{
if (overwrite && File.Exists(targetMdfFilename)) File.Delete(targetMdfFilename);
if (overwrite && File.Exists(targetLdfFilename)) File.Delete(targetLdfFilename);
File.Move(mdfFilename, targetMdfFilename);
File.Move(ldfFilename, targetLdfFilename);
}
else
{
File.Copy(mdfFilename, targetMdfFilename, overwrite);
File.Copy(ldfFilename, targetLdfFilename, overwrite);
}
}
}
/// <summary>
/// Gets a value indicating whether database files exist.
/// </summary>
/// <param name="databaseName">The name of the source database.</param>
/// <param name="filesPath">The directory containing source database files.</param>
/// <param name="extension">The database files extension.</param>
/// <returns>A value indicating whether the database files exist.</returns>
/// <remarks>
/// Extensions are used eg to copy MyDatabase.mdf to MyDatabase.mdf.temp.
/// </remarks>
public bool DatabaseFilesExist(string databaseName, string filesPath, string extension = null)
{
string logName, baseFilename, baseLogFilename, mdfFilename, ldfFilename;
GetDatabaseFiles(databaseName, filesPath,
out logName, out baseFilename, out baseLogFilename, out mdfFilename, out ldfFilename);
if (extension != null)
{
mdfFilename += "." + extension;
ldfFilename += "." + extension;
}
return File.Exists(mdfFilename) && File.Exists(ldfFilename);
}
/// <summary>
/// Gets the name of the database files.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
/// <param name="filesPath">The directory containing database files.</param>
/// <param name="logName">The name of the log.</param>
/// <param name="baseFilename">The base filename (the MDF filename without the .mdf extension).</param>
/// <param name="baseLogFilename">The base log filename (the LDF filename without the .ldf extension).</param>
/// <param name="mdfFilename">The MDF filename.</param>
/// <param name="ldfFilename">The LDF filename.</param>
private static void GetDatabaseFiles(string databaseName, string filesPath,
out string logName,
out string baseFilename, out string baseLogFilename,
out string mdfFilename, out string ldfFilename)
{
logName = databaseName + "_log";
baseFilename = Path.Combine(filesPath, databaseName);
baseLogFilename = Path.Combine(filesPath, logName);
mdfFilename = baseFilename + ".mdf";
ldfFilename = baseFilename + "_log.ldf";
}
#endregion
#region SqlLocalDB
/// <summary>
/// Executes the SqlLocalDB command.
/// </summary>
/// <param name="args">The arguments.</param>
/// <param name="output">The command standard output.</param>
/// <param name="error">The command error output.</param>
/// <returns>The process exit code.</returns>
/// <remarks>
/// Execution is successful if the exit code is zero, and error is empty.
/// </remarks>
private int ExecuteSqlLocalDb(string args, out string output, out string error)
{
var programFiles = Environment.GetEnvironmentVariable("ProgramFiles");
if (programFiles == null)
{
output = string.Empty;
error = "SqlLocalDB.exe not found";
return -1;
}
var path = Path.Combine(programFiles, string.Format(@"Microsoft SQL Server\{0}0\Tools\Binn\SqlLocalDB.exe", _version));
var p = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
FileName = path,
Arguments = args,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
}
};
p.Start();
output = p.StandardOutput.ReadToEnd();
error = p.StandardError.ReadToEnd();
p.WaitForExit();
return p.ExitCode;
}
/// <summary>
/// Returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier.
/// </summary>
/// <param name="name">The name to quote.</param>
/// <param name="quote">A quote character.</param>
/// <returns></returns>
/// <remarks>
/// This is a C# implementation of T-SQL QUOTEDNAME.
/// <paramref name="quote"/> is optional, it can be '[' (default), ']', '\'' or '"'.
/// </remarks>
private static string QuotedName(string name, char quote = '[')
{
switch (quote)
{
case '[':
case ']':
return "[" + name.Replace("]", "]]") + "]";
case '\'':
return "'" + name.Replace("'", "''") + "'";
case '"':
return "\"" + name.Replace("\"", "\"\"") + "\"";
default:
throw new NotSupportedException("Not a valid quote character.");
}
}
#endregion
}
}
@@ -435,7 +435,24 @@ namespace Umbraco.Core.Persistence.Repositories
nodeDto.Path = parent.Path;
nodeDto.Level = short.Parse(level.ToString(CultureInfo.InvariantCulture));
nodeDto.SortOrder = sortOrder;
var o = Database.IsNew(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);
// note:
// there used to be a check on Database.IsNew(nodeDto) here to either Insert or Update,
// but I cannot figure out what was the point, as the node should obviously be new if
// we reach that point - removed.
// see if there's a reserved identifier for this unique id
var sql = new Sql("SELECT id FROM umbracoNode WHERE uniqueID=@0 AND nodeObjectType=@1", nodeDto.UniqueId, Constants.ObjectTypes.IdReservationGuid);
var id = Database.ExecuteScalar<int>(sql);
if (id > 0)
{
nodeDto.NodeId = id;
Database.Update(nodeDto);
}
else
{
Database.Insert(nodeDto);
}
//Update with new correct path
nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
@@ -84,7 +84,7 @@ namespace Umbraco.Core.Persistence.Repositories
#endregion
#region Overrides of PetaPocoRepositoryBase<int,IMedia>
protected override Sql GetBaseQuery(BaseQueryType queryType)
{
var sql = new Sql();
@@ -153,7 +153,7 @@ namespace Umbraco.Core.Persistence.Repositories
/// This is the underlying method that processes most queries for this repository
/// </summary>
/// <param name="sqlFull">
/// The full SQL to select all media data
/// The full SQL to select all media data
/// </param>
/// <param name="pagingSqlQuery">
/// The Id SQL to just return all media ids - used to process the properties for the media item
@@ -164,7 +164,7 @@ namespace Umbraco.Core.Persistence.Repositories
{
// fetch returns a list so it's ok to iterate it in this method
var dtos = Database.Fetch<ContentVersionDto, ContentDto, NodeDto>(sqlFull);
//This is a tuple list identifying if the content item came from the cache or not
var content = new List<Tuple<IMedia, bool>>();
var defs = new DocumentDefinitionCollection();
@@ -180,7 +180,7 @@ namespace Umbraco.Core.Persistence.Repositories
if (withCache)
{
var cached = IsolatedCache.GetCacheItem<IMedia>(GetCacheIdKey<IMedia>(dto.NodeId));
//only use this cached version if the dto returned is the same version - this is just a safety check, media doesn't
//only use this cached version if the dto returned is the same version - this is just a safety check, media doesn't
//store different versions, but just in case someone corrupts some data we'll double check to be sure.
if (cached != null && cached.Version == dto.VersionId)
{
@@ -303,7 +303,7 @@ namespace Umbraco.Core.Persistence.Repositories
.From<ContentXmlDto>(SqlSyntax)
.InnerJoin<NodeDto>(SqlSyntax)
.On<ContentXmlDto, NodeDto>(SqlSyntax, left => left.NodeId, right => right.NodeId);
if (contentTypeIdsA.Length > 0)
{
xmlIdsQuery.InnerJoin<ContentDto>(SqlSyntax)
@@ -314,7 +314,7 @@ namespace Umbraco.Core.Persistence.Repositories
}
xmlIdsQuery.Where<NodeDto>(dto => dto.NodeObjectType == mediaObjectType, SqlSyntax);
var allXmlIds = Database.Fetch<int>(xmlIdsQuery);
var toRemove = allXmlIds.Except(allMediaIds).ToArray();
@@ -380,7 +380,24 @@ namespace Umbraco.Core.Persistence.Repositories
nodeDto.Path = parent.Path;
nodeDto.Level = short.Parse(level.ToString(CultureInfo.InvariantCulture));
nodeDto.SortOrder = sortOrder;
var o = Database.IsNew(nodeDto) ? Convert.ToInt32(Database.Insert(nodeDto)) : Database.Update(nodeDto);
// note:
// there used to be a check on Database.IsNew(nodeDto) here to either Insert or Update,
// but I cannot figure out what was the point, as the node should obviously be new if
// we reach that point - removed.
// see if there's a reserved identifier for this unique id
var sql = new Sql("SELECT id FROM umbracoNode WHERE uniqueID=@0 AND nodeObjectType=@1", nodeDto.UniqueId, Constants.ObjectTypes.IdReservationGuid);
var id = Database.ExecuteScalar<int>(sql);
if (id > 0)
{
nodeDto.NodeId = id;
Database.Update(nodeDto);
}
else
{
Database.Insert(nodeDto);
}
//Update with new correct path
nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
@@ -564,7 +581,7 @@ namespace Umbraco.Core.Persistence.Repositories
private IMedia CreateMediaFromDto(ContentVersionDto dto, Sql docSql)
{
var contentType = _mediaTypeRepository.Get(dto.ContentDto.ContentTypeId);
var media = MediaFactory.BuildEntity(dto, contentType);
var docDef = new DocumentDefinition(dto, contentType);
@@ -584,7 +601,7 @@ namespace Umbraco.Core.Persistence.Repositories
if (EnsureUniqueNaming == false)
return nodeName;
var names = Database.Fetch<SimilarNodeName>("SELECT id, text AS name FROM umbracoNode WHERE nodeObjectType=@objectType AND parentId=@parentId",
var names = Database.Fetch<SimilarNodeName>("SELECT id, text AS name FROM umbracoNode WHERE nodeObjectType=@objectType AND parentId=@parentId",
new { objectType = NodeObjectTypeId, parentId });
return SimilarNodeName.GetUniqueName(names, id, nodeName);
+9 -5
View File
@@ -192,7 +192,7 @@ namespace Umbraco.Core
if (File.Exists(filePath) == false) return string.Empty;
var hash = File.ReadAllText(filePath, Encoding.UTF8);
_cachedAssembliesHash = hash;
return _cachedAssembliesHash;
}
@@ -245,7 +245,7 @@ namespace Umbraco.Core
internal static string GetFileHash(IEnumerable<Tuple<FileSystemInfo, bool>> filesAndFolders, ProfilingLogger logger)
{
using (logger.TraceDuration<PluginManager>("Determining hash of code files on disk", "Hash determined"))
{
{
// get the distinct file infos to hash
var uniqInfos = new HashSet<string>();
var uniqContent = new HashSet<string>();
@@ -275,7 +275,7 @@ namespace Umbraco.Core
}
}
return generator.GenerateHash();
}
}
}
}
@@ -315,9 +315,9 @@ namespace Umbraco.Core
generator.AddFileSystemItem(fileOrFolder);
}
return generator.GenerateHash();
}
}
}
}
}
#endregion
@@ -439,6 +439,10 @@ namespace Umbraco.Core
internal void WriteCache()
{
// be absolutely sure
if (Directory.Exists(_tempFolder) == false)
Directory.CreateDirectory(_tempFolder);
var filePath = GetPluginListFilePath();
using (var stream = GetFileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, ListFileOpenWriteTimeout))
@@ -53,7 +53,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters
// Fall back on normal behaviour
if (values.Any() == false)
{
return sourceString.Split(Environment.NewLine.ToCharArray());
return sourceString.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
}
return values.ToArray();
@@ -49,7 +49,7 @@ namespace Umbraco.Core.Security
public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
var result = await PasswordSignInAsyncImpl(userName, password, isPersistent, shouldLockout);
switch (result)
{
case SignInStatus.Success:
@@ -104,6 +104,14 @@ namespace Umbraco.Core.Security
var user = await UserManager.FindByNameAsync(userName);
if (user == null)
{
var requestContext = _request.Context;
if (requestContext != null)
{
var backofficeUserManager = requestContext.GetBackOfficeUserManager();
if (backofficeUserManager != null)
backofficeUserManager.RaiseInvalidLoginAttemptEvent(userName);
}
return SignInStatus.Failure;
}
if (await UserManager.IsLockedOutAsync(user.Id))
@@ -121,6 +129,15 @@ namespace Umbraco.Core.Security
await UserManager.AccessFailedAsync(user.Id);
if (await UserManager.IsLockedOutAsync(user.Id))
{
//at this point we've just locked the user out after too many failed login attempts
var requestContext = _request.Context;
if (requestContext != null)
{
var backofficeUserManager = requestContext.GetBackOfficeUserManager();
if (backofficeUserManager != null)
backofficeUserManager.RaiseAccountLockedEvent(user.Id);
}
return SignInStatus.LockedOut;
}
}
@@ -176,7 +193,7 @@ namespace Umbraco.Core.Security
AllowRefresh = true,
IssuedUtc = nowUtc,
ExpiresUtc = nowUtc.AddMinutes(GlobalSettings.TimeOutInMinutes)
}, userIdentity, rememberBrowserIdentity);
}, userIdentity, rememberBrowserIdentity);
}
else
{
@@ -191,7 +208,9 @@ namespace Umbraco.Core.Security
//track the last login date
user.LastLoginDateUtc = DateTime.UtcNow;
user.AccessFailedCount = 0;
if (user.AccessFailedCount > 0)
//we have successfully logged in, reset the AccessFailedCount
user.AccessFailedCount = 0;
await UserManager.UpdateAsync(user);
_logger.WriteCore(TraceEventType.Information, 0,
@@ -232,4 +251,4 @@ namespace Umbraco.Core.Security
return null;
}
}
}
}
@@ -1,11 +1,11 @@
using System;
using System.Linq;
using System.Text;
using System.Configuration.Provider;
using System.Threading.Tasks;
using System.Web.Security;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;
using Umbraco.Core.Auditing;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Services;
@@ -29,7 +29,7 @@ namespace Umbraco.Core.Security
MembershipProviderBase membershipProvider)
: base(store)
{
if (options == null) throw new ArgumentNullException("options");;
if (options == null) throw new ArgumentNullException("options");
InitUserManager(this, membershipProvider, options);
}
@@ -140,8 +140,8 @@ namespace Umbraco.Core.Security
/// <param name="dataProtectionProvider"></param>
/// <returns></returns>
protected void InitUserManager(
BackOfficeUserManager<T> manager,
MembershipProviderBase membershipProvider,
BackOfficeUserManager<T> manager,
MembershipProviderBase membershipProvider,
IDataProtectionProvider dataProtectionProvider)
{
// Configure validation logic for usernames
@@ -164,7 +164,7 @@ namespace Umbraco.Core.Security
//use a custom hasher based on our membership provider
manager.PasswordHasher = new MembershipPasswordHasher(membershipProvider);
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<T, int>(dataProtectionProvider.Create("ASP.NET Identity"));
@@ -238,5 +238,192 @@ namespace Umbraco.Core.Security
/// Gets/sets the default back office user password checker
/// </summary>
public IBackOfficeUserPasswordChecker BackOfficeUserPasswordChecker { get; set; }
public override Task<IdentityResult> SetLockoutEndDateAsync(int userId, DateTimeOffset lockoutEnd)
{
var result = base.SetLockoutEndDateAsync(userId, lockoutEnd);
// The way we unlock is by setting the lockoutEnd date to the current datetime
if (result.Result.Succeeded && lockoutEnd >= DateTimeOffset.UtcNow)
RaiseAccountLockedEvent(userId);
else
RaiseAccountUnlockedEvent(userId);
return result;
}
public override Task<IdentityResult> AccessFailedAsync(int userId)
{
var result = base.AccessFailedAsync(userId);
//Slightly confusing: this will return a Success if we successfully update the AccessFailed count
if (result.Result.Succeeded)
RaiseLoginFailedEvent(userId);
return result;
}
public override Task<IdentityResult> ChangePasswordAsync(int userId, string currentPassword, string newPassword)
{
var result = base.ChangePasswordAsync(userId, currentPassword, newPassword);
if (result.Result.Succeeded)
RaisePasswordChangedEvent(userId);
return result;
}
public override async Task<IdentityResult> ResetAccessFailedCountAsync(int userId)
{
var lockoutStore = (IUserLockoutStore<BackOfficeIdentityUser, int>)Store;
var user = await FindByIdAsync(userId);
if (user == null)
throw new InvalidOperationException("No user found by user id " + userId);
var accessFailedCount = await GetAccessFailedCountAsync(user.Id);
if (accessFailedCount == 0)
return IdentityResult.Success;
await lockoutStore.ResetAccessFailedCountAsync(user);
//raise the event now that it's reset
RaiseResetAccessFailedCountEvent(userId);
return await UpdateAsync(user);
}
internal void RaiseAccountLockedEvent(int userId)
{
OnAccountLocked(new IdentityAuditEventArgs(AuditEvent.AccountLocked, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseAccountUnlockedEvent(int userId)
{
OnAccountUnlocked(new IdentityAuditEventArgs(AuditEvent.AccountUnlocked, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseForgotPasswordRequestedEvent(int userId)
{
OnForgotPasswordRequested(new IdentityAuditEventArgs(AuditEvent.ForgotPasswordRequested, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseForgotPasswordChangedSuccessEvent(int userId)
{
OnForgotPasswordChangedSuccess(new IdentityAuditEventArgs(AuditEvent.ForgotPasswordChangedSuccess, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseLoginFailedEvent(int userId)
{
OnLoginFailed(new IdentityAuditEventArgs(AuditEvent.LoginFailed, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseInvalidLoginAttemptEvent(string username)
{
OnLoginFailed(new IdentityAuditEventArgs(AuditEvent.LoginFailed, GetCurrentRequestIpAddress(), username, string.Format("Attempted login for username '{0}' failed", username)));
}
internal void RaiseLoginRequiresVerificationEvent(int userId)
{
OnLoginRequiresVerification(new IdentityAuditEventArgs(AuditEvent.LoginRequiresVerification, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseLoginSuccessEvent(int userId)
{
OnLoginSuccess(new IdentityAuditEventArgs(AuditEvent.LoginSucces, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseLogoutSuccessEvent(int userId)
{
OnLogoutSuccess(new IdentityAuditEventArgs(AuditEvent.LogoutSuccess, GetCurrentRequestIpAddress(), userId));
}
internal void RaisePasswordChangedEvent(int userId)
{
OnPasswordChanged(new IdentityAuditEventArgs(AuditEvent.PasswordChanged, GetCurrentRequestIpAddress(), userId));
}
internal void RaisePasswordResetEvent(int userId)
{
OnPasswordReset(new IdentityAuditEventArgs(AuditEvent.PasswordReset, GetCurrentRequestIpAddress(), userId));
}
internal void RaiseResetAccessFailedCountEvent(int userId)
{
OnResetAccessFailedCount(new IdentityAuditEventArgs(AuditEvent.ResetAccessFailedCount, GetCurrentRequestIpAddress(), userId));
}
public static event EventHandler AccountLocked;
public static event EventHandler AccountUnlocked;
public static event EventHandler ForgotPasswordRequested;
public static event EventHandler ForgotPasswordChangedSuccess;
public static event EventHandler LoginFailed;
public static event EventHandler LoginRequiresVerification;
public static event EventHandler LoginSuccess;
public static event EventHandler LogoutSuccess;
public static event EventHandler PasswordChanged;
public static event EventHandler PasswordReset;
public static event EventHandler ResetAccessFailedCount;
protected virtual void OnAccountLocked(IdentityAuditEventArgs e)
{
if (AccountLocked != null) AccountLocked(this, e);
}
protected virtual void OnAccountUnlocked(IdentityAuditEventArgs e)
{
if (AccountUnlocked != null) AccountUnlocked(this, e);
}
protected virtual void OnForgotPasswordRequested(IdentityAuditEventArgs e)
{
if (ForgotPasswordRequested != null) ForgotPasswordRequested(this, e);
}
protected virtual void OnForgotPasswordChangedSuccess(IdentityAuditEventArgs e)
{
if (ForgotPasswordChangedSuccess != null) ForgotPasswordChangedSuccess(this, e);
}
protected virtual void OnLoginFailed(IdentityAuditEventArgs e)
{
if (LoginFailed != null) LoginFailed(this, e);
}
protected virtual void OnLoginRequiresVerification(IdentityAuditEventArgs e)
{
if (LoginRequiresVerification != null) LoginRequiresVerification(this, e);
}
protected virtual void OnLoginSuccess(IdentityAuditEventArgs e)
{
if (LoginSuccess != null) LoginSuccess(this, e);
}
protected virtual void OnLogoutSuccess(IdentityAuditEventArgs e)
{
if (LogoutSuccess != null) LogoutSuccess(this, e);
}
protected virtual void OnPasswordChanged(IdentityAuditEventArgs e)
{
if (PasswordChanged != null) PasswordChanged(this, e);
}
protected virtual void OnPasswordReset(IdentityAuditEventArgs e)
{
if (PasswordReset != null) PasswordReset(this, e);
}
protected virtual void OnResetAccessFailedCount(IdentityAuditEventArgs e)
{
if (ResetAccessFailedCount != null) ResetAccessFailedCount(this, e);
}
/// <summary>
/// Returns the current request IP address for logging if there is one
/// </summary>
/// <returns></returns>
protected virtual string GetCurrentRequestIpAddress()
{
//TODO: inject a service to get this value, we should not be relying on the old HttpContext.Current especially in the ASP.NET Identity world.
var httpContext = HttpContext.Current == null ? (HttpContextBase)null : new HttpContextWrapper(HttpContext.Current);
return httpContext.GetCurrentRequestIpAddress();
}
}
}
@@ -0,0 +1,26 @@
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Umbraco.Core.Serialization
{
public class KnownTypeUdiJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Udi).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jo = JToken.ReadFrom(reader);
var val = jo.ToObject<string>();
return val == null ? null : Udi.Parse(val, true);
}
}
}
@@ -4,12 +4,11 @@ using Newtonsoft.Json.Linq;
namespace Umbraco.Core.Serialization
{
public class UdiJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(Udi).IsAssignableFrom(objectType);
return typeof (Udi).IsAssignableFrom(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+36 -44
View File
@@ -13,13 +13,11 @@ using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
using Umbraco.Core.Scoping;
namespace Umbraco.Core.Services
{
@@ -903,15 +901,43 @@ namespace Umbraco.Core.Services
/// <returns>True if the Content can be published, otherwise False</returns>
public bool IsPublishable(IContent content)
{
//If the passed in content has yet to be saved we "fallback" to checking the Parent
//because if the Parent is publishable then the current content can be Saved and Published
if (content.HasIdentity == false)
int[] ids;
if (content.HasIdentity)
{
var parent = GetById(content.ParentId);
return IsPublishable(parent, true);
// get ids from path (we have identity)
// skip the first one that has to be -1 - and we don't care
// skip the last one that has to be "this" - and it's ok to stop at the parent
ids = content.Path.Split(',').Skip(1).SkipLast().Select(int.Parse).ToArray();
}
else
{
// no path yet (no identity), have to move up to parent
// skip the first one that has to be -1 - and we don't care
// don't skip the last one that is "parent"
var parent = GetById(content.ParentId);
if (parent == null) return false;
ids = parent.Path.Split(',').Skip(1).Select(int.Parse).ToArray();
}
if (ids.Length == 0)
return false;
return IsPublishable(content, false);
// if the first one is recycle bin, fail fast
if (ids[0] == Constants.System.RecycleBinContent)
return false;
// fixme - move to repository?
using (var uow = UowProvider.GetUnitOfWork(readOnly: true))
{
var sql = new Sql(@"
SELECT id
FROM umbracoNode
JOIN cmsDocument ON umbracoNode.id=cmsDocument.nodeId AND cmsDocument.published=@0
WHERE umbracoNode.trashed=@1 AND umbracoNode.id IN (@2)",
true, false, ids);
Console.WriteLine(sql.SQL);
var x = uow.Database.Fetch<int>(sql);
return ids.Length == x.Count;
}
}
/// <summary>
@@ -1062,7 +1088,7 @@ namespace Umbraco.Core.Services
descendant.WriterId = userId;
descendant.ChangeTrashedState(true, descendant.ParentId);
repository.AddOrUpdate(descendant);
moveInfo.Add(new MoveEventInfo<IContent>(descendant, descendant.Path, descendant.ParentId));
}
@@ -2227,7 +2253,7 @@ namespace Umbraco.Core.Services
if (raiseEvents)
{
saveEventArgs.CanCancel = false;
saveEventArgs.CanCancel = false;
uow.Events.Dispatch(Saved, this, saveEventArgs);
}
@@ -2311,40 +2337,6 @@ namespace Umbraco.Core.Services
}
}
/// <summary>
/// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state.
/// </summary>
/// <remarks>
/// Check current is only used when falling back to checking the Parent of non-saved content, as
/// non-saved content doesn't have a valid path yet.
/// </remarks>
/// <param name="content"><see cref="IContent"/> to check if anscestors are published</param>
/// <param name="checkCurrent">Boolean indicating whether the passed in content should also be checked for published versions</param>
/// <returns>True if the Content can be published, otherwise False</returns>
private bool IsPublishable(IContent content, bool checkCurrent)
{
var ids = content.Path.Split(',').Select(int.Parse).ToList();
foreach (var id in ids)
{
//If Id equals that of the recycle bin we return false because nothing in the bin can be published
if (id == Constants.System.RecycleBinContent)
return false;
//We don't check the System Root, so just continue
if (id == Constants.System.Root) continue;
//If the current id equals that of the passed in content and if current shouldn't be checked we skip it.
if (checkCurrent == false && id == content.Id) continue;
//Check if the content for the current id is published - escape the loop if we encounter content that isn't published
var hasPublishedVersion = HasPublishedVersion(id);
if (hasPublishedVersion == false)
return false;
}
return true;
}
private PublishStatusType CheckAndLogIsPublishable(IContent content)
{
//Check if parent is published (although not if its a root node) - if parent isn't published this Content cannot be published
@@ -646,5 +646,34 @@ namespace Umbraco.Core.Services
return exists;
}
}
/// <inheritdoc />
public int ReserveId(Guid key)
{
NodeDto node;
using (var scope = UowProvider.ScopeProvider.CreateScope())
{
var sql = new Sql("SELECT * FROM umbracoNode WHERE uniqueID=@0 AND nodeObjectType=@1", key, Constants.ObjectTypes.IdReservationGuid);
node = scope.Database.SingleOrDefault<NodeDto>(sql);
if (node != null) throw new InvalidOperationException("An identifier has already been reserved for this Udi.");
node = new NodeDto
{
UniqueId = key,
Text = "RESERVED.ID",
NodeObjectType = Constants.ObjectTypes.IdReservationGuid,
CreateDate = DateTime.Now,
UserId = 0,
ParentId = -1,
Level = 1,
Path = "-1",
SortOrder = 0,
Trashed = false
};
scope.Database.Insert(node);
scope.Complete();
}
return node.NodeId;
}
}
}
+9 -1
View File
@@ -170,7 +170,7 @@ namespace Umbraco.Core.Services
/// <param name="totalRecords"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="filter"></param>
/// <param name="filter"></param>
/// <returns></returns>
IEnumerable<IUmbracoEntity> GetPagedDescendants(int id, UmbracoObjectTypes umbracoObjectType, long pageIndex, int pageSize, out long totalRecords,
string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = "");
@@ -270,5 +270,13 @@ namespace Umbraco.Core.Services
/// <param name="umbracoObjectType"><see cref="UmbracoObjectTypes"/></param>
/// <returns>Type of the entity</returns>
Type GetEntityType(UmbracoObjectTypes umbracoObjectType);
/// <summary>
/// Reserves an identifier for a key.
/// </summary>
/// <param name="key">They key.</param>
/// <returns>The identifier.</returns>
/// <remarks>When a new content or a media is saved with the key, it will have the reserved identifier.</remarks>
int ReserveId(Guid key);
}
}
+8
View File
@@ -46,6 +46,10 @@ namespace Umbraco.Core.Services
if (val == null) return Attempt<int>.Fail();
// cache reservations, when something is saved this cache is cleared anyways
//if (umbracoObjectType == UmbracoObjectTypes.IdReservation)
// Attempt.Succeed(val.Value);
try
{
_locker.EnterWriteLock();
@@ -95,6 +99,10 @@ namespace Umbraco.Core.Services
if (val == null) return Attempt<Guid>.Fail();
// cache reservations, when something is saved this cache is cleared anyways
//if (umbracoObjectType == UmbracoObjectTypes.IdReservation)
// Attempt.Succeed(val.Value);
try
{
_locker.EnterWriteLock();
+6 -6
View File
@@ -57,17 +57,18 @@ namespace Umbraco.Core
public new static StringUdi Parse(string s)
{
var udi = Udi.Parse(s);
if (!(udi is StringUdi))
if (udi is StringUdi == false)
throw new FormatException("String \"" + s + "\" is not a string entity id.");
return (StringUdi)udi;
return (StringUdi) udi;
}
public static bool TryParse(string s, out StringUdi udi)
{
udi = null;
Udi tmp;
if (!TryParse(s, out tmp) || !(tmp is StringUdi)) return false;
udi = (StringUdi)tmp;
if (TryParse(s, out tmp) == false || tmp is StringUdi == false) return false;
udi = (StringUdi) tmp;
return true;
}
@@ -77,10 +78,9 @@ namespace Umbraco.Core
get { return Id == string.Empty; }
}
/// <inheritdoc/>
public StringUdi EnsureClosed()
{
base.EnsureNotRoot();
EnsureNotRoot();
return this;
}
}
+153 -58
View File
@@ -3,7 +3,6 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Umbraco.Core.Deploy;
namespace Umbraco.Core
@@ -15,7 +14,15 @@ namespace Umbraco.Core
[TypeConverter(typeof(UdiTypeConverter))]
public abstract class Udi : IComparable<Udi>
{
private static readonly Lazy<Dictionary<string, UdiType>> UdiTypes;
// notes - see U4-10409
// if this class is used during application pre-start it cannot scans the assemblies,
// this is addressed by lazily-scanning, with the following caveats:
// - parsing a root udi still requires a scan and therefore still breaks
// - parsing an invalid udi ("umb://should-be-guid/<not-a-guid>") corrupts KnowUdiTypes
private static volatile bool _scanned;
private static readonly object ScanLocker = new object();
private static ConcurrentDictionary<string, UdiType> _udiTypes;
private static readonly ConcurrentDictionary<string, Udi> RootUdis = new ConcurrentDictionary<string, Udi>();
internal readonly Uri UriValue; // internal for UdiRange
@@ -42,50 +49,16 @@ namespace Umbraco.Core
static Udi()
{
UdiTypes = new Lazy<Dictionary<string, UdiType>>(() =>
{
var result = new Dictionary<string, UdiType>();
// known types:
foreach (var fi in typeof(Constants.UdiEntityType).GetFields(BindingFlags.Public | BindingFlags.Static))
{
// IsLiteral determines if its value is written at
// compile time and not changeable
// IsInitOnly determine if the field can be set
// in the body of the constructor
// for C# a field which is readonly keyword would have both true
// but a const field would have only IsLiteral equal to true
if (fi.IsLiteral && fi.IsInitOnly == false)
{
var udiType = fi.GetCustomAttribute<Constants.UdiTypeAttribute>();
// initialize with known (built-in) Udi types
// we will add scanned types later on
_udiTypes = new ConcurrentDictionary<string, UdiType>(Constants.UdiEntityType.GetTypes());
}
if (udiType == null)
throw new InvalidOperationException("All Constants listed in UdiEntityType must be attributed with " + typeof(Constants.UdiTypeAttribute));
result[fi.GetValue(null).ToString()] = udiType.UdiType;
}
}
// Scan for unknown UDI types
// there is no way we can get the "registered" service connectors, as registration
// happens in Deploy, not in Core, and the Udi class belongs to Core - therefore, we
// just pick every service connectors - just making sure that not two of them
// would register the same entity type, with different udi types (would not make
// much sense anyways).
var connectors = PluginManager.Current.ResolveTypes<IServiceConnector>();
foreach (var connector in connectors)
{
var attrs = connector.GetCustomAttributes<UdiDefinitionAttribute>(false);
foreach (var attr in attrs)
{
UdiType udiType;
if (result.TryGetValue(attr.EntityType, out udiType) && udiType != attr.UdiType)
throw new Exception(string.Format("Entity type \"{0}\" is declared by more than one IServiceConnector, with different UdiTypes.", attr.EntityType));
result[attr.EntityType] = attr.UdiType;
}
}
return result;
});
// for tests, totally unsafe
internal static void ResetUdiTypes()
{
_udiTypes = new ConcurrentDictionary<string, UdiType>(Constants.UdiEntityType.GetTypes());
_scanned = false;
}
/// <summary>
@@ -113,17 +86,65 @@ namespace Umbraco.Core
public static Udi Parse(string s)
{
Udi udi;
ParseInternal(s, false, out udi);
ParseInternal(s, false, false, out udi);
return udi;
}
public static bool TryParse(string s, out Udi udi)
/// <summary>
/// Converts the string representation of an entity identifier into the equivalent Udi instance.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <param name="knownTypes">A value indicating whether to only deal with known types.</param>
/// <returns>An Udi instance that contains the value that was parsed.</returns>
/// <remarks>
/// <para>If <paramref name="knownTypes"/> is <c>true</c>, and the string could not be parsed because
/// the entity type was not known, the method succeeds but sets <c>udi</c>to an
/// <see cref="UnknownTypeUdi"/> value.</para>
/// <para>If <paramref name="knownTypes"/> is <c>true</c>, assemblies are not scanned for types,
/// and therefore only builtin types may be known. Unless scanning already took place.</para>
/// </remarks>
public static Udi Parse(string s, bool knownTypes)
{
return ParseInternal(s, true, out udi);
Udi udi;
ParseInternal(s, false, knownTypes, out udi);
return udi;
}
private static bool ParseInternal(string s, bool tryParse, out Udi udi)
/// <summary>
/// Converts the string representation of an entity identifier into the equivalent Udi instance.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <param name="udi">An Udi instance that contains the value that was parsed.</param>
/// <returns>A boolean value indicating whether the string could be parsed.</returns>
public static bool TryParse(string s, out Udi udi)
{
return ParseInternal(s, true, false, out udi);
}
/// <summary>
/// Converts the string representation of an entity identifier into the equivalent Udi instance.
/// </summary>
/// <param name="s">The string to convert.</param>
/// <param name="knownTypes">A value indicating whether to only deal with known types.</param>
/// <param name="udi">An Udi instance that contains the value that was parsed.</param>
/// <returns>A boolean value indicating whether the string could be parsed.</returns>
/// <remarks>
/// <para>If <paramref name="knownTypes"/> is <c>true</c>, and the string could not be parsed because
/// the entity type was not known, the method returns <c>false</c> but still sets <c>udi</c>
/// to an <see cref="UnknownTypeUdi"/> value.</para>
/// <para>If <paramref name="knownTypes"/> is <c>true</c>, assemblies are not scanned for types,
/// and therefore only builtin types may be known. Unless scanning already took place.</para>
/// </remarks>
public static bool TryParse(string s, bool knownTypes, out Udi udi)
{
return ParseInternal(s, true, knownTypes, out udi);
}
private static bool ParseInternal(string s, bool tryParse, bool knownTypes, out Udi udi)
{
if (knownTypes == false)
EnsureScanForUdiTypes();
udi = null;
Uri uri;
@@ -136,12 +157,21 @@ namespace Umbraco.Core
var entityType = uri.Host;
UdiType udiType;
if (UdiTypes.Value.TryGetValue(entityType, out udiType) == false)
if (_udiTypes.TryGetValue(entityType, out udiType) == false)
{
if (knownTypes)
{
// not knowing the type is not an error
// just return the unknown type udi
udi = UnknownTypeUdi.Instance;
return false;
}
if (tryParse) return false;
throw new FormatException(string.Format("Unknown entity type \"{0}\".", entityType));
}
var path = uri.AbsolutePath.TrimStart('/');
if (udiType == UdiType.GuidUdi)
{
if (path == string.Empty)
@@ -158,21 +188,25 @@ namespace Umbraco.Core
udi = new GuidUdi(uri.Host, guid);
return true;
}
if (udiType == UdiType.StringUdi)
{
udi = path == string.Empty ? GetRootUdi(uri.Host) : new StringUdi(uri.Host, Uri.UnescapeDataString(path));
return true;
}
if (tryParse) return false;
throw new InvalidOperationException("Internal error.");
throw new InvalidOperationException(string.Format("Invalid udi type \"{0}\".", udiType));
}
private static Udi GetRootUdi(string entityType)
{
EnsureScanForUdiTypes();
return RootUdis.GetOrAdd(entityType, x =>
{
UdiType udiType;
if (UdiTypes.Value.TryGetValue(x, out udiType) == false)
if (_udiTypes.TryGetValue(x, out udiType) == false)
throw new ArgumentException(string.Format("Unknown entity type \"{0}\".", entityType));
return udiType == UdiType.StringUdi
? (Udi)new StringUdi(entityType, string.Empty)
@@ -180,6 +214,46 @@ namespace Umbraco.Core
});
}
/// <summary>
/// When required scan assemblies for known UDI types based on <see cref="IServiceConnector"/> instances
/// </summary>
/// <remarks>
/// This is only required when needing to resolve root udis
/// </remarks>
private static void EnsureScanForUdiTypes()
{
if (_scanned) return;
lock (ScanLocker)
{
// Scan for unknown UDI types
// there is no way we can get the "registered" service connectors, as registration
// happens in Deploy, not in Core, and the Udi class belongs to Core - therefore, we
// just pick every service connectors - just making sure that not two of them
// would register the same entity type, with different udi types (would not make
// much sense anyways).
var connectors = PluginManager.Current.ResolveTypes<IServiceConnector>();
var result = new Dictionary<string, UdiType>();
foreach (var connector in connectors)
{
var attrs = connector.GetCustomAttributes<UdiDefinitionAttribute>(false);
foreach (var attr in attrs)
{
UdiType udiType;
if (result.TryGetValue(attr.EntityType, out udiType) && udiType != attr.UdiType)
throw new Exception(string.Format("Entity type \"{0}\" is declared by more than one IServiceConnector, with different UdiTypes.", attr.EntityType));
result[attr.EntityType] = attr.UdiType;
}
}
// merge these into the known list
foreach (var item in result)
_udiTypes.TryAdd(item.Key, item.Value);
_scanned = true;
}
}
/// <summary>
/// Creates a root Udi for an entity type.
/// </summary>
@@ -199,13 +273,14 @@ namespace Umbraco.Core
public static Udi Create(string entityType, string id)
{
UdiType udiType;
if (UdiTypes.Value.TryGetValue(entityType, out udiType) == false)
if (_udiTypes.TryGetValue(entityType, out udiType) == false)
throw new ArgumentException(string.Format("Unknown entity type \"{0}\".", entityType), "entityType");
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentException("Value cannot be null or whitespace.", "id");
if (udiType != UdiType.StringUdi)
throw new InvalidOperationException(string.Format("Entity type \"{0}\" does not have string udis.", entityType));
return new StringUdi(entityType, id);
}
@@ -218,24 +293,31 @@ namespace Umbraco.Core
public static Udi Create(string entityType, Guid id)
{
UdiType udiType;
if (UdiTypes.Value.TryGetValue(entityType, out udiType) == false)
if (_udiTypes.TryGetValue(entityType, out udiType) == false)
throw new ArgumentException(string.Format("Unknown entity type \"{0}\".", entityType), "entityType");
if (udiType != UdiType.GuidUdi)
throw new InvalidOperationException(string.Format("Entity type \"{0}\" does not have guid udis.", entityType));
throw new InvalidOperationException(string.Format("Entity type \"{0}\" does not have guid udis.", entityType));
if (id == default(Guid))
throw new ArgumentException("Cannot be an empty guid.", "id");
return new GuidUdi(entityType, id);
}
internal static Udi Create(Uri uri)
{
// if it's a know type go fast and use ctors
// else fallback to parsing the string (and guess the type)
UdiType udiType;
if (UdiTypes.Value.TryGetValue(uri.Host, out udiType) == false)
if (_udiTypes.TryGetValue(uri.Host, out udiType) == false)
throw new ArgumentException(string.Format("Unknown entity type \"{0}\".", uri.Host), "uri");
if (udiType == UdiType.GuidUdi)
return new GuidUdi(uri);
if (udiType == UdiType.GuidUdi)
return new StringUdi(uri);
throw new ArgumentException(string.Format("Uri \"{0}\" is not a valid udi.", uri));
}
@@ -284,6 +366,19 @@ namespace Umbraco.Core
{
return (udi1 == udi2) == false;
}
}
private class UnknownTypeUdi : Udi
{
private UnknownTypeUdi()
: base("unknown", "umb://unknown/")
{ }
public static readonly UnknownTypeUdi Instance = new UnknownTypeUdi();
public override bool IsRoot
{
get { return false; }
}
}
}
}
+46 -43
View File
@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using Umbraco.Core.Models;
namespace Umbraco.Core
{
public static partial class Constants
{
/// <summary>
@@ -13,81 +13,95 @@ namespace Umbraco.Core
/// but entity types are strings and so can be extended beyond what is defined here.</remarks>
public static class UdiEntityType
{
[UdiType(UdiType.Unknown)]
// note: const fields in this class MUST be consistent with what GetTypes returns
// this is validated by UdiTests.ValidateUdiEntityType
// also, this is used exclusively in Udi static ctor, only once, so there is no
// need to keep it around in a field nor to make it readonly
internal static Dictionary<string, UdiType> GetTypes()
{
return new Dictionary<string,UdiType>
{
{ Unknown, UdiType.Unknown },
{ AnyGuid, UdiType.GuidUdi },
{ Document, UdiType.GuidUdi },
{ Media, UdiType.GuidUdi },
{ Member, UdiType.GuidUdi },
{ DictionaryItem, UdiType.GuidUdi },
{ Macro, UdiType.GuidUdi },
{ Template, UdiType.GuidUdi },
{ DocumentType, UdiType.GuidUdi },
{ DocumentTypeContainer, UdiType.GuidUdi },
{ MediaType, UdiType.GuidUdi },
{ MediaTypeContainer, UdiType.GuidUdi },
{ DataType, UdiType.GuidUdi },
{ DataTypeContainer, UdiType.GuidUdi },
{ MemberType, UdiType.GuidUdi },
{ MemberGroup, UdiType.GuidUdi },
{ RelationType, UdiType.GuidUdi },
{ FormsForm, UdiType.GuidUdi },
{ FormsPreValue, UdiType.GuidUdi },
{ FormsDataSource, UdiType.GuidUdi },
{ AnyString, UdiType.StringUdi},
{ Language, UdiType.StringUdi},
{ MacroScript, UdiType.StringUdi},
{ MediaFile, UdiType.StringUdi},
{ TemplateFile, UdiType.StringUdi},
{ Script, UdiType.StringUdi},
{ PartialView, UdiType.StringUdi},
{ PartialViewMacro, UdiType.StringUdi},
{ Stylesheet, UdiType.StringUdi},
{ UserControl, UdiType.StringUdi},
{ Xslt, UdiType.StringUdi},
};
}
public const string Unknown = "unknown";
// guid entity types
[UdiType(UdiType.GuidUdi)]
public const string AnyGuid = "any-guid"; // that one is for tests
[UdiType(UdiType.GuidUdi)]
public const string Document = "document";
[UdiType(UdiType.GuidUdi)]
public const string Media = "media";
[UdiType(UdiType.GuidUdi)]
public const string Member = "member";
[UdiType(UdiType.GuidUdi)]
public const string DictionaryItem = "dictionary-item";
[UdiType(UdiType.GuidUdi)]
public const string Macro = "macro";
[UdiType(UdiType.GuidUdi)]
public const string Template = "template";
[UdiType(UdiType.GuidUdi)]
public const string DocumentType = "document-type";
[UdiType(UdiType.GuidUdi)]
public const string DocumentTypeContainer = "document-type-container";
[UdiType(UdiType.GuidUdi)]
public const string MediaType = "media-type";
[UdiType(UdiType.GuidUdi)]
public const string MediaTypeContainer = "media-type-container";
[UdiType(UdiType.GuidUdi)]
public const string DataType = "data-type";
[UdiType(UdiType.GuidUdi)]
public const string DataTypeContainer = "data-type-container";
[UdiType(UdiType.GuidUdi)]
public const string MemberType = "member-type";
[UdiType(UdiType.GuidUdi)]
public const string MemberGroup = "member-group";
[UdiType(UdiType.GuidUdi)]
public const string RelationType = "relation-type";
// forms
[UdiType(UdiType.GuidUdi)]
public const string FormsForm = "forms-form";
[UdiType(UdiType.GuidUdi)]
public const string FormsPreValue = "forms-prevalue";
[UdiType(UdiType.GuidUdi)]
public const string FormsDataSource = "forms-datasource";
// string entity types
[UdiType(UdiType.StringUdi)]
public const string AnyString = "any-string"; // that one is for tests
[UdiType(UdiType.StringUdi)]
public const string Language = "language";
[UdiType(UdiType.StringUdi)]
public const string MacroScript = "macroscript";
[UdiType(UdiType.StringUdi)]
public const string MediaFile = "media-file";
[UdiType(UdiType.StringUdi)]
public const string TemplateFile = "template-file";
[UdiType(UdiType.StringUdi)]
public const string Script = "script";
[UdiType(UdiType.StringUdi)]
public const string Stylesheet = "stylesheet";
[UdiType(UdiType.StringUdi)]
public const string PartialView = "partial-view";
[UdiType(UdiType.StringUdi)]
public const string PartialViewMacro = "partial-view-macro";
[UdiType(UdiType.StringUdi)]
public const string UserControl = "usercontrol";
[UdiType(UdiType.StringUdi)]
public const string Xslt = "xslt";
public static string FromUmbracoObjectType(UmbracoObjectTypes umbracoObjectType)
@@ -179,16 +193,5 @@ namespace Umbraco.Core
string.Format("EntityType \"{0}\" does not have a matching UmbracoObjectType.", entityType));
}
}
[AttributeUsage(AttributeTargets.Field)]
internal class UdiTypeAttribute : Attribute
{
public UdiType UdiType { get; private set; }
public UdiTypeAttribute(UdiType udiType)
{
UdiType = udiType;
}
}
}
}
+2 -2
View File
@@ -62,8 +62,8 @@ namespace Umbraco.Core
{
Uri uri;
if (!Uri.IsWellFormedUriString(s, UriKind.Absolute)
|| !Uri.TryCreate(s, UriKind.Absolute, out uri))
if (Uri.IsWellFormedUriString(s, UriKind.Absolute) == false
|| Uri.TryCreate(s, UriKind.Absolute, out uri) == false)
{
//if (tryParse) return false;
throw new FormatException(string.Format("String \"{0}\" is not a valid udi range.", s));
+6 -1
View File
@@ -45,6 +45,9 @@
<HintPath>..\packages\AutoMapper.3.3.1\lib\net40\AutoMapper.Net4.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="ClientDependency.Core, Version=1.9.2.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\ClientDependency.1.9.2\lib\net45\ClientDependency.Core.dll</HintPath>
</Reference>
<Reference Include="HtmlAgilityPack, Version=1.4.9.5, Culture=neutral, PublicKeyToken=bd319b19eaf3b43a, processorArchitecture=MSIL">
<HintPath>..\packages\HtmlAgilityPack.1.4.9.5\lib\Net45\HtmlAgilityPack.dll</HintPath>
<Private>True</Private>
@@ -148,6 +151,7 @@
<Compile Include="Attempt{T}.cs" />
<Compile Include="Auditing\Audit.cs" />
<Compile Include="Auditing\AuditTypes.cs" />
<Compile Include="Auditing\IdentityAuditEventArgs.cs" />
<Compile Include="BindingRedirects.cs" />
<Compile Include="ByteArrayExtensions.cs" />
<Compile Include="CacheHelper.cs" />
@@ -496,6 +500,7 @@
<Compile Include="Persistence\Factories\PublicAccessEntryFactory.cs" />
<Compile Include="Persistence\Factories\TaskFactory.cs" />
<Compile Include="Persistence\Factories\TaskTypeFactory.cs" />
<Compile Include="Persistence\LocalDb.cs" />
<Compile Include="Persistence\LockedRepository.cs" />
<Compile Include="Persistence\LockingRepository.cs" />
<Compile Include="Persistence\Mappers\AccessMapper.cs" />
@@ -640,6 +645,7 @@
<Compile Include="Security\EmailService.cs" />
<Compile Include="Security\OwinExtensions.cs" />
<Compile Include="SemVersionExtensions.cs" />
<Compile Include="Serialization\KnownTypeUdiJsonConverter.cs" />
<Compile Include="Serialization\NoTypeConverterJsonConverter.cs" />
<Compile Include="Serialization\StreamResultExtensions.cs" />
<Compile Include="Serialization\UdiJsonConverter.cs" />
@@ -1581,7 +1587,6 @@
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<Import Project="..\packages\AutoMapper.3.3.1\tools\AutoMapper.targets" Condition="Exists('..\packages\AutoMapper.3.3.1\tools\AutoMapper.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -60,7 +60,7 @@ namespace Umbraco.Core.Xml
return -1;
});
const string rootXpath = "descendant::*[@id={0}]";
const string rootXpath = "id({0})";
//parseable items:
var vars = new Dictionary<string, Func<string, string>>();
+1
View File
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AutoMapper" version="3.3.1" targetFramework="net45" />
<package id="ClientDependency" version="1.9.2" targetFramework="net45" />
<package id="HtmlAgilityPack" version="1.4.9.5" targetFramework="net45" />
<package id="ImageProcessor" version="2.5.3" targetFramework="net45" />
<package id="log4net" version="2.0.8" targetFramework="net45" />
+74 -28
View File
@@ -12,6 +12,17 @@ namespace Umbraco.Tests.Dependencies
[TestFixture]
public class NuGet
{
// note
// these tests assume that the test suite runs from the project's ~/bin directory
// instead, we want to be able to pass the required paths as parameters
// NUnit 3.x supports TestContext.TestParameters, alas we are still running 2.x
//
// so instead
//
// furthermore, all these tests should be parts of the build and fail the build
// in case the NuGet things are not consisted. Also, v8 uses <PackageReference>
// wherever possible so we will also have to deal with it eventually.
[Test]
public void NuGet_Package_Versions_Are_The_Same_In_All_Package_Config_Files()
{
@@ -40,21 +51,20 @@ namespace Umbraco.Tests.Dependencies
[Test]
public void NuSpec_File_Matches_Installed_Dependencies()
{
var solutionDirectory = GetSolutionDirectory();
Assert.NotNull(solutionDirectory);
Assert.NotNull(solutionDirectory.Parent);
var nuSpecPath = solutionDirectory.Parent.FullName + "\\build\\NuSpecs\\";
Assert.IsTrue(Directory.Exists(nuSpecPath));
var nuspecsDirectory = NuSpecsDirectory;
Assert.IsNotNull(nuspecsDirectory);
var packagesAndVersions = GetNuGetPackagesInSolution();
var failTest = false;
Assert.IsTrue(packagesAndVersions.Any());
var nuSpecFiles = Directory.GetFiles(nuSpecPath);
foreach (var fileName in nuSpecFiles.Where(x => x.EndsWith("nuspec")))
Console.WriteLine("NuSpecs: " + nuspecsDirectory.FullName);
var failTest = false;
var nuspecFiles = nuspecsDirectory.GetFiles().Where(x => x.Extension == ".nuspec").Select(x => x.FullName);
foreach (var filename in nuspecFiles)
{
var serializer = new XmlSerializer(typeof(NuSpec));
using (var reader = new StreamReader(fileName))
using (var reader = new StreamReader(filename))
{
var nuspec = (NuSpec)serializer.Deserialize(reader);
var dependencies = nuspec.MetaData.dependencies;
@@ -64,13 +74,13 @@ namespace Umbraco.Tests.Dependencies
{
var dependencyVersionRange = dependency.Version.Replace("[", string.Empty).Replace("(", string.Empty).Split(',');
var dependencyMinimumVersion = dependencyVersionRange.First().Trim();
var matchingPackages = packagesAndVersions.Where(x => string.Equals(x.PackageName, dependency.Id,
StringComparison.InvariantCultureIgnoreCase)).ToList();
if (matchingPackages.Any() == false)
continue;
// NuGet_Package_Versions_Are_The_Same_In_All_Package_Config_Files test
// NuGet_Package_Versions_Are_The_Same_In_All_Package_Config_Files test
// guarantees that all packages have one version, solutionwide, so it's okay to take First() here
if (dependencyMinimumVersion != matchingPackages.First().PackageVersion)
{
@@ -88,13 +98,12 @@ namespace Umbraco.Tests.Dependencies
private List<PackageVersionMatcher> GetNuGetPackagesInSolution()
{
var packagesAndVersions = new List<PackageVersionMatcher>();
var solutionDirectory = GetSolutionDirectory();
if (solutionDirectory == null)
return packagesAndVersions;
var sourceDirectory = SourceDirectory;
if (sourceDirectory == null) return packagesAndVersions;
var packageConfigFiles = new List<FileInfo>();
var packageDirectories =
solutionDirectory.GetDirectories().Where(x =>
sourceDirectory.GetDirectories().Where(x =>
x.Name.StartsWith("Umbraco.Tests") == false &&
x.Name.StartsWith("Umbraco.MSBuild.Tasks") == false).ToArray();
@@ -123,15 +132,53 @@ namespace Umbraco.Tests.Dependencies
return packagesAndVersions;
}
private DirectoryInfo GetSolutionDirectory()
private DirectoryInfo SourceDirectory
{
var testsDirectory = new FileInfo(TestHelper.MapPathForTest("~/"));
if (testsDirectory.Directory == null)
return null;
if (testsDirectory.Directory.Parent == null || testsDirectory.Directory.Parent.Parent == null)
return null;
var solutionDirectory = testsDirectory.Directory.Parent.Parent.Parent;
return solutionDirectory;
get
{
// UMBRACO_TMP is set by VSTS and points to build.tmp
var tmp = Environment.GetEnvironmentVariable("UMBRACO_TMP");
if (tmp == null) return SolutionDirectory;
var path = Path.Combine(tmp, "..\\src");
path = Path.GetFullPath(path); // sanitize
var dir = new DirectoryInfo(path);
return dir.Exists ? dir : null;
}
}
private DirectoryInfo NuSpecsDirectory
{
get
{
// UMBRACO_TMP is set by VSTS and points to build.tmp
var tmp = Environment.GetEnvironmentVariable("UMBRACO_TMP");
if (tmp == null)
{
var solutionDirectory = SolutionDirectory;
if (solutionDirectory == null) return null;
return new DirectoryInfo(Path.Combine(solutionDirectory.FullName, "..\\build\\NuSpecs"));
}
var path = Path.Combine(tmp, "..\\build\\NuSpecs");
path = Path.GetFullPath(path); // sanitize
var dir = new DirectoryInfo(path);
return dir.Exists ? dir : null;
}
}
private DirectoryInfo SolutionDirectory
{
get
{
var testsDirectory = new FileInfo(TestHelper.MapPathForTest("~/"));
if (testsDirectory.Directory == null)
return null;
if (testsDirectory.Directory.Parent == null || testsDirectory.Directory.Parent.Parent == null)
return null;
var solutionDirectory = testsDirectory.Directory.Parent.Parent.Parent;
return solutionDirectory;
}
}
}
@@ -159,7 +206,7 @@ namespace Umbraco.Tests.Dependencies
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd")]
[XmlRoot(Namespace = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd", IsNullable = false, ElementName = "package")]
@@ -168,7 +215,7 @@ namespace Umbraco.Tests.Dependencies
[XmlElement("metadata")]
public Metadata MetaData { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd", TypeName = "metadata")]
public class Metadata
{
@@ -182,9 +229,8 @@ namespace Umbraco.Tests.Dependencies
{
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
}
}
@@ -21,6 +21,21 @@ namespace Umbraco.Tests.FrontEnd
Assert.AreEqual("Hello world, this is some&hellip;", result);
}
/// <summary>
/// If a truncated string ends with a space, we should trim the space before appending the ellipsis.
/// </summary>
[Test]
public void Truncate_Simple_With_Trimming()
{
var text = "Hello world, this is some text <a href='blah'>with a link</a>";
var helper = new UmbracoHelper();
var result = helper.Truncate(text, 26).ToString();
Assert.AreEqual("Hello world, this is some&hellip;", result);
}
[Test]
public void Truncate_Inside_Word()
{
@@ -78,5 +93,79 @@ namespace Umbraco.Tests.FrontEnd
Assert.AreEqual(expectedResult, result);
}
[Test]
public void Truncate_By_Words()
{
var text = "Hello world, this is some text <a href='blah'>with a link</a>";
var helper = new UmbracoHelper();
var result = helper.TruncateByWords(text, 4).ToString();
Assert.AreEqual("Hello world, this is&hellip;", result);
}
[Test]
public void Truncate_By_Words_With_Tag()
{
var text = "Hello world, <b>this</b> is some text <a href='blah'>with a link</a>";
var helper = new UmbracoHelper();
var result = helper.TruncateByWords(text, 4).ToString();
Assert.AreEqual("Hello world, <b>this</b> is&hellip;", result);
}
[Test]
public void Truncate_By_Words_Mid_Tag()
{
var text = "Hello world, this is some text <a href='blah'>with a link</a>";
var helper = new UmbracoHelper();
var result = helper.TruncateByWords(text, 7).ToString();
Assert.AreEqual("Hello world, this is some text <a href='blah'>with&hellip;</a>", result);
}
[Test]
public void Strip_All_Html()
{
var text = "Hello world, <b>this</b> is some text <a href='blah'>with a link</a>";
var helper = new UmbracoHelper();
var result = helper.StripHtml(text, null).ToString();
Assert.AreEqual("Hello world, this is some text with a link", result);
}
[Test]
public void Strip_Specific_Html()
{
var text = "Hello world, <b>this</b> is some text <a href='blah'>with a link</a>";
string [] tags = {"b"};
var helper = new UmbracoHelper();
var result = helper.StripHtml(text, tags).ToString();
Assert.AreEqual("Hello world, this is some text <a href='blah'>with a link</a>", result);
}
[Test]
public void Strip_Invalid_Html()
{
var text = "Hello world, <bthis</b> is some text <a href='blah'>with a link</a>";
var helper = new UmbracoHelper();
var result = helper.StripHtml(text).ToString();
Assert.AreEqual("Hello world, is some text with a link", result);
}
}
}
@@ -1,70 +1,146 @@
using System;
using System.Configuration;
using NUnit.Framework;
using Umbraco.Core.Models;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
using Umbraco.Web.Routing;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.template;
namespace Umbraco.Tests.Routing
{
[TestFixture]
public class ContentFinderByNiceUrlTests : BaseRoutingTest
{
[TestFixture]
public class ContentFinderByNiceUrlTests : BaseRoutingTest
{
[TestCase("/", 1046)]
[TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' !
[TestCase("/Sub1", 1173)]
[TestCase("/sub1", 1173)]
[TestCase("/sub1.aspx", 1173)]
[TestCase("/home/sub1", -1)] // should fail
// these two are special. getNiceUrl(1046) returns "/" but getNiceUrl(1172) cannot also return "/" so
// we've made it return "/test-page" => we have to support that url back in the lookup...
[TestCase("/home", 1046)]
[TestCase("/test-page", 1172)]
public void Match_Document_By_Url_Hide_Top_Level(string urlString, int expectedId)
{
var routingContext = GetRoutingContext(urlString);
var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
var docreq = new PublishedContentRequest(url, routingContext);
var lookup = new ContentFinderByNiceUrl();
SettingsForTests.HideTopLevelNodeFromPath = true;
var result = lookup.TryFindContent(docreq);
[TestCase("/", 1046)]
[TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' !
[TestCase("/Sub1", 1173)]
[TestCase("/sub1", 1173)]
[TestCase("/sub1.aspx", 1173)]
[TestCase("/home/sub1", -1)] // should fail
if (expectedId > 0)
{
Assert.IsTrue(result);
Assert.AreEqual(expectedId, docreq.PublishedContent.Id);
}
else
{
Assert.IsFalse(result);
}
}
// these two are special. getNiceUrl(1046) returns "/" but getNiceUrl(1172) cannot also return "/" so
// we've made it return "/test-page" => we have to support that url back in the lookup...
[TestCase("/home", 1046)]
[TestCase("/test-page", 1172)]
public void Match_Document_By_Url_Hide_Top_Level(string urlString, int expectedId)
{
var routingContext = GetRoutingContext(urlString);
var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
var docreq = new PublishedContentRequest(url, routingContext);
var lookup = new ContentFinderByNiceUrl();
SettingsForTests.HideTopLevelNodeFromPath = true;
[TestCase("/", 1046)]
[TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' !
[TestCase("/home", 1046)]
[TestCase("/home/Sub1", 1173)]
[TestCase("/Home/Sub1", 1173)] //different cases
[TestCase("/home/Sub1.aspx", 1173)]
public void Match_Document_By_Url(string urlString, int expectedId)
{
var routingContext = GetRoutingContext(urlString);
var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
var docreq = new PublishedContentRequest(url, routingContext);
var lookup = new ContentFinderByNiceUrl();
var result = lookup.TryFindContent(docreq);
if (expectedId > 0)
{
Assert.IsTrue(result);
Assert.AreEqual(expectedId, docreq.PublishedContent.Id);
}
else
{
Assert.IsFalse(result);
}
}
[TestCase("/", 1046)]
[TestCase("/default.aspx", 1046)] //this one is actually rather important since this is the path that comes through when we are running in pre-IIS 7 for the root document '/' !
[TestCase("/home", 1046)]
[TestCase("/home/Sub1", 1173)]
[TestCase("/Home/Sub1", 1173)] //different cases
[TestCase("/home/Sub1.aspx", 1173)]
public void Match_Document_By_Url(string urlString, int expectedId)
{
var routingContext = GetRoutingContext(urlString);
var url = routingContext.UmbracoContext.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
var docreq = new PublishedContentRequest(url, routingContext);
var lookup = new ContentFinderByNiceUrl();
SettingsForTests.HideTopLevelNodeFromPath = false;
var result = lookup.TryFindContent(docreq);
var result = lookup.TryFindContent(docreq);
Assert.IsTrue(result);
Assert.AreEqual(expectedId, docreq.PublishedContent.Id);
}
Assert.IsTrue(result);
Assert.AreEqual(expectedId, docreq.PublishedContent.Id);
}
/// <summary>
/// This test handles requests with special characters in the URL.
/// </summary>
/// <param name="urlString"></param>
/// <param name="expectedId"></param>
[TestCase("/", 1046)]
[TestCase("/home/sub1/custom-sub-3-with-accént-character", 1179)]
[TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)]
public void Match_Document_By_Url_With_Special_Characters(string urlString, int expectedId)
{
var routingContext = GetRoutingContext(urlString);
var url = routingContext.UmbracoContext
.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
var docreq = new PublishedContentRequest(url, routingContext);
var lookup = new ContentFinderByNiceUrl();
SettingsForTests.HideTopLevelNodeFromPath = false;
}
var result = lookup.TryFindContent(docreq);
Assert.IsTrue(result);
Assert.AreEqual(expectedId, docreq.PublishedContent.Id);
}
/// <summary>
/// This test handles requests with a hostname associated.
/// The logic for handling this goes through the DomainHelper and is a bit different
/// from what happens in a normal request - so it has a separate test with a mocked
/// hostname added.
/// </summary>
/// <param name="urlString"></param>
/// <param name="expectedId"></param>
[TestCase("/", 1046)]
[TestCase("/home/sub1/custom-sub-3-with-accént-character", 1179)]
[TestCase("/home/sub1/custom-sub-4-with-æøå", 1180)]
public void Match_Document_By_Url_With_Special_Characters_Using_Hostname(string urlString, int expectedId)
{
var routingContext = GetRoutingContext(urlString);
var url = routingContext.UmbracoContext
.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
var docreq = new PublishedContentRequest(url, routingContext);
docreq.UmbracoDomain = new UmbracoDomain("mysite");
docreq.DomainUri = new Uri("http://mysite/");
var lookup = new ContentFinderByNiceUrl();
SettingsForTests.HideTopLevelNodeFromPath = false;
var result = lookup.TryFindContent(docreq);
Assert.IsTrue(result);
Assert.AreEqual(expectedId, docreq.PublishedContent.Id);
}
/// <summary>
/// This test handles requests with a hostname with special characters associated.
/// The logic for handling this goes through the DomainHelper and is a bit different
/// from what happens in a normal request - so it has a separate test with a mocked
/// hostname added.
/// </summary>
/// <param name="urlString"></param>
/// <param name="expectedId"></param>
[TestCase("/æøå/", 1046)]
[TestCase("/æøå/home/sub1", 1173)]
[TestCase("/æøå/home/sub1/custom-sub-3-with-accént-character", 1179)]
[TestCase("/æøå/home/sub1/custom-sub-4-with-æøå", 1180)]
public void Match_Document_By_Url_With_Special_Characters_In_Hostname(string urlString, int expectedId)
{
var routingContext = GetRoutingContext(urlString);
var url = routingContext.UmbracoContext
.CleanedUmbracoUrl; //very important to use the cleaned up umbraco url
var docreq = new PublishedContentRequest(url, routingContext);
docreq.UmbracoDomain = new UmbracoDomain("http://mysite/æøå");
docreq.DomainUri = new Uri("http://mysite/æøå");
var lookup = new ContentFinderByNiceUrl();
SettingsForTests.HideTopLevelNodeFromPath = false;
var result = lookup.TryFindContent(docreq);
Assert.IsTrue(result);
Assert.AreEqual(expectedId, docreq.PublishedContent.Id);
}
}
}
@@ -998,6 +998,21 @@ namespace Umbraco.Tests.Services
Assert.That(content.Published, Is.True);
}
[Test]
public void IsPublishable()
{
// Arrange
var contentService = ServiceContext.ContentService;
var parent = contentService.CreateContent("parent", -1, "umbTextpage");
contentService.SaveAndPublishWithStatus(parent);
var content = contentService.CreateContent("child", parent, "umbTextpage");
contentService.Save(content);
Assert.IsTrue(contentService.IsPublishable(content));
contentService.UnPublish(parent);
Assert.IsFalse(contentService.IsPublishable(content));
}
[Test]
public void Can_Publish_Content_WithEvents()
{
@@ -1171,6 +1186,39 @@ namespace Umbraco.Tests.Services
Assert.That(content.Published, Is.True);
Assert.That(published, Is.True);
}
/// <summary>
/// Try to immitate a new child content item being created through the UI.
/// This content item will have no Id, Path or Identity.
/// It seems like this is wiped somewhere in the process when creating an item through the UI
/// and we need to make sure we handle nullchecks for these properties when creating content.
/// This is unfortunately not caught by the normal ContentService tests.
/// </summary>
[Test]
public void Can_Save_And_Publish_Content_And_Child_Without_Identity()
{
// Arrange
var contentService = ServiceContext.ContentService;
var content = contentService.CreateContent("Home US", -1, "umbTextpage", 0);
content.SetValue("author", "Barack Obama");
// Act
var published = contentService.SaveAndPublish(content, 0);
var childContent = contentService.CreateContent("Child", content.Id, "umbTextpage", 0);
// Reset all identity properties
childContent.Id = 0;
childContent.Path = null;
((Content)childContent).ResetIdentity();
var childPublished = contentService.SaveAndPublish(childContent, 0);
// Assert
Assert.That(content.HasIdentity, Is.True);
Assert.That(content.Published, Is.True);
Assert.That(childContent.HasIdentity, Is.True);
Assert.That(childContent.Published, Is.True);
Assert.That(published, Is.True);
Assert.That(childPublished, Is.True);
}
[Test]
public void Can_Get_Published_Descendant_Versions()
@@ -6,12 +6,25 @@ using System.Threading;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
namespace Umbraco.Tests.Services
{
// these tests tend to fail from time to time esp. on VSTS
//
// read
// Lock Time-out: https://technet.microsoft.com/en-us/library/ms172402.aspx?f=255&MSPPError=-2147217396
// http://support.x-tensive.com/question/5242/strange-locking-exceptions-with-sqlserverce
// http://debuggingblog.com/wp/2009/05/07/high-cpu-usage-and-windows-forms-application-hang-with-sqlce-database-and-the-sqlcelocktimeoutexception/
//
// tried to increase it via connection string or via SET LOCK_TIMEOUT
// but still, the test fails on VSTS in most cases, so now ignoring it,
// as I could not figure out _why_ and it does not look like we are
// causing it, getting into __sysObjects locks, no idea why
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture, RequiresSTA]
public class ThreadSafetyServiceTest : BaseDatabaseFactoryTest
@@ -32,23 +45,82 @@ namespace Umbraco.Tests.Services
base.TearDown();
}
/// <summary>
/// Used to track exceptions during multi-threaded tests, volatile so that it is not locked in CPU registers.
/// </summary>
private volatile Exception _error = null;
// not sure this is doing anything really
protected override string GetDbConnectionString()
{
// need a longer timeout for tests?
return base.GetDbConnectionString() + "default lock timeout=60000;";
}
/// <summary>
/// Used to track exceptions during multi-threaded tests, volatile so that it is not locked in CPU registers.
/// </summary>
private volatile Exception _error;
private const int MaxThreadCount = 20;
[Test]
private IScopeProvider ScopeProvider { get { return ApplicationContext.Current.ScopeProvider; } }
private void Save(ContentService service, IContent content)
{
using (var scope = ScopeProvider.CreateScope())
{
scope.Database.Execute("SET LOCK_TIMEOUT 60000");
service.Save(content);
scope.Complete();
}
}
private void Save(MediaService service, IMedia media)
{
using (var scope = ScopeProvider.CreateScope())
{
scope.Database.Execute("SET LOCK_TIMEOUT 60000");
service.Save(media);
scope.Complete();
}
}
private ManualResetEventSlim TraceLocks()
{
var done = new ManualResetEventSlim(false);
// comment out to trace locks
return done;
new Thread(() =>
{
while (done.IsSet == false)
{
var db = ApplicationContext.Current.DatabaseContext.Database;
var info = db.Query<dynamic>("SELECT * FROM sys.lock_information;");
Console.WriteLine("LOCKS:");
foreach (var row in info)
{
Console.WriteLine("> " + row.request_spid + " " + row.resource_type + " " + row.resource_description + " " + row.request_mode + " " + row.resource_table + " " + row.resource_table_id + " " + row.request_status);
}
Thread.Sleep(50);
}
}).Start();
return done;
}
[Test]
public void Ensure_All_Threads_Execute_Successfully_Content_Service()
{
//we will mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null)
Assert.Ignore("Do not run on VSTS.");
// the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
var contentService = (ContentService)ServiceContext.ContentService;
var threads = new List<Thread>();
Debug.WriteLine("Starting...");
var done = TraceLocks();
_error = null;
for (var i = 0; i < MaxThreadCount; i++)
{
var t = new Thread(() =>
@@ -57,26 +129,17 @@ namespace Umbraco.Tests.Services
{
Debug.WriteLine("[{0}] Running...", Thread.CurrentThread.ManagedThreadId);
using (var scope = ApplicationContext.Current.ScopeProvider.CreateScope())
{
var database = scope.Database;
Debug.WriteLine("[{0}] Database {1}.", Thread.CurrentThread.ManagedThreadId, database.InstanceSid);
}
//create 2 content items
string name1 = "test" + Guid.NewGuid();
var content1 = contentService.CreateContent(name1, -1, "umbTextpage", 0);
var name1 = "test-" + Guid.NewGuid();
var content1 = contentService.CreateContent(name1, -1, "umbTextpage");
Debug.WriteLine("[{0}] Saving content #1.", Thread.CurrentThread.ManagedThreadId);
contentService.Save(content1);
Save(contentService, content1);
Thread.Sleep(100); //quick pause for maximum overlap!
Thread.Sleep(100); // quick pause for maximum overlap
string name2 = "test" + Guid.NewGuid();
var content2 = contentService.CreateContent(name2, -1, "umbTextpage", 0);
var name2 = "test-" + Guid.NewGuid();
var content2 = contentService.CreateContent(name2, -1, "umbTextpage");
Debug.WriteLine("[{0}] Saving content #2.", Thread.CurrentThread.ManagedThreadId);
contentService.Save(content2);
Save(contentService, content2);
}
catch(Exception e)
{
@@ -86,39 +149,43 @@ namespace Umbraco.Tests.Services
threads.Add(t);
}
//start all threads
// start all threads
threads.ForEach(x => x.Start());
//wait for all to complete
// wait for all to complete
threads.ForEach(x => x.Join());
//kill them all
threads.ForEach(x => x.Abort());
done.Set();
if (_error == null)
{
//now look up all items, there should be 40!
// now look up all items, there should be 40!
var items = contentService.GetRootContent();
Assert.AreEqual(40, items.Count());
Assert.AreEqual(2 * MaxThreadCount, items.Count());
}
else
{
throw new Exception("Error!", _error);
}
Assert.Fail("ERROR! " + _error);
}
}
[Test]
public void Ensure_All_Threads_Execute_Successfully_Media_Service()
{
//we will mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
var mediaService = (MediaService)ServiceContext.MediaService;
if (Environment.GetEnvironmentVariable("UMBRACO_TMP") != null)
Assert.Ignore("Do not run on VSTS.");
// mimick the ServiceContext in that each repository in a service (i.e. ContentService) is a singleton
var mediaService = (MediaService) ServiceContext.MediaService;
var threads = new List<Thread>();
Debug.WriteLine("Starting...");
for (var i = 0; i < MaxThreadCount; i++)
var done = TraceLocks();
_error = null;
for (var i = 0; i < MaxThreadCount; i++)
{
var t = new Thread(() =>
{
@@ -126,25 +193,17 @@ namespace Umbraco.Tests.Services
{
Debug.WriteLine("[{0}] Running...", Thread.CurrentThread.ManagedThreadId);
using (var scope = ApplicationContext.Current.ScopeProvider.CreateScope())
{
var database = scope.Database;
Debug.WriteLine("[{0}] Database {1}.", Thread.CurrentThread.ManagedThreadId, database.InstanceSid);
}
var name1 = "test-" + Guid.NewGuid();
var media1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder);
Debug.WriteLine("[{0}] Saving media #1.", Thread.CurrentThread.ManagedThreadId);
Save(mediaService, media1);
//create 2 content items
Thread.Sleep(100); // quick pause for maximum overlap
string name1 = "test" + Guid.NewGuid();
var folder1 = mediaService.CreateMedia(name1, -1, Constants.Conventions.MediaTypes.Folder, 0);
Debug.WriteLine("[{0}] Saving content #1.", Thread.CurrentThread.ManagedThreadId);
mediaService.Save(folder1, 0);
Thread.Sleep(100); //quick pause for maximum overlap!
string name = "test" + Guid.NewGuid();
var folder2 = mediaService.CreateMedia(name, -1, Constants.Conventions.MediaTypes.Folder, 0);
Debug.WriteLine("[{0}] Saving content #2.", Thread.CurrentThread.ManagedThreadId);
mediaService.Save(folder2, 0);
var name2 = "test-" + Guid.NewGuid();
var media2 = mediaService.CreateMedia(name2, -1, Constants.Conventions.MediaTypes.Folder);
Debug.WriteLine("[{0}] Saving media #2.", Thread.CurrentThread.ManagedThreadId);
Save(mediaService, media2);
}
catch (Exception e)
{
@@ -154,32 +213,30 @@ namespace Umbraco.Tests.Services
threads.Add(t);
}
//start all threads
// start all threads
threads.ForEach(x => x.Start());
//wait for all to complete
// wait for all to complete
threads.ForEach(x => x.Join());
//kill them all
threads.ForEach(x => x.Abort());
done.Set();
if (_error == null)
{
//now look up all items, there should be 40!
// now look up all items, there should be 40
var items = mediaService.GetRootMedia();
Assert.AreEqual(40, items.Count());
Assert.AreEqual(2 * MaxThreadCount, items.Count());
}
else
{
Assert.Fail("ERROR! " + _error);
}
}
public void CreateTestData()
{
//Create and Save ContentType "umbTextpage" -> 1045
ContentType contentType = MockedContentTypes.CreateSimpleContentType("umbTextpage", "Textpage");
// Create and Save ContentType "umbTextpage" -> 1045
var contentType = MockedContentTypes.CreateSimpleContentType("umbTextpage", "Textpage");
contentType.Key = new Guid("1D3A8E6E-2EA9-4CC1-B229-1AEE19821522");
ServiceContext.ContentTypeService.Save(contentType);
}
@@ -1,13 +1,10 @@
using System.Configuration;
using System.Linq;
using System.Web.Routing;
using NUnit.Framework;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Models;
using Umbraco.Tests.TestHelpers.Stubs;
using Umbraco.Web;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
using Umbraco.Web.Routing;
namespace Umbraco.Tests.TestHelpers
+3 -18
View File
@@ -1,23 +1,6 @@
using System;
using System.IO;
using System.Web.Routing;
using System.Xml;
using NUnit.Framework;
using SQLCE4Umbraco;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
using Umbraco.Core.Services;
using Umbraco.Tests.PublishedContent;
using Umbraco.Web;
using Umbraco.Web.Routing;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.cache;
namespace Umbraco.Tests.TestHelpers
{
@@ -68,7 +51,9 @@ namespace Umbraco.Tests.TestHelpers
<content><![CDATA[]]></content>
</Home>
<CustomDocument id=""1177"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""custom sub 1"" urlName=""custom-sub-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1177"" isDoc="""" />
<CustomDocument id=""1178"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 2"" urlName=""custom-sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1178"" isDoc="""" />
<CustomDocument id=""1178"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 2"" urlName=""custom-sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1178"" isDoc="""" />
<CustomDocument id=""1179"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 3 with accént character"" urlName=""custom-sub-3-with-accént-character"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1179"" isDoc="""" />
<CustomDocument id=""1180"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 4 with æøå"" urlName=""custom-sub-4-with-æøå"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1180"" isDoc="""" />
</Home>
<Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content>
</Home>
+143 -7
View File
@@ -1,8 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Deploy;
using Umbraco.Core.Serialization;
namespace Umbraco.Tests
@@ -11,7 +14,7 @@ namespace Umbraco.Tests
public class UdiTests
{
[Test]
public void StringEntityCtorTest()
public void StringUdiCtorTest()
{
var udi = new StringUdi(Constants.UdiEntityType.AnyString, "test-id");
Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
@@ -20,7 +23,7 @@ namespace Umbraco.Tests
}
[Test]
public void StringEntityParseTest()
public void StringUdiParseTest()
{
var udi = Udi.Parse("umb://" + Constants.UdiEntityType.AnyString + "/test-id");
Assert.AreEqual(Constants.UdiEntityType.AnyString, udi.EntityType);
@@ -29,6 +32,9 @@ namespace Umbraco.Tests
Assert.IsNotNull(stringEntityId);
Assert.AreEqual("test-id", stringEntityId.Id);
Assert.AreEqual("umb://" + Constants.UdiEntityType.AnyString + "/test-id", udi.ToString());
udi = Udi.Parse("umb://" + Constants.UdiEntityType.AnyString + "/DA845952BE474EE9BD6F6194272AC750");
Assert.IsInstanceOf<StringUdi>(udi);
}
[Test]
@@ -83,7 +89,7 @@ namespace Umbraco.Tests
}
[Test]
public void GuidEntityCtorTest()
public void GuidUdiCtorTest()
{
var guid = Guid.NewGuid();
var udi = new GuidUdi(Constants.UdiEntityType.AnyGuid, guid);
@@ -93,7 +99,7 @@ namespace Umbraco.Tests
}
[Test]
public void GuidEntityParseTest()
public void GuidUdiParseTest()
{
var guid = Guid.NewGuid();
var s = "umb://" + Constants.UdiEntityType.AnyGuid + "/" + guid.ToString("N");
@@ -148,9 +154,32 @@ namespace Umbraco.Tests
Assert.AreEqual(Constants.UdiEntityType.AnyGuid, udi.EntityType);
Assert.AreEqual(guid, ((GuidUdi)udi).Guid);
Assert.Throws<InvalidOperationException>(() => Udi.Create(Constants.UdiEntityType.AnyString, guid));
Assert.Throws<InvalidOperationException>(() => Udi.Create(Constants.UdiEntityType.AnyGuid, "foo"));
Assert.Throws<ArgumentException>(() => Udi.Create("barf", "foo"));
// *not* testing whether Udi.Create(type, invalidValue) throws
// because we don't throw anymore - see U4-10409
}
[Test]
public void RootUdiTest()
{
var stringUdi = new StringUdi(Constants.UdiEntityType.AnyString, string.Empty);
Assert.IsTrue(stringUdi.IsRoot);
Assert.AreEqual("umb://any-string/", stringUdi.ToString());
var guidUdi = new GuidUdi(Constants.UdiEntityType.AnyGuid, Guid.Empty);
Assert.IsTrue(guidUdi.IsRoot);
Assert.AreEqual("umb://any-guid/00000000000000000000000000000000", guidUdi.ToString());
var udi = Udi.Parse("umb://any-string/");
Assert.IsTrue(udi.IsRoot);
Assert.IsInstanceOf<StringUdi>(udi);
udi = Udi.Parse("umb://any-guid/00000000000000000000000000000000");
Assert.IsTrue(udi.IsRoot);
Assert.IsInstanceOf<GuidUdi>(udi);
udi = Udi.Parse("umb://any-guid/");
Assert.IsTrue(udi.IsRoot);
Assert.IsInstanceOf<GuidUdi>(udi);
}
[Test]
@@ -202,5 +231,112 @@ namespace Umbraco.Tests
Assert.AreEqual(string.Format("umb://any-guid/{0:N}", guid), drange.Udi.UriValue.ToString());
Assert.AreEqual(Constants.DeploySelector.ChildrenOfThis, drange.Selector);
}
[Test]
public void ValidateUdiEntityType()
{
var types = Constants.UdiEntityType.GetTypes();
foreach (var fi in typeof (Constants.UdiEntityType).GetFields(BindingFlags.Public | BindingFlags.Static))
{
// IsLiteral determines if its value is written at
// compile time and not changeable
// IsInitOnly determine if the field can be set
// in the body of the constructor
// for C# a field which is readonly keyword would have both true
// but a const field would have only IsLiteral equal to true
if (fi.IsLiteral && fi.IsInitOnly == false)
{
var value = fi.GetValue(null).ToString();
if (types.ContainsKey(value) == false)
Assert.Fail("Error in class Constants.UdiEntityType, type \"{0}\" is not declared by GetTypes.", value);
types.Remove(value);
}
}
Assert.AreEqual(0, types.Count, "Error in class Constants.UdiEntityType, GetTypes declares types that don't exist ({0}).", string.Join(",", types.Keys.Select(x => "\"" + x + "\"")));
}
[Test]
public void KnownTypes()
{
Udi udi;
// cannot parse an unknown type, udi is null
// this will scan
Assert.IsFalse(Udi.TryParse("umb://whatever/1234", out udi));
Assert.IsNull(udi);
Udi.ResetUdiTypes();
// unless we want to know
Assert.IsFalse(Udi.TryParse("umb://whatever/1234", true, out udi));
Assert.AreEqual(Constants.UdiEntityType.Unknown, udi.EntityType);
Assert.AreEqual("Umbraco.Core.Udi+UnknownTypeUdi", udi.GetType().FullName);
Udi.ResetUdiTypes();
// not known
Assert.IsFalse(Udi.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", true, out udi));
Assert.AreEqual(Constants.UdiEntityType.Unknown, udi.EntityType);
Assert.AreEqual("Umbraco.Core.Udi+UnknownTypeUdi", udi.GetType().FullName);
// scanned
Assert.IsTrue(Udi.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", out udi));
Assert.IsInstanceOf<GuidUdi>(udi);
// known
Assert.IsTrue(Udi.TryParse("umb://foo/A87F65C8D6B94E868F6949BA92C93045", true, out udi));
Assert.IsInstanceOf<GuidUdi>(udi);
// can get method for Deploy compatibility
var method = typeof (Udi).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof (string), typeof (bool) }, null);
Assert.IsNotNull(method);
}
[UdiDefinition("foo", UdiType.GuidUdi)]
public class FooConnector : IServiceConnector
{
public IArtifact GetArtifact(Udi udi)
{
throw new NotImplementedException();
}
public IArtifact GetArtifact(object entity)
{
throw new NotImplementedException();
}
public ArtifactDeployState ProcessInit(IArtifact art, IDeployContext context)
{
throw new NotImplementedException();
}
public void Process(ArtifactDeployState dart, IDeployContext context, int pass)
{
throw new NotImplementedException();
}
public void Explode(UdiRange range, List<Udi> udis)
{
throw new NotImplementedException();
}
public NamedUdiRange GetRange(Udi udi, string selector)
{
throw new NotImplementedException();
}
public NamedUdiRange GetRange(string entityType, string sid, string selector)
{
throw new NotImplementedException();
}
public bool Compare(IArtifact art1, IArtifact art2, ICollection<Difference> differences = null)
{
throw new NotImplementedException();
}
}
}
}
+4 -4
View File
@@ -30,6 +30,7 @@
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
<NugetPackages Condition="$(NugetPackages) == '' Or $(NugetPackages) == '*Undefined*'">$(SolutionDir)\packages</NugetPackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -213,6 +214,7 @@
<Compile Include="Web\Controllers\BackOfficeControllerUnitTests.cs" />
<Compile Include="DelegateExtensionsTests.cs" />
<Compile Include="Web\HttpCookieExtensionsTests.cs" />
<Compile Include="Web\Mvc\HtmlStringUtilitiesTests.cs" />
<Compile Include="Web\Mvc\RenderIndexActionSelectorAttributeTests.cs" />
<Compile Include="Persistence\Repositories\AuditRepositoryTest.cs" />
<Compile Include="Persistence\Repositories\DomainRepositoryTest.cs" />
@@ -773,12 +775,10 @@
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<PropertyGroup>
<PreBuildEvent>xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\amd64\*.* "$(TargetDir)amd64\" /Y /F /E /I /C /D
xcopy "$(ProjectDir)"..\packages\SqlServerCE.4.0.0.1\x86\*.* "$(TargetDir)x86\" /Y /F /E /I /C /D</PreBuildEvent>
<PreBuildEvent>xcopy "$(NugetPackages)\SqlServerCE.4.0.0.1\amd64\*.*" "$(TargetDir)amd64\" /Y /F /E /I /C /D
xcopy "$(NugetPackages)\SqlServerCE.4.0.0.1\x86\*.*" "$(TargetDir)x86\" /Y /F /E /I /C /D</PreBuildEvent>
</PropertyGroup>
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<Import Project="..\packages\AutoMapper.3.3.1\tools\AutoMapper.targets" Condition="Exists('..\packages\AutoMapper.3.3.1\tools\AutoMapper.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
@@ -0,0 +1,26 @@
using NUnit.Framework;
using Umbraco.Web;
namespace Umbraco.Tests.Web.Mvc
{
[TestFixture]
public class HtmlStringUtilitiesTests
{
private HtmlStringUtilities _htmlStringUtilities;
[SetUp]
public virtual void Initialize()
{
_htmlStringUtilities = new HtmlStringUtilities();
}
[Test]
public void ReplaceLineBreaksWithHtmlBreak()
{
var output = _htmlStringUtilities.ReplaceLineBreaksForHtml("<div><h1>hello world</h1><p>hello world\r\nhello world\rhello world\nhello world</p></div>");
var expected = "<div><h1>hello world</h1><p>hello world<br />hello world<br />hello world<br />hello world</p></div>";
Assert.AreEqual(expected, output);
}
}
}
+2 -2
View File
@@ -39,7 +39,7 @@
"globals": {
"angular": false,
"_": false,
"$", false,
"$": false,
"tinymce": false,
"tinyMCE": false,
"FileReader": false,
@@ -47,7 +47,7 @@
"window": false,
"LazyLoad": false,
"ActiveXObject": false,
"Bloodhound", false
"Bloodhound": false
}
}
-97
View File
@@ -1,97 +0,0 @@
#Belle
Umbraco 7 UI, codename "Belle" Built on AngularJS, bower, Lazyload.js and Twitter Bootstrap
##Introduction
Slides from the initial demonstration of Belle done at the Umbraco DK Fest can be found here:
http://rawgithub.com/umbraco/Umbraco.Web.Ui.Client/build/master/Presentation/index.html
##Running the site with mocked data
This won't require any database or setup, as everything is running through node. All you have to do is install
node and grunt on either windows or OSX and the entire setup is ready for you.
###Install node.js
We need node to run tests and automated less compiling and other automated tasks. go to http://nodejs.org. Node.js is a powerfull javascript engine, which allows us to run all our tests and tasks written in javascript locally.
*note:* On windows you might need to restart explorer.exe to register node.
###Install dependencies
Next we need to install all the required packages. This is done with the package tool, included with node.js, open /src/Umbraco.Web.UI.Client in cmd.exe or osx terminal and run the command:
npm install
this will fetch all needed packages to your local machine.
###Install grunt globally
Grunt is a task runner for node.js, and we use it for all automated tasks in the build process. For convenience we need to install it globally on your machine, so it can be used directly in cmd.exe or the terminal.
So run the command:
npm install grunt-cli -g
*note:* On windows you might need to restart explorer.exe to register the grunt cmd.
*note:* On OSX you might need to run:
sudo npm install grunt-cli -g
Now that you have node and grunt installed, you can open `/src/Umbraco.Web.UI.Client` in either `cmd.exe` or terminal and run:
grunt dev
This will build the site, merge less files, run tests and create the /Build folder, and finally open the site in your
browser.
##Limitations
The current prototype simply uses in-memory storage, so no database dependencies. It is aimed at showing UI, not a complete functional client-server setup.
##Project Structure
All project files are located in /src/Umbraco.Web.UI.Client which only contains client-side files, everything
related to asp.net are in /src/Umbraco.Web.UI
after building Belle files are located in /build/belle, with all files following AngularJs
conventions:
###Folders
- */Umbraco.Web.Ui.Client/build/lib:* Dependencies
- */Umbraco.Web.Ui.Client/build/js:* Application javascript files
- */Umbraco.Web.Ui.Client/build/views/common/:* Main application views
- */Umbraco.Web.Ui.Client/build/views/[sectioname]/pagename Editors html
- */Umbraco.Web.Ui.Client/build/views/propertyeditors:* Property Editors html
###Files
- */Umbraco.Web.Ui.Client/build/js/app.js:* Main umbraco application / modules
- */Umbraco.Web.Ui.Client/build/js/loader.js:* lazyload configuration for dependencies
- */Umbraco.Web.Ui.Client/build/js/routes.js:* Application routes
- */Umbraco.Web.Ui.Client/build/js/umbraco.controllers.js:* Application controllers
- */Umbraco.Web.Ui.Client/build/js/umbraco.services.js:* Application services
- */Umbraco.Web.Ui.Client/build/js/umbraco.filters.js:* Application filters
- */Umbraco.Web.Ui.Client/build/js/umbraco.directives.js:* Application directives
- */Umbraco.Web.Ui.Client/build/js/umbraco.resources.js:* Application resources, like content, media, users, members etc
- */Umbraco.Web.Ui.Client/build/js/umbraco.mocks.js:* Fake Application resources, for running the app without a server
##Getting started
The current app is built, following conventions from angularJs and bootstrap. To get started with the applicaton you will need to atleast know the basics of these frameworks
###AngularJS
- Excellent introduction videos on http://www.egghead.io/
- Official guide at: http://docs.angularjs.org/guide/
###Require.js
- Introduction: http://javascriptplayground.com/blog/2012/07/requirejs-amd-tutorial-introduction
- Require.js website: http://requirejs.org/
+51 -2
View File
@@ -1,5 +1,5 @@
{
"name": "Umbraco",
"name": "umbraco",
"version": "7",
"homepage": "https://github.com/umbraco/Umbraco-CMS",
"authors": [
@@ -29,6 +29,55 @@
"codemirror": "~5.3.0",
"angular-local-storage": "~0.2.3",
"moment": "~2.10.3",
"ace-builds": "^1.2.3"
"ace-builds": "^1.2.3",
"font-awesome": "~4.2"
},
"install": {
"path": "lib-bower",
"ignore": [
"font-awesome",
"angular",
"bootstrap",
"codemirror"
],
"sources": {
"moment": "bower_components/moment/min/moment-with-locales.js",
"underscore": [
"bower_components/underscore/underscore-min.js",
"bower_components/underscore/underscore-min.map"
],
"jquery": [
"bower_components/jquery/dist/jquery.min.js",
"bower_components/jquery/dist/jquery.min.map"
],
"angular-dynamic-locale": [
"bower_components/angular-dynamic-locale/tmhDynamicLocale.min.js",
"bower_components/angular-dynamic-locale/tmhDynamicLocale.min.js.map"
],
"angular-local-storage": [
"bower_components/angular-local-storage/dist/angular-local-storage.min.js",
"bower_components/angular-local-storage/dist/angular-local-storage.min.js.map"
],
"tinymce": [
"bower_components/tinymce/tinymce.min.js"
],
"typeahead.js": "bower_components/typeahead.js/dist/typeahead.bundle.min.js",
"rgrove-lazyload":"bower_components/rgrove-lazyload/lazyload.js",
"ng-file-upload":"bower_components/ng-file-upload/ng-file-upload.min.js",
"jquery-ui":"bower_components/jquery-ui/jquery-ui.min.js",
"jquery-migrate":"bower_components/jquery-migrate/jquery-migrate.min.js"
}
}
}
-597
View File
@@ -1,597 +0,0 @@
module.exports = function (grunt) {
// Default task.
grunt.registerTask('default', ['jshint:dev', 'build', 'karma:unit']);
grunt.registerTask('dev', ['jshint:dev', 'build-dev', 'webserver', 'open:dev', 'watch']);
grunt.registerTask('docserve', ['docs:api', 'connect:docserver', 'open:docs', 'watch:docs']);
grunt.registerTask('vs', ['jshint:dev', 'build-dev', 'watch']);
//TODO: Too much watching, this brings windows to it's knees when in dev mode
//run by the watch task
grunt.registerTask('watch-js', ['jshint:dev', 'concat', 'copy:app', 'copy:mocks', 'copy:canvasdesigner', 'copy:vs', 'karma:unit']);
grunt.registerTask('watch-less', ['recess:build', 'recess:installer', 'recess:nonodes', 'recess:canvasdesigner', 'postcss', 'copy:canvasdesigner', 'copy:assets', 'copy:vs']);
grunt.registerTask('watch-html', ['copy:views', 'copy:vs']);
grunt.registerTask('watch-installer', ['concat:install', 'concat:installJs', 'copy:installer', 'copy:vs']);
grunt.registerTask('watch-canvasdesigner', ['copy:canvasdesigner', 'concat:canvasdesignerJs', 'copy:vs']);
grunt.registerTask('watch-test', ['jshint:dev', 'karma:unit']);
//triggered from grunt
grunt.registerTask('build', ['concat', 'recess:build', 'recess:installer', 'recess:nonodes', 'recess:canvasdesigner', 'postcss', 'bower-install-simple', 'bower', 'copy', 'clean:post']);
//triggered from grunt dev vs or grunt vs
grunt.registerTask('build-dev', ['clean:pre', 'concat', 'recess:build', 'recess:installer', 'recess:nonodes', 'postcss', 'bower-install-simple', 'bower', 'copy']);
//utillity tasks
grunt.registerTask('docs', ['ngdocs']);
grunt.registerTask('webserver', ['connect:devserver']);
// Print a timestamp (useful for when watching)
grunt.registerTask('timestamp', function () {
grunt.log.subhead(Date());
});
// Project configuration.
grunt.initConfig({
buildVersion: grunt.option('buildversion') || '7',
connect: {
devserver: {
options: {
port: 9990,
hostname: '0.0.0.0',
base: './build',
middleware: function(connect, options) {
return [
//uncomment to enable CSP
// util.csp(),
//util.rewrite(),
connect.favicon('images/favicon.ico'),
connect.static(options.base),
connect.directory(options.base)
];
}
}
},
testserver: {},
docserver: {
options: {
port: 8880,
hostname: '0.0.0.0',
base: './docs/api',
middleware: function(connect, options) {
return [
//uncomment to enable CSP
// util.csp(),
//util.rewrite(),
connect.static(options.base),
connect.directory(options.base)
];
}
}
},
},
open: {
dev: {
path: 'http://localhost:9990/belle/'
},
docs: {
path: 'http://localhost:8880/index.html'
}
},
distdir: 'build/belle',
vsdir: '../Umbraco.Web.UI/umbraco',
pkg: grunt.file.readJSON('package.json'),
banner:
'/*! <%= pkg.title || pkg.name %>\n' +
'<%= pkg.homepage ? " * " + pkg.homepage + "\\n" : "" %>' +
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>;\n' +
' * Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %>\n */\n',
src: {
js: ['src/**/*.js', 'src/*.js'],
common: ['src/common/**/*.js'],
controllers: ['src/**/*.controller.js'],
specs: ['test/**/*.spec.js'],
scenarios: ['test/**/*.scenario.js'],
samples: ['sample files/*.js'],
html: ['src/index.html', 'src/install.html'],
everything: ['src/**/*.*', 'test/**/*.*', 'docs/**/*.*'],
tpl: {
app: ['src/views/**/*.html'],
common: ['src/common/**/*.tpl.html']
},
less: ['src/less/belle.less'], // recess:build doesn't accept ** in its file patterns
prod: ['<%= distdir %>/js/*.js']
},
clean: {
pre: ['<%= distdir %>/*'],
post: ['<%= distdir %>/js/*.dev.js']
},
copy: {
assets: {
files: [{ dest: '<%= distdir %>/assets', src: '**', expand: true, cwd: 'src/assets/' }]
},
config: {
files: [{ dest: '<%= distdir %>/../config', src: '**', expand: true, cwd: 'src/config/' }]
},
installer: {
files: [{ dest: '<%= distdir %>/views/install', src: '**/*.html', expand: true, cwd: 'src/installer/steps' }]
},
canvasdesigner: {
files: [
{ dest: '<%= distdir %>/preview', src: '**/*.html', expand: true, cwd: 'src/canvasdesigner' },
{ dest: '<%= distdir %>/preview/editors', src: '**/*.html', expand: true, cwd: 'src/canvasdesigner/editors' },
{ dest: '<%= distdir %>/assets/less', src: '**/*.less', expand: true, cwd: 'src/canvasdesigner/editors' },
{ dest: '<%= distdir %>/js', src: 'canvasdesigner.config.js', expand: true, cwd: 'src/canvasdesigner/config' },
{ dest: '<%= distdir %>/js', src: 'canvasdesigner.palettes.js', expand: true, cwd: 'src/canvasdesigner/config' },
{ dest: '<%= distdir %>/js', src: 'canvasdesigner.front.js', expand: true, cwd: 'src/canvasdesigner' }
]
},
vendor: {
files: [{ dest: '<%= distdir %>/lib', src: '**', expand: true, cwd: 'lib/' }]
},
views: {
files: [{ dest: '<%= distdir %>/views', src: ['**/*.*', '!**/*.controller.js'], expand: true, cwd: 'src/views' }]
},
app: {
files: [
{ dest: '<%= distdir %>/js', src: '*.js', expand: true, cwd: 'src/' }
]
},
mocks: {
files: [{ dest: '<%= distdir %>/js', src: '*.js', expand: true, cwd: 'src/common/mocks/' }]
},
vs: {
files: [
//everything except the index.html root file!
//then we need to figure out how to not copy all the test stuff either!?
{ dest: '<%= vsdir %>/assets', src: '**', expand: true, cwd: '<%= distdir %>/assets' },
{ dest: '<%= vsdir %>/js', src: '**', expand: true, cwd: '<%= distdir %>/js' },
{ dest: '<%= vsdir %>/views', src: '**', expand: true, cwd: '<%= distdir %>/views' },
{ dest: '<%= vsdir %>/preview', src: '**', expand: true, cwd: '<%= distdir %>/preview' },
{ dest: '<%= vsdir %>/lib', src: '**', expand: true, cwd: '<%= distdir %>/lib' }
]
}
},
karma: {
unit: { configFile: 'test/config/karma.conf.js', keepalive: true },
e2e: { configFile: 'test/config/e2e.js', keepalive: true },
watch: { configFile: 'test/config/unit.js', singleRun: false, autoWatch: true, keepalive: true }
},
concat: {
index: {
src: ['src/index.html'],
dest: '<%= distdir %>/index.html',
options: {
process: true
}
},
install: {
src: ['src/installer/installer.html'],
dest: '<%= distdir %>/installer.html',
options: {
process: true
}
},
installJs: {
src: ['src/installer/**/*.js'],
dest: '<%= distdir %>/js/umbraco.installer.js',
options: {
banner: "<%= banner %>\n(function() { \n\n angular.module('umbraco.install', []); \n",
footer: "\n\n})();"
}
},
canvasdesignerJs: {
src: ['src/canvasdesigner/canvasdesigner.global.js', 'src/canvasdesigner/canvasdesigner.controller.js', 'src/canvasdesigner/editors/*.js', 'src/canvasdesigner/lib/*.js'],
dest: '<%= distdir %>/js/canvasdesigner.panel.js'
},
controllers: {
src: ['src/controllers/**/*.controller.js', 'src/views/**/*.controller.js'],
dest: '<%= distdir %>/js/umbraco.controllers.js',
options: {
banner: "<%= banner %>\n(function() { \n\n",
footer: "\n\n})();"
}
},
services: {
src: ['src/common/services/*.js'],
dest: '<%= distdir %>/js/umbraco.services.js',
options: {
banner: "<%= banner %>\n(function() { \n\n",
footer: "\n\n})();"
}
},
security: {
src: ['src/common/security/*.js'],
dest: '<%= distdir %>/js/umbraco.security.js',
options: {
banner: "<%= banner %>\n(function() { \n\n",
footer: "\n\n})();"
}
},
resources: {
src: ['src/common/resources/*.js'],
dest: '<%= distdir %>/js/umbraco.resources.js',
options: {
banner: "<%= banner %>\n(function() { \n\n",
footer: "\n\n})();"
}
},
testing: {
src: ['src/common/mocks/*/*.js'],
dest: '<%= distdir %>/js/umbraco.testing.js',
options: {
banner: "<%= banner %>\n(function() { \n\n",
footer: "\n\n})();"
}
},
directives: {
src: ['src/common/directives/**/*.js'],
dest: '<%= distdir %>/js/umbraco.directives.js',
options: {
banner: "<%= banner %>\n(function() { \n\n",
footer: "\n\n})();"
}
},
filters: {
src: ['src/common/filters/*.js'],
dest: '<%= distdir %>/js/umbraco.filters.js',
options: {
banner: "<%= banner %>\n(function() { \n\n",
footer: "\n\n})();"
}
}
},
uglify: {
options: {
mangle: true
},
combine: {
files: {
'<%= distdir %>/js/umbraco.min.js': ['<%= distdir %>/js/umbraco.*.js']
}
}
},
recess: {
build: {
files: {
'<%= distdir %>/assets/css/<%= pkg.name %>.css':
['<%= src.less %>']
},
options: {
compile: true,
compress: true
}
},
nonodes: {
files: {
'<%= distdir %>/assets/css/nonodes.style.min.css':
['src/less/pages/nonodes.less']
},
options: {
compile: true,
compress: true
}
},
installer: {
files: {
'<%= distdir %>/assets/css/installer.css':
['src/less/installer.less']
},
options: {
compile: true,
compress: true
}
},
canvasdesigner: {
files: {
'<%= distdir %>/assets/css/canvasdesigner.css':
['src/less/canvas-designer.less', 'src/less/helveticons.less']
},
options: {
compile: true,
compress: true
}
}
},
postcss: {
options: {
processors: [
// add vendor prefixes
require('autoprefixer-core')({
browsers: 'last 2 versions'
})
]
},
dist: {
src: '<%= distdir %>/assets/css/<%= pkg.name %>.css'
}
},
ngTemplateCache: {
views: {
files: {
'<%= distdir %>/js/umbraco.views.js': 'src/views/**/*.html'
},
options: {
trim: 'src/',
module: 'umbraco.views'
}
}
},
watch: {
docs: {
files: ['docs/src/**/*.md'],
tasks: ['watch-docs', 'timestamp']
},
css: {
files: 'src/**/*.less',
tasks: ['watch-less', 'timestamp'],
options: {
livereload: true,
},
},
js: {
files: ['src/**/*.js', 'src/*.js'],
tasks: ['watch-js', 'timestamp'],
},
test: {
files: ['test/**/*.js'],
tasks: ['watch-test', 'timestamp'],
},
installer: {
files: ['src/installer/**/*.*'],
tasks: ['watch-installer', 'timestamp'],
},
canvasdesigner: {
files: ['src/canvasdesigner/**/*.*'],
tasks: ['watch-canvasdesigner', 'timestamp'],
},
html: {
files: ['src/views/**/*.html', 'src/*.html'],
tasks: ['watch-html', 'timestamp']
},
options: {
interval: 500
}
},
ngdocs: {
options: {
dest: 'docs/api',
startPage: '/api',
title: "Umbraco Backoffice UI API Documentation",
html5Mode: false,
styles: [
'docs/umb-docs.css'
],
image: "https://our.umbraco.org/assets/images/logo.svg"
},
api: {
src: ['src/common/**/*.js', 'docs/src/api/**/*.ngdoc'],
title: 'API Documentation'
},
tutorials: {
src: [],
title: ''
}
},
eslint:{
src: ['<%= src.common %>','<%= src.controllers %>'],
options: {quiet: true}
},
jshint: {
dev: {
files: {
src: ['<%= src.common %>']
},
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: "nofunc",
newcap: true,
noarg: true,
sub: true,
boss: true,
//NOTE: This is required so it doesn't barf on reserved words like delete when doing $http.delete
es5: true,
eqnull: true,
//NOTE: we need to use eval sometimes so ignore it
evil: true,
//NOTE: we need to check for strings such as "javascript:" so don't throw errors regarding those
scripturl: true,
//NOTE: we ignore tabs vs spaces because enforcing that causes lots of errors depending on the text editor being used
smarttabs: true,
globals: {}
}
},
build: {
files: {
src: ['<%= src.prod %>']
},
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: "nofunc",
newcap: true,
noarg: true,
sub: true,
boss: true,
//NOTE: This is required so it doesn't barf on reserved words like delete when doing $http.delete
es5: true,
eqnull: true,
//NOTE: we need to use eval sometimes so ignore it
evil: true,
//NOTE: we need to check for strings such as "javascript:" so don't throw errors regarding those
scripturl: true,
//NOTE: we ignore tabs vs spaces because enforcing that causes lots of errors depending on the text editor being used
smarttabs: true,
globalstrict: true,
globals: { $: false, jQuery: false, define: false, require: false, window: false }
}
}
},
bower: {
dev: {
dest: '<%= distdir %>/lib',
options: {
expand: true,
ignorePackages: ['bootstrap'],
packageSpecific: {
'moment': {
keepExpandedHierarchy: false,
files: ['min/moment-with-locales.js']
},
'typeahead.js': {
keepExpandedHierarchy: false,
files: ['dist/typeahead.bundle.min.js']
},
'underscore': {
files: ['underscore-min.js', 'underscore-min.map']
},
'rgrove-lazyload': {
files: ['lazyload.js']
},
'bootstrap-social': {
files: ['bootstrap-social.css']
},
'font-awesome': {
files: ['css/font-awesome.min.css', 'fonts/*']
},
"jquery": {
keepExpandedHierarchy: false,
files: ['dist/jquery.min.js', 'dist/jquery.min.map']
},
'jquery-ui': {
keepExpandedHierarchy: false,
files: ['jquery-ui.min.js']
},
'jquery-migrate': {
keepExpandedHierarchy: false,
files: ['jquery-migrate.min.js']
},
'tinymce': {
files: ['plugins/**', 'themes/**', 'tinymce.min.js']
},
'angular-dynamic-locale': {
files: ['tmhDynamicLocale.min.js', 'tmhDynamicLocale.min.js.map']
},
'ng-file-upload': {
keepExpandedHierarchy: false,
files: ['ng-file-upload.min.js']
},
'angular-local-storage': {
keepExpandedHierarchy: false,
files: ['dist/angular-local-storage.min.js']
},
'codemirror': {
files: [
'lib/codemirror.js',
'lib/codemirror.css',
'mode/css/*',
'mode/javascript/*',
'mode/xml/*',
'mode/htmlmixed/*',
'addon/search/*',
'addon/edit/*',
'addon/selection/*',
'addon/dialog/*'
]
},
'ace-builds': {
files: [
'src-min-noconflict/ace.js',
'src-min-noconflict/ext-language_tools.js',
'src-min-noconflict/ext-searchbox.js',
'src-min-noconflict/ext-settings_menu.js',
'src-min-noconflict/snippets/text.js',
'src-min-noconflict/snippets/javascript.js',
'src-min-noconflict/theme-chrome.js',
'src-min-noconflict/mode-razor.js',
'src-min-noconflict/mode-javascript.js',
'src-min-noconflict/worker-javascript.js',
]
}
}
}
},
options: {
expand: true
}
},
"bower-install-simple": {
options: {
color: true
},
"dev": {}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-recess');
grunt.loadNpmTasks('grunt-postcss');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks("grunt-bower-install-simple");
grunt.loadNpmTasks('grunt-bower');
grunt.loadNpmTasks('grunt-ngdocs');
grunt.loadNpmTasks('grunt-eslint');
grunt.loadNpmTasks('grunt-hustler');
};
+399
View File
@@ -0,0 +1,399 @@
var gulp = require('gulp');
var watch = require('gulp-watch');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var wrap = require("gulp-wrap-js");
var sort = require('gulp-sort');
var connect = require('gulp-connect');
var open = require('gulp-open');
var runSequence = require('run-sequence');
var _ = require('lodash');
var MergeStream = require('merge-stream');
//Less + css
var postcss = require('gulp-postcss');
var less = require('gulp-less');
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
// Documentation
var gulpDocs = require('gulp-ngdocs');
// Testing
var karmaServer = require('karma').Server;
/***************************************************************
Helper functions
***************************************************************/
function processJs(files, out) {
return gulp.src(files)
.pipe(sort())
.pipe(concat(out))
.pipe(wrap('(function(){\n%= body %\n})();'))
.pipe(gulp.dest(root + targets.js));
console.log(out + " compiled");
}
function processLess(files, out) {
var processors = [
autoprefixer,
cssnano({zindex: false}),
];
return gulp.src(files)
.pipe(less())
.pipe(postcss(processors))
.pipe(rename(out))
.pipe(gulp.dest(root + targets.css));
console.log(out + " compiled");
}
/***************************************************************
Paths and destinations
Each group is iterated automatically in the setup tasks below
***************************************************************/
var sources = {
//less files used by backoffice and preview
//processed in the less task
less: {
installer: { files: ["src/less/installer.less"], out: "installer.css" },
nonodes: { files: ["src/less/pages/nonodes.less"], out: "nonodes.style.min.css"},
preview: { files: ["src/less/canvas-designer.less"], out: "canvasdesigner.css" },
umbraco: { files: ["src/less/belle.less"], out: "umbraco.css" }
},
//js files for backoffie
//processed in the js task
js: {
preview: { files: ["src/canvasdesigner/**/*.js"], out: "umbraco.canvasdesigner.js" },
installer: { files: ["src/installer/**/*.js"], out: "umbraco.installer.js" },
controllers: { files: ["src/{views,controllers}/**/*.controller.js"], out: "umbraco.controllers.js" },
directives: { files: ["src/common/directives/**/*.js"], out: "umbraco.directives.js" },
filters: { files: ["src/common/filters/**/*.js"], out: "umbraco.filters.js" },
resources: { files: ["src/common/resources/**/*.js"], out: "umbraco.resources.js" },
services: { files: ["src/common/services/**/*.js"], out: "umbraco.services.js" },
security: { files: ["src/common/security/**/*.js"], out: "umbraco.security.js" }
},
//selectors for copying all views into the build
//processed in the views task
views:{
umbraco: {files: ["src/views/**/*html"], folder: ""},
preview: { files: ["src/canvasdesigner/**/*.html"], folder: "../preview"},
installer: {files: ["src/installer/steps/*.html"], folder: "install"}
},
//globs for file-watching
globs:{
views: "./src/views/**/*.html",
less: "./src/less/**/*.less",
js: "./src/*.js",
lib: "./lib/**/*",
bower: "./lib-bower/**/*",
assets: "./src/assets/**"
}
};
var root = "../Umbraco.Web.UI/Umbraco/";
var targets = {
js: "js/",
lib: "lib/",
views: "views/",
css: "assets/css/",
assets: "assets/"
};
/**************************
* Main tasks for the project to prepare backoffice files
**************************/
// Build - build the files ready for production
gulp.task('build', function(cb) {
runSequence(["dependencies", "js", "less", "views"], "test:unit", cb);
});
// Dev - build the files ready for development and start watchers
gulp.task('dev', function(cb) {
runSequence(["dependencies", "js", "less", "views"], "watch", cb);
});
// Docserve - build and open the back office documentation
gulp.task('docserve', function(cb) {
runSequence('docs', 'connect:docs', 'open:docs', cb);
});
/**************************
* Task processes and copies all dependencies, either installed by bower, npm or stored locally in the project
**************************/
gulp.task('dependencies', function () {
//bower component specific copy rules
//this is to patch the sometimes wonky rules these libs are distrbuted under
//as we do multiple things in this task, we merge the multiple streams
var stream = new MergeStream();
//Tinymce
stream.add(
gulp.src(["./bower_components/tinymce/plugins/**",
"./bower_components/tinymce/themes/**"],
{ base: "./bower_components/tinymce/" })
.pipe(gulp.dest(root + targets.lib + "/tinymce"))
);
//font-awesome
stream.add(
gulp.src(["./bower_components/font-awesome/fonts/*",
"./bower_components/font-awesome/css/font-awesome.min.css"],
{ base: "./bower_components/font-awesome/" })
.pipe(gulp.dest(root + targets.lib + "/font-awesome"))
);
// ace Editor
stream.add(
gulp.src(["bower_components/ace-builds/src-min-noconflict/ace.js",
"bower_components/ace-builds/src-min-noconflict/ext-language_tools.js",
"bower_components/ace-builds/src-min-noconflict/ext-searchbox.js",
"bower_components/ace-builds/src-min-noconflict/ext-settings_menu.js",
"bower_components/ace-builds/src-min-noconflict/snippets/text.js",
"bower_components/ace-builds/src-min-noconflict/snippets/javascript.js",
"bower_components/ace-builds/src-min-noconflict/theme-chrome.js",
"bower_components/ace-builds/src-min-noconflict/mode-razor.js",
"bower_components/ace-builds/src-min-noconflict/mode-javascript.js",
"bower_components/ace-builds/src-min-noconflict/worker-javascript.js"],
{ base: "./bower_components/ace-builds/" })
.pipe(gulp.dest(root + targets.lib + "/ace-builds"))
);
// code mirror
stream.add(
gulp.src([
"bower_components/codemirror/lib/codemirror.js",
"bower_components/codemirror/lib/codemirror.css",
"bower_components/codemirror/mode/css/*",
"bower_components/codemirror/mode/javascript/*",
"bower_components/codemirror/mode/xml/*",
"bower_components/codemirror/mode/htmlmixed/*",
"bower_components/codemirror/addon/search/*",
"bower_components/codemirror/addon/edit/*",
"bower_components/codemirror/addon/selection/*",
"bower_components/codemirror/addon/dialog/*"],
{ base: "./bower_components/codemirror/" })
.pipe(gulp.dest(root + targets.lib + "/codemirror"))
);
//copy over libs which are not on bower (/lib) and
//libraries that have been managed by bower-installer (/lib-bower)
stream.add(
gulp.src(sources.globs.lib)
.pipe(gulp.dest(root + targets.lib))
);
stream.add(
gulp.src(sources.globs.bower)
.pipe(gulp.dest(root + targets.lib))
);
//Copies all static assets into /root / assets folder
//css, fonts and image files
stream.add(
gulp.src(sources.globs.assets)
.pipe(gulp.dest(root + targets.assets))
);
// Copies all the less files related to the preview into their folder
//these are not pre-processed as preview has its own less combiler client side
stream.add(
gulp.src("src/canvasdesigner/editors/*.less")
.pipe(gulp.dest(root + targets.assets + "/less"))
);
// Todo: check if we need these fileSize
stream.add(
gulp.src("src/views/propertyeditors/grid/config/*.*")
.pipe(gulp.dest(root + targets.views + "/propertyeditors/grid/config"))
);
stream.add(
gulp.src("src/views/dashboard/default/*.jpg")
.pipe(gulp.dest(root + targets.views + "/dashboard/default"))
);
return stream;
});
/**************************
* Copies all angular JS files into their seperate umbraco.*.js file
**************************/
gulp.task('js', function () {
//we run multiple streams, so merge them all together
var stream = new MergeStream();
stream.add(
gulp.src(sources.globs.js)
.pipe(gulp.dest(root + targets.js))
);
_.forEach(sources.js, function (group) {
stream.add (processJs(group.files, group.out) );
});
return stream;
});
gulp.task('less', function () {
var stream = new MergeStream();
_.forEach(sources.less, function (group) {
stream.add( processLess(group.files, group.out) );
});
return stream;
});
gulp.task('views', function () {
var stream = new MergeStream();
_.forEach(sources.views, function (group) {
console.log("copying " + group.files + " to " + root + targets.views + group.folder)
stream.add (
gulp.src(group.files)
.pipe( gulp.dest(root + targets.views + group.folder) )
);
});
return stream;
});
gulp.task('watch', function () {
var stream = new MergeStream();
var watchInterval = 500;
//Setup a watcher for all groups of javascript files
_.forEach(sources.js, function (group) {
if(group.watch !== false){
stream.add(
watch(group.files, { ignoreInitial: true, interval: watchInterval }, function (file) {
console.info(file.path + " has changed, added to: " + group.out);
processJs(group.files, group.out);
})
);
}
});
stream.add(
//watch all less files and trigger the less task
watch(sources.globs.less, { ignoreInitial: true, interval: watchInterval }, function () {
gulp.run(['less']);
})
);
//watch all views - copy single file changes
stream.add(
watch(sources.globs.views, { interval: watchInterval })
.pipe(gulp.dest(root + targets.views))
);
//watch all app js files that will not be merged - copy single file changes
stream.add(
watch(sources.globs.js, { interval: watchInterval })
.pipe(gulp.dest(root + targets.js))
);
return stream;
});
/**************************
* Build Backoffice UI API documentation
**************************/
gulp.task('docs', [], function (cb) {
var options = {
html5Mode: false,
startPage: '/api',
title: "Umbraco Backoffice UI API Documentation",
dest: 'docs/api',
styles: ['docs/umb-docs.css'],
image: "https://our.umbraco.org/assets/images/logo.svg"
}
return gulpDocs.sections({
api: {
glob: ['src/common/**/*.js', 'docs/src/api/**/*.ngdoc'],
api: true,
title: 'API Documentation'
}
})
.pipe(gulpDocs.process(options))
.pipe(gulp.dest('docs/api'));
cb();
});
gulp.task('connect:docs', function (cb) {
connect.server({
root: 'docs/api',
livereload: true,
fallback: 'docs/api/index.html',
port: 8880
});
cb();
});
gulp.task('open:docs', function (cb) {
var options = {
uri: 'http://localhost:8880/index.html'
};
gulp.src(__filename)
.pipe(open(options));
cb();
});
/**************************
* Build tests
**************************/
// Karma test
gulp.task('test:unit', function() {
new karmaServer({
configFile: __dirname + "/test/config/karma.conf.js",
keepalive: true
})
.start();
});
gulp.task('test:e2e', function() {
new karmaServer({
configFile: __dirname + "/test/config/e2e.js",
keepalive: true
})
.start();
});
@@ -193,10 +193,10 @@
// Reset container width
// Required here as we reset the width earlier on and the grid mixins don't override early enough
.navbar-static-top .container,
.navbar-static-top .container,
.navbar-fixed-top .container,
.navbar-fixed-bottom .container {
#grid > .core > .span(@gridColumns);
.navbar-fixed-bottom .container {
width: (@gridColumnWidth * @gridColumns) + (@gridGutterWidth * (@gridColumns - 1));
}
// Fixed to top
+29 -32
View File
@@ -6,7 +6,7 @@
"license": "MIT",
"repository": {
"type": "git",
"url": "git@github.com:umbraco/umbraco-cms.git"
"url": "https://github.com/umbraco/Umbraco-CMS.git"
},
"bugs": {
"url": "https://issues.umbraco.org"
@@ -14,38 +14,35 @@
"engines": {
"node": ">= 0.8.4"
},
"scripts": {
"install": "bower-installer",
"test": "karma start test/config/karma.conf.js --singlerun",
"build": "gulp"
},
"dependencies": {},
"devDependencies": {
"autoprefixer-core": "~5.2.1",
"bower": "^1.4.1",
"eslint": "^0.23.0",
"eslint-plugin-angular": "0.0.13",
"grunt": "~0.4.0",
"grunt-bower": "^0.19.0",
"grunt-bower-install-simple": "^1.1.3",
"grunt-contrib-clean": "~0.4.0",
"grunt-contrib-concat": "~0.1.3",
"grunt-contrib-connect": "~0.3.0",
"grunt-contrib-copy": "~0.7.0",
"grunt-contrib-jshint": "~0.2.0",
"grunt-contrib-uglify": "~0.1.1",
"grunt-contrib-watch": "~0.3.1",
"grunt-eslint": "^15.0.0",
"grunt-html2js": "~0.1.0",
"grunt-hustler": "^4.0.6",
"grunt-karma": "~0.5",
"grunt-ngdocs": "~0.1.2",
"grunt-open": "~0.2.0",
"grunt-postcss": "~0.6.0",
"grunt-recess": "~0.3",
"karma": "~0.9",
"karma-chrome-launcher": "0.0.2",
"karma-coffee-preprocessor": "0.0.1",
"karma-firefox-launcher": "0.0.2",
"karma-jasmine": "0.0.1",
"karma-phantomjs-launcher": "0.0.2",
"karma-requirejs": "0.0.1",
"karma-script-launcher": "0.0.1",
"phantomjs": "~1.9.1-0"
"autoprefixer": "^6.5.0",
"bower-installer": "^1.2.0",
"cssnano": "^3.7.6",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.0",
"gulp-connect": "^5.0.0",
"gulp-less": "^3.1.0",
"gulp-ngdocs": "^0.3.0",
"gulp-open": "^2.0.0",
"gulp-postcss": "^6.2.0",
"gulp-rename": "^1.2.2",
"gulp-sort": "^2.0.0",
"gulp-watch": "^4.3.10",
"gulp-wrap": "^0.13.0",
"gulp-wrap-js": "^0.4.1",
"jasmine-core": "2.5.2",
"karma": "^1.7.0",
"karma-jasmine": "^1.1.0",
"karma-phantomjs-launcher": "^1.0.4",
"less": "^2.6.1",
"lodash": "^4.16.3",
"merge-stream": "^1.0.1",
"run-sequence": "^2.1.0"
}
}
@@ -11,8 +11,8 @@ LazyLoad.js([
'../js/umbraco.security.js',
'../ServerVariables',
'../lib/spectrum/spectrum.js',
'../js/canvasdesigner.panel.js',
'../js/umbraco.canvasdesigner.js',
'../js/canvasdesigner.panel.js'
], function () {
jQuery(document).ready(function () {
angular.bootstrap(document, ['Umbraco.canvasdesigner']);
@@ -1,7 +1,7 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Umbraco Canvas Designer</title>
<title>Umbraco Preview</title>
<link href="../assets/css/canvasdesigner.css" type="text/css" rel="stylesheet" />
<link href="../lib/spectrum/spectrum.css" type="text/css" rel="stylesheet" />
<link href="../lib/jquery-ui/jquery-ui-1.10.4.custom.min.css" type="text/css" rel="stylesheet" />
@@ -141,9 +141,7 @@ function formHelper(angularHelper, serverValidationManager, $timeout, notificati
dialogService.ysodDialog(err);
}
}
else {
dialogService.ysodDialog(err);
}
},
/**
@@ -87,6 +87,7 @@ function tinyMceService(dialogService, $log, imageHelper, $http, $timeout, macro
editor.addButton('umbmediapicker', {
icon: 'custom icon-picture',
tooltip: 'Media Picker',
stateSelector: 'img',
onclick: function () {
var selectedElm = editor.selection.getNode(),
@@ -0,0 +1 @@
angular.module('umbraco.install', []);
@@ -125,7 +125,7 @@ body {
@media (max-width: 500px) {
#search-form .form-search {
width: ~"(calc(~'100%' - ~'80px'))";
width: calc(100% - 80px);
}
}
@@ -1,4 +1,6 @@
@import "helveticons.less";
/******* font-face *******/
@font-face {
@@ -14,7 +16,7 @@ body {
overflow: hidden;
height: 100%;
width: 100%;
width: ~"(calc(~'100%' - ~'80px'))"; // 80px is the fixed left menu for toggling the different browser sizes
width: calc(~"100% - 80px"); // 80px is the fixed left menu for toggling the different browser sizes
position: absolute;
padding: 0;
margin: 0;
@@ -2,7 +2,7 @@
position: fixed;
overflow: hidden;
background: @white;
z-index: 996660;
z-index: 7500;
animation: fadeIn 0.2s;
box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
}
@@ -155,7 +155,7 @@
@media (max-width: 500px) {
.umb-overlay.umb-overlay-left {
margin-left: 41px;
width: ~"(calc(~'100%' - ~'41px'))";
width: calc(100% - 41px);
}
}
@@ -6,7 +6,7 @@
left: 0;
width: 100%;
height: 100%;
z-index: 999;
z-index: 5000;
display: flex;
align-items: center;
justify-content: center;
@@ -329,7 +329,7 @@ a.umb-package-details__back-link {
.umb-package-details__main-content {
flex: 1 1 auto;
margin-right: 40px;
width: ~"(calc(~'100%' - ~'@{sidebarwidth}' - ~'40px'))"; // Make sure that the main content area doesn't gets affected by inline styling
width: calc(~'100%' - ~'@{sidebarwidth}' - ~'40px'); // Make sure that the main content area doesn't gets affected by inline styling
}
.umb-package-details__sidebar {
@@ -356,7 +356,7 @@
.umb-panel-header-content-wrapper {
display: flex;
flex-direction: column;
height: 100px;
height: 99px;
padding: 0 20px;
}
@@ -126,7 +126,7 @@ ul.sections li.help {
bottom: 0;
left: 0;
display: block;
width: ~"(calc(~'100%' - ~'5px'))"; //subtract 4px orange border + 1px border-right for sections
width: calc(100% - 5px); //subtract 4px orange border + 1px border-right for sections
}
ul.sections li.help a {
@@ -187,6 +187,7 @@
<i class="icon icon-navigation" ng-if="!property.inherited"></i>
<span class="umb-group-builder__property-meta-label">{{ property.label }}</span>
<span class="umb-group-builder__property-meta-alias">({{ property.alias }})</span>
<span ng-show="sortingMode"><input name="propertySortOrder" type="number" class="umb-group-builder__group-sort-value umb-editor-tiny" ng-model="property.sortOrder" ng-disabled="property.inherited" /></span>
</div>
</div>
@@ -190,6 +190,15 @@ function ContentEditController($scope, $rootScope, $routeParams, $q, $timeout, $
$scope.page.buttonGroupState = "success";
}, function (err) {
$scope.page.buttonGroupState = "error";
$scope.busy = false;
//show any notifications
if (angular.isArray(err.data.notifications)) {
for (var i = 0; i < err.data.notifications.length; i++) {
notificationsService.showNotification(err.data.notifications[i]);
}
}
});
}
@@ -1,5 +1,7 @@
module.exports = function(karma) {
karma.configure({
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../..',
@@ -7,40 +9,36 @@ module.exports = function(karma) {
// list of files / patterns to load in the browser
files: [
'lib/../build/belle/lib/jquery/jquery.min.js',
'lib/angular/1.1.5/angular.js',
'lib/angular/1.1.5/angular-cookies.min.js',
'lib/angular/1.1.5/angular-mocks.js',
'lib/angular/angular-ui-sortable.js',
/*
For angular 1.2:
'lib/angular/1.2/angular.js',
'lib/angular/1.2/angular-route.min.js',
'lib/angular/1.2/angular-touch.min.js',
'lib/angular/1.2/angular-cookies.min.js',
'lib/angular/1.2/angular-animate.min.js',
'lib/angular/1.2/angular-mocks.js',*/
'lib/../build/belle/lib/underscore/underscore-min.js',
'lib/../build/belle/lib/moment/moment-with-locales.js',
'lib/umbraco/Extensions.js',
'lib/../build/belle/lib/rgrove-lazyload/lazyload.js',
'lib/../build/belle/lib/angular-local-storage/angular-local-storage.min.js',
//libraries
'lib-bower/jquery/jquery.min.js',
'lib/angular/1.1.5/angular.js',
'lib/angular/1.1.5/angular-cookies.min.js',
'lib/angular/1.1.5/angular-mocks.js',
'lib/angular/angular-ui-sortable.js',
'lib-bower/underscore/underscore-min.js',
'lib-bower/moment/moment-with-locales.js',
'lib/umbraco/Extensions.js',
'lib-bower/rgrove-lazyload/lazyload.js',
'lib-bower//angular-local-storage/angular-local-storage.min.js',
'test/config/app.unit.js',
'src/common/mocks/umbraco.servervariables.js',
//app bootstrap and loader
'test/config/app.unit.js',
'src/common/directives/*.js',
'src/common/filters/*.js',
'src/common/services/*.js',
'src/common/security/*.js',
'src/common/resources/*.js',
'src/common/mocks/**/*.js',
'src/views/**/*.controller.js',
'test/unit/**/*.spec.js',
{pattern: 'lib/**/*.js', watched: true, served: true, included: false}
//application files
'src/common/directives/*.js',
'src/common/filters/*.js',
'src/common/services/*.js',
'src/common/security/*.js',
'src/common/resources/*.js',
'src/views/**/*.controller.js',
//mocked data and routing
'src/common/mocks/umbraco.servervariables.js',
'src/common/mocks/**/*.js',
//tests
'test/unit/**/*.spec.js'
],
// list of files to exclude
@@ -66,7 +64,7 @@ module.exports = function(karma) {
// level of logging
// possible values: karma.LOG_DISABLE || karma.LOG_ERROR || karma.LOG_WARN || karma.LOG_INFO || karma.LOG_DEBUG
// CLI --log-level debug
logLevel: karma.LOG_INFO,
logLevel: config.LOG_WARN,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
@@ -83,9 +81,10 @@ module.exports = function(karma) {
// CLI --browsers Chrome,Firefox,Safari
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 5000,
// allow waiting a bit longer, some machines require this
browserNoActivityTimeout: 100000, // default 10,000ms
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
@@ -94,7 +93,7 @@ module.exports = function(karma) {
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
plugins: [
'karma-jasmine',
'karma-phantomjs-launcher'
@@ -42,7 +42,7 @@ describe('edit content controller tests', function () {
it('it should have an content object', function() {
//controller should have a content object
expect(scope.content).toNotBe(undefined);
expect(scope.content).not.toBeUndefined();
//if should be the same as the routeParams defined one
expect(scope.content.id).toBe(1234);
@@ -41,7 +41,7 @@ describe('edit media controller tests', function () {
it('it should have an media object', function() {
//controller should have a content object
expect(scope.content).toNotBe(undefined);
expect(scope.content).not.toBeUndefined();
//if should be the same as the routeParams defined one
expect(scope.content.id).toBe(1234);
@@ -59,19 +59,19 @@ describe('Content picker controller tests', function () {
};
it('should define the default properties on construction', function () {
expect(scope.model.value).toNotBe(undefined);
expect(scope.model.value).not.toBeUndefined();
});
it("should populate scope.renderModel", function(){
expect(scope.renderModel).toNotBe(undefined);
expect(scope.renderModel).not.toBeUndefined();
expect(scope.renderModel.length).toBe(3);
});
it("Each rendermodel item should contain name, id and icon", function(){
var item = scope.renderModel[0];
expect(item.name).toNotBe(undefined);
expect(item.name).not.toBeUndefined();
expect(item.id).toBe(1233);
expect(item.icon).toNotBe(undefined);
expect(item.icon).not.toBeUndefined();
});
it("Removing an item should update renderModel, ids and model.value", function(){
@@ -18,14 +18,14 @@ describe('Assets service tests', function () {
it('Loads a javascript file', function () {
var loaded = false;
runs( function(){
assetsService.loadJs("lib/umbraco/NamespaceManager.js").then(function(){
expect(Umbraco.Sys).toNotBe(undefined);
});
});
runs(function(){
expect(Umbraco.Sys).toNotBe(undefined);
});
// runs( function(){
// assetsService.loadJs("lib/umbraco/NamespaceManager.js").then(function(){
// expect(Umbraco.Sys).toNotBe(undefined);
// });
// });
// runs(function(){
// expect(Umbraco.Sys).toNotBe(undefined);
// });
});
});
});
@@ -36,7 +36,7 @@ describe('content factory tests', function () {
$rootScope.$digest();
$httpBackend.flush();
expect(doc).toNotBe(undefined);
expect(doc).not.toBeUndefined();
expect(doc.id).toBe(1234);
});

Some files were not shown because too many files have changed in this diff Show More