From 9796b30bbb69706eafcd6aa0bf84927fa435e528 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Jan 2014 11:02:24 +1100 Subject: [PATCH 01/71] Fixes: U4-4104 Using strongly typed Html.Action with a PluginController causes exception --- src/Umbraco.Web/HtmlHelperRenderExtensions.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs index 6c4967d59a..e10a89769c 100644 --- a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs +++ b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs @@ -181,7 +181,14 @@ namespace Umbraco.Web if (!metaData.AreaName.IsNullOrWhiteSpace()) { //set the area to the plugin area - routeVals.Add("area", metaData.AreaName); + if (routeVals.ContainsKey("area")) + { + routeVals["area"] = metaData.AreaName; + } + else + { + routeVals.Add("area", metaData.AreaName); + } } return htmlHelper.Action(actionName, metaData.ControllerName, routeVals); From 7da41594fd3b84c4157afd2aca16134b668e215e Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Jan 2014 11:27:44 +1100 Subject: [PATCH 02/71] re-publicizes member services, fixes: U4-4102 Un-obsolete ContentService.Publish --- src/Umbraco.Core/Services/ContentService.cs | 2 +- src/Umbraco.Core/Services/IContentService.cs | 1 - src/Umbraco.Core/Services/IMemberService.cs | 2 +- src/Umbraco.Core/Services/IMembershipMemberService.cs | 4 ++-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/Umbraco.Core/Services/ContentService.cs b/src/Umbraco.Core/Services/ContentService.cs index 29bb8c1711..b481db9825 100644 --- a/src/Umbraco.Core/Services/ContentService.cs +++ b/src/Umbraco.Core/Services/ContentService.cs @@ -622,10 +622,10 @@ namespace Umbraco.Core.Services /// The to publish /// Optional Id of the User issueing the publishing /// True if publishing succeeded, otherwise False - [Obsolete("Use PublishWithStatus instead, that method will provide more detailed information on the outcome")] public bool Publish(IContent content, int userId = 0) { var result = SaveAndPublishDo(content, userId); + LogHelper.Info("Call was made to ContentService.Publish, use PublishWithStatus instead since that method will provide more detailed information on the outcome"); return result.Success; } diff --git a/src/Umbraco.Core/Services/IContentService.cs b/src/Umbraco.Core/Services/IContentService.cs index 0a19deda6e..9acdef9bc3 100644 --- a/src/Umbraco.Core/Services/IContentService.cs +++ b/src/Umbraco.Core/Services/IContentService.cs @@ -249,7 +249,6 @@ namespace Umbraco.Core.Services /// The to publish /// Optional Id of the User issueing the publishing /// True if publishing succeeded, otherwise False - [Obsolete("Use PublishWithStatus instead, that method will provide more detailed information on the outcome")] bool Publish(IContent content, int userId = 0); /// diff --git a/src/Umbraco.Core/Services/IMemberService.cs b/src/Umbraco.Core/Services/IMemberService.cs index 87c15573c6..05bcafba38 100644 --- a/src/Umbraco.Core/Services/IMemberService.cs +++ b/src/Umbraco.Core/Services/IMemberService.cs @@ -8,7 +8,7 @@ namespace Umbraco.Core.Services /// /// Defines the MemberService, which is an easy access to operations involving (umbraco) members. /// - internal interface IMemberService : IMembershipMemberService + public interface IMemberService : IMembershipMemberService { /// /// Checks if a member with the id exists diff --git a/src/Umbraco.Core/Services/IMembershipMemberService.cs b/src/Umbraco.Core/Services/IMembershipMemberService.cs index 026615ef11..01fa2954f0 100644 --- a/src/Umbraco.Core/Services/IMembershipMemberService.cs +++ b/src/Umbraco.Core/Services/IMembershipMemberService.cs @@ -13,7 +13,7 @@ namespace Umbraco.Core.Services /// /// Idea is to have this is an isolated interface so that it can be easily 'replaced' in the membership provider impl. /// - internal interface IMembershipMemberService : IMembershipMemberService + public interface IMembershipMemberService : IMembershipMemberService { IMember CreateMember(string email, string username, string password, IMemberType memberType); } @@ -24,7 +24,7 @@ namespace Umbraco.Core.Services /// /// Idea is to have this is an isolated interface so that it can be easily 'replaced' in the membership provider impl. /// - internal interface IMembershipMemberService : IService + public interface IMembershipMemberService : IService where T : class, IMembershipUser { /// From 3f8b3031c22b91d8478e9a9518e5c7ccadba30ca Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Jan 2014 11:57:33 +1100 Subject: [PATCH 03/71] completes: U4-3996 Fix EditUser to use the membership provider properly, U4-3997 Fix EditMember to use the membership provider properly --- src/Umbraco.Core/Models/Membership/IUser.cs | 2 +- .../Models/Membership/IUserType.cs | 2 +- .../Security/IUsersMembershipProvider.cs | 10 ++++ .../Security/MembershipProviderExtensions.cs | 10 ++++ .../Security/UmbracoMembershipProviderBase.cs | 1 - .../Services/IMembershipUserService.cs | 2 +- src/Umbraco.Core/Umbraco.Core.csproj | 1 + .../Providers/MembersMembershipProvider.cs | 2 +- .../UmbracoServiceMembershipProvider.cs | 2 +- .../Providers/UsersMembershipProvider.cs | 3 +- .../umbraco/editContent.aspx.cs | 2 - .../umbraco/login.aspx.cs | 47 +++++++++++++------ .../umbraco/members/EditMember.aspx.cs | 13 +++-- .../umbraco/users/EditUser.aspx.cs | 17 +++---- .../UsersMembershipProvider.cs | 2 +- 15 files changed, 76 insertions(+), 40 deletions(-) create mode 100644 src/Umbraco.Core/Security/IUsersMembershipProvider.cs diff --git a/src/Umbraco.Core/Models/Membership/IUser.cs b/src/Umbraco.Core/Models/Membership/IUser.cs index f45f4ebea6..b15e5845e5 100644 --- a/src/Umbraco.Core/Models/Membership/IUser.cs +++ b/src/Umbraco.Core/Models/Membership/IUser.cs @@ -7,7 +7,7 @@ namespace Umbraco.Core.Models.Membership /// Defines the interface for a /// /// Will be left internal until a proper Membership implementation is part of the roadmap - internal interface IUser : IMembershipUser, IProfile + public interface IUser : IMembershipUser, IProfile { new object Id { get; set; } diff --git a/src/Umbraco.Core/Models/Membership/IUserType.cs b/src/Umbraco.Core/Models/Membership/IUserType.cs index aa2d882e4c..fe678afd2b 100644 --- a/src/Umbraco.Core/Models/Membership/IUserType.cs +++ b/src/Umbraco.Core/Models/Membership/IUserType.cs @@ -5,7 +5,7 @@ using Umbraco.Core.Persistence.Mappers; namespace Umbraco.Core.Models.Membership { - internal interface IUserType : IAggregateRoot + public interface IUserType : IAggregateRoot { /// /// The user type alias diff --git a/src/Umbraco.Core/Security/IUsersMembershipProvider.cs b/src/Umbraco.Core/Security/IUsersMembershipProvider.cs new file mode 100644 index 0000000000..8f2dbf8b00 --- /dev/null +++ b/src/Umbraco.Core/Security/IUsersMembershipProvider.cs @@ -0,0 +1,10 @@ +namespace Umbraco.Core.Security +{ + /// + /// A marker interface used internally to identify Umbraco built-in Users membership providers + /// + internal interface IUsersMembershipProvider + { + + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/Security/MembershipProviderExtensions.cs b/src/Umbraco.Core/Security/MembershipProviderExtensions.cs index 85db27ac97..747f6c42c0 100644 --- a/src/Umbraco.Core/Security/MembershipProviderExtensions.cs +++ b/src/Umbraco.Core/Security/MembershipProviderExtensions.cs @@ -10,6 +10,16 @@ namespace Umbraco.Core.Security { internal static class MembershipProviderExtensions { + /// + /// Returns true if the provider specified is a built-in Umbraco users provider + /// + /// + /// + public static bool IsUmbracoUsersProvider(this MembershipProvider membershipProvider) + { + return (membershipProvider is IUsersMembershipProvider); + } + /// /// Returns true if the provider specified is a built-in Umbraco membership provider /// diff --git a/src/Umbraco.Core/Security/UmbracoMembershipProviderBase.cs b/src/Umbraco.Core/Security/UmbracoMembershipProviderBase.cs index 6cbd12f448..12ca2b4b4a 100644 --- a/src/Umbraco.Core/Security/UmbracoMembershipProviderBase.cs +++ b/src/Umbraco.Core/Security/UmbracoMembershipProviderBase.cs @@ -3,7 +3,6 @@ using System.Web.Security; namespace Umbraco.Core.Security { - /// /// A base membership provider class for umbraco providers /// diff --git a/src/Umbraco.Core/Services/IMembershipUserService.cs b/src/Umbraco.Core/Services/IMembershipUserService.cs index c79607edab..75382e5c46 100644 --- a/src/Umbraco.Core/Services/IMembershipUserService.cs +++ b/src/Umbraco.Core/Services/IMembershipUserService.cs @@ -8,7 +8,7 @@ namespace Umbraco.Core.Services /// /// Idea is to have this is an isolated interface so that it can be easily 'replaced' in the membership provider impl. /// - internal interface IMembershipUserService : IMembershipMemberService + public interface IMembershipUserService : IMembershipMemberService { IUser CreateMember(string username, string email, string password, IUserType userType); diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 09ab59e054..0c7025fe00 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -740,6 +740,7 @@ + diff --git a/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs index 9ab6b90bd0..84de8f3367 100644 --- a/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs @@ -17,7 +17,7 @@ namespace Umbraco.Web.Security.Providers /// /// Custom Membership Provider for Umbraco Members (User authentication for Frontend applications NOT umbraco CMS) /// - internal class MembersMembershipProvider : UmbracoServiceMembershipProvider + public class MembersMembershipProvider : UmbracoServiceMembershipProvider { public MembersMembershipProvider() : this(ApplicationContext.Current.Services.MemberService) diff --git a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs index 16ea1e4393..28c3b930b7 100644 --- a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs @@ -17,7 +17,7 @@ namespace Umbraco.Web.Security.Providers /// /// Abstract Membership Provider that users any implementation of IMembershipMemberService{TEntity} service /// - internal abstract class UmbracoServiceMembershipProvider : UmbracoMembershipProviderBase + public abstract class UmbracoServiceMembershipProvider : UmbracoMembershipProviderBase where T : IMembershipMemberService where TEntity : class, IMembershipUser { diff --git a/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs index 23fe07b02b..d8bfceba43 100644 --- a/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs @@ -5,6 +5,7 @@ using System.Text; using System.Web.Security; using Umbraco.Core; using Umbraco.Core.Models.Membership; +using Umbraco.Core.Security; using Umbraco.Core.Services; namespace Umbraco.Web.Security.Providers @@ -12,7 +13,7 @@ namespace Umbraco.Web.Security.Providers /// /// Custom Membership Provider for Umbraco Users (User authentication for Umbraco Backend CMS) /// - internal class UsersMembershipProvider : UmbracoServiceMembershipProvider + public class UsersMembershipProvider : UmbracoServiceMembershipProvider, IUsersMembershipProvider { public UsersMembershipProvider() diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/editContent.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/editContent.aspx.cs index 91c6a8a4e0..3af648c142 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/editContent.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/editContent.aspx.cs @@ -365,8 +365,6 @@ namespace umbraco.cms.presentation _unPublish.Visible = false; _documentHasPublishedVersion = false; - //library.UnPublishSingleNode(_document.Id); - Current.ClientTools.SyncTree(_document.Path, true); ClientTools.ShowSpeechBubble(speechBubbleIcon.success, ui.Text("unpublish"), ui.Text("speechBubbles", "contentUnpublished")); diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs index 73a26c4494..36008e7fac 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.ComponentModel; +using System.Configuration.Provider; using System.Data; using System.Drawing; using System.Security; @@ -17,6 +18,7 @@ using Umbraco.Core.IO; using umbraco.cms.businesslogic.web; using System.Linq; using Umbraco.Core; +using Umbraco.Core.Security; namespace umbraco.cms.presentation { @@ -28,6 +30,19 @@ namespace umbraco.cms.presentation [Obsolete("This property is no longer used")] protected umbWindow treeWindow; + private MembershipProvider BackOfficeProvider + { + get + { + var provider = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider]; + if (provider == null) + { + throw new ProviderException("The membership provider " + UmbracoSettings.DefaultBackofficeProvider + " was not found"); + } + return provider; + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -35,9 +50,9 @@ namespace umbraco.cms.presentation // validate redirect url string redirUrl = Request["redir"]; - if (!String.IsNullOrEmpty(redirUrl)) + if (!string.IsNullOrEmpty(redirUrl)) { - validateRedirectUrl(redirUrl); + ValidateRedirectUrl(redirUrl); } } @@ -63,15 +78,18 @@ namespace umbraco.cms.presentation } - protected void Button1_Click(object sender, System.EventArgs e) + protected void Button1_Click(object sender, EventArgs e) { // Authenticate users by using the provider specified in umbracoSettings.config - if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].ValidateUser(lname.Text, passw.Text)) + if (BackOfficeProvider.ValidateUser(lname.Text, passw.Text)) { - if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is ActiveDirectoryMembershipProvider) - ActiveDirectoryMapping(lname.Text, Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(lname.Text, false).Email); + if (BackOfficeProvider.IsUmbracoUsersProvider() == false) + { + CustomProviderMapping(lname.Text, BackOfficeProvider.GetUser(lname.Text, false).Email); + } + - BusinessLogic.User u = new User(lname.Text); + var u = new User(lname.Text); doLogin(u); // Check if the user should be redirected to live editing @@ -97,8 +115,7 @@ namespace umbraco.cms.presentation } else if (u.DefaultToLiveEditing) { - throw new UserAuthorizationException( - "Canvas editing isn't enabled. It can be enabled via the UmbracoSettings.config"); + throw new UserAuthorizationException("Canvas editing isn't enabled. It can be enabled via the UmbracoSettings.config"); } if (hf_height.Value != "undefined") @@ -111,7 +128,7 @@ namespace umbraco.cms.presentation if (string.IsNullOrEmpty(redirUrl)) Response.Redirect("umbraco.aspx"); - else if (validateRedirectUrl(redirUrl)) + else if (ValidateRedirectUrl(redirUrl)) { Response.Redirect(redirUrl, true); } @@ -122,9 +139,9 @@ namespace umbraco.cms.presentation } } - private bool validateRedirectUrl(string url) + private static bool ValidateRedirectUrl(string url) { - if (!isUrlLocalToHost(url)) + if (IsUrlLocalToHost(url) == false) { LogHelper.Info(String.Format("Security warning: Login redirect was attempted to a site at another domain: '{0}'", url)); @@ -137,7 +154,7 @@ namespace umbraco.cms.presentation return true; } - private bool isUrlLocalToHost(string url) + private static bool IsUrlLocalToHost(string url) { if (String.IsNullOrEmpty(url)) { @@ -158,11 +175,11 @@ namespace umbraco.cms.presentation } /// - /// Maps active directory account to umbraco user account + /// Maps a custom provider's information to an umbraco user account /// /// Name of the login. /// Email address of the user - private void ActiveDirectoryMapping(string loginName, string email) + private static void CustomProviderMapping(string loginName, string email) { // Password is not copied over because it is stored in active directory for security! // The user is create with default access to content and as a writer user type diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs index 600b769c6a..0154b77382 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs @@ -68,7 +68,7 @@ namespace umbraco.cms.presentation.members { _document = new Member(int.Parse(Request.QueryString["id"])); _member = Membership.GetUser(_document.LoginName, false); - _contentControl = new ContentControl(_document, controls.ContentControl.publishModes.NoPublish, "TabView1"); + _contentControl = new ContentControl(_document, ContentControl.publishModes.NoPublish, "TabView1"); _contentControl.Width = Unit.Pixel(666); _contentControl.Height = Unit.Pixel(666); @@ -92,13 +92,13 @@ namespace umbraco.cms.presentation.members MemberLoginNameVal.EnableClientScript = false; MemberLoginNameVal.Display = ValidatorDisplay.Dynamic; - MemberLoginNameExistCheck.ErrorMessage = ui.Text("errorHandling", "errorExistsWithoutTab", "Login Name", BasePages.UmbracoEnsuredPage.CurrentUser); + MemberLoginNameExistCheck.ErrorMessage = ui.Text("errorHandling", "errorExistsWithoutTab", "Login Name", CurrentUser); MemberLoginNameExistCheck.EnableClientScript = false; MemberLoginNameExistCheck.ValidateEmptyText = false; MemberLoginNameExistCheck.ControlToValidate = MemberLoginNameTxt.ID; MemberLoginNameExistCheck.ServerValidate += MemberLoginNameExistCheck_ServerValidate; - MemberEmailExistCheck.ErrorMessage = ui.Text("errorHandling", "errorExistsWithoutTab", "E-mail", BasePages.UmbracoEnsuredPage.CurrentUser); + MemberEmailExistCheck.ErrorMessage = ui.Text("errorHandling", "errorExistsWithoutTab", "E-mail", CurrentUser); MemberEmailExistCheck.EnableClientScript = false; MemberEmailExistCheck.ValidateEmptyText = false; MemberEmailExistCheck.ControlToValidate = MemberEmail.ID; @@ -116,7 +116,7 @@ namespace umbraco.cms.presentation.members var menuSave = m_MemberShipPanel.Menu.NewImageButton(); menuSave.ID = m_MemberShipPanel.ID + "_save"; menuSave.ImageUrl = SystemDirectories.Umbraco + "/images/editor/save.gif"; - menuSave.Click += new ImageClickEventHandler(MenuSaveClick); + menuSave.Click += MenuSaveClick; menuSave.AltText = ui.Text("buttons", "save", null); _member = Membership.GetUser(Request.QueryString["id"], false); @@ -167,7 +167,7 @@ namespace umbraco.cms.presentation.members if (Membership.Provider.IsUmbracoMembershipProvider()) { _contentControl.tpProp.Controls.Add(p); - _contentControl.Save += new System.EventHandler(tmp_save); + _contentControl.Save += tmp_save; } else { @@ -244,8 +244,7 @@ namespace umbraco.cms.presentation.members { var membershipHelper = new MembershipHelper(); //set the writable properties that we are editing - membershipHelper.UpdateMember(membershipUser, Membership.Provider, - MemberEmail.Text.Trim()); + membershipHelper.UpdateMember(membershipUser, Membership.Provider, MemberEmail.Text.Trim()); } private void UpdateRoles(MembershipUser membershipUser) diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs index 95b2e891e7..b85835788d 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs @@ -10,6 +10,7 @@ using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Xml; using Umbraco.Core.Logging; +using Umbraco.Core.Security; using Umbraco.Web; using Umbraco.Web.Models; using Umbraco.Web.Security; @@ -36,7 +37,7 @@ namespace umbraco.cms.presentation.user { public EditUser() { - CurrentApp = BusinessLogic.DefaultApps.users.ToString(); + CurrentApp = DefaultApps.users.ToString(); } protected HtmlTable macroProperties; protected TextBox uname = new TextBox(); @@ -51,8 +52,8 @@ namespace umbraco.cms.presentation.user protected CheckBox DefaultToLiveEditing = new CheckBox(); - protected controls.ContentPicker mediaPicker = new umbraco.controls.ContentPicker(); - protected controls.ContentPicker contentPicker = new umbraco.controls.ContentPicker(); + protected ContentPicker mediaPicker = new ContentPicker(); + protected ContentPicker contentPicker = new ContentPicker(); protected TextBox cName = new TextBox(); protected CheckBox cFulltree = new CheckBox(); @@ -60,8 +61,8 @@ namespace umbraco.cms.presentation.user protected DropDownList cDescription = new DropDownList(); protected DropDownList cCategories = new DropDownList(); protected DropDownList cExcerpt = new DropDownList(); - protected controls.ContentPicker cMediaPicker = new umbraco.controls.ContentPicker(); - protected controls.ContentPicker cContentPicker = new umbraco.controls.ContentPicker(); + protected ContentPicker cMediaPicker = new ContentPicker(); + protected ContentPicker cContentPicker = new ContentPicker(); protected CustomValidator sectionValidator = new CustomValidator(); protected Pane pp = new Pane(); @@ -167,7 +168,7 @@ namespace umbraco.cms.presentation.user //This is a hack to allow the admin to change a user's password to whatever they want - this will only work if we are using the // default umbraco membership provider. // See the notes below in the ChangePassword method. - if (BackOfficeProvider is UsersMembershipProvider) + if (BackOfficeProvider.IsUmbracoUsersProvider()) { passwordChanger.ShowOldPassword = false; } @@ -436,7 +437,7 @@ namespace umbraco.cms.presentation.user var changePasswordModel = passwordChangerControl.ChangingPasswordModel; // Is it using the default membership provider - if (BackOfficeProvider is UsersMembershipProvider) + if (BackOfficeProvider.IsUmbracoUsersProvider()) { //This is a total hack so that an admin can change the password without knowing the previous one // we do this by simply passing in the already stored hashed/encrypted password in the database - @@ -604,6 +605,6 @@ namespace umbraco.cms.presentation.user /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// - protected global::umbraco.uicontrols.TabView UserTabs; + protected TabView UserTabs; } } diff --git a/src/umbraco.providers/UsersMembershipProvider.cs b/src/umbraco.providers/UsersMembershipProvider.cs index f5e9acf961..0c8c23854b 100644 --- a/src/umbraco.providers/UsersMembershipProvider.cs +++ b/src/umbraco.providers/UsersMembershipProvider.cs @@ -16,7 +16,7 @@ namespace umbraco.providers /// /// Custom Membership Provider for Umbraco Users (User authentication for Umbraco Backend CMS) /// - public class UsersMembershipProvider : MembershipProviderBase + public class UsersMembershipProvider : MembershipProviderBase, IUsersMembershipProvider { /// From 47974d49fef9fc5fad203550e586ef2891269d91 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Jan 2014 12:16:47 +1100 Subject: [PATCH 04/71] obsoletes old providers, creates new membership role provider stub --- .../Security/Providers/MembersRoleProvider.cs | 65 +++++++++++++++++++ src/Umbraco.Web/Umbraco.Web.csproj | 1 + .../UsersMembershipProvider.cs | 1 + src/umbraco.providers/UsersRoleProvider.cs | 13 ++-- .../members/UmbracoMembershipProvider.cs | 2 +- .../members/UmbracoRoleProvider.cs | 16 +++-- 6 files changed, 85 insertions(+), 13 deletions(-) create mode 100644 src/Umbraco.Web/Security/Providers/MembersRoleProvider.cs diff --git a/src/Umbraco.Web/Security/Providers/MembersRoleProvider.cs b/src/Umbraco.Web/Security/Providers/MembersRoleProvider.cs new file mode 100644 index 0000000000..50e84a9afe --- /dev/null +++ b/src/Umbraco.Web/Security/Providers/MembersRoleProvider.cs @@ -0,0 +1,65 @@ +using System.Web.Security; + +namespace Umbraco.Web.Security.Providers +{ + public class MembersRoleProvider : RoleProvider + { + private string _applicationName; + + public override bool IsUserInRole(string username, string roleName) + { + throw new System.NotImplementedException(); + } + + public override string[] GetRolesForUser(string username) + { + throw new System.NotImplementedException(); + } + + public override void CreateRole(string roleName) + { + throw new System.NotImplementedException(); + } + + public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) + { + throw new System.NotImplementedException(); + } + + public override bool RoleExists(string roleName) + { + throw new System.NotImplementedException(); + } + + public override void AddUsersToRoles(string[] usernames, string[] roleNames) + { + throw new System.NotImplementedException(); + } + + public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) + { + throw new System.NotImplementedException(); + } + + public override string[] GetUsersInRole(string roleName) + { + throw new System.NotImplementedException(); + } + + public override string[] GetAllRoles() + { + throw new System.NotImplementedException(); + } + + public override string[] FindUsersInRole(string roleName, string usernameToMatch) + { + throw new System.NotImplementedException(); + } + + public override string ApplicationName + { + get { return _applicationName; } + set { _applicationName = value; } + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Web/Umbraco.Web.csproj b/src/Umbraco.Web/Umbraco.Web.csproj index 83d7ba6288..9295a21996 100644 --- a/src/Umbraco.Web/Umbraco.Web.csproj +++ b/src/Umbraco.Web/Umbraco.Web.csproj @@ -316,6 +316,7 @@ + diff --git a/src/umbraco.providers/UsersMembershipProvider.cs b/src/umbraco.providers/UsersMembershipProvider.cs index 0c8c23854b..ad03da826f 100644 --- a/src/umbraco.providers/UsersMembershipProvider.cs +++ b/src/umbraco.providers/UsersMembershipProvider.cs @@ -16,6 +16,7 @@ namespace umbraco.providers /// /// Custom Membership Provider for Umbraco Users (User authentication for Umbraco Backend CMS) /// + [Obsolete("This has been superceded by Umbraco.Web.Security.Providers.UsersMembershipProvider")] public class UsersMembershipProvider : MembershipProviderBase, IUsersMembershipProvider { diff --git a/src/umbraco.providers/UsersRoleProvider.cs b/src/umbraco.providers/UsersRoleProvider.cs index d6c451e8f0..e18dc0c7a1 100644 --- a/src/umbraco.providers/UsersRoleProvider.cs +++ b/src/umbraco.providers/UsersRoleProvider.cs @@ -12,10 +12,11 @@ namespace umbraco.providers /// /// Custom Roles Provider for Umbraco /// + [Obsolete("This is not used and no methods are implemented, it will be removed in future versions")] public class UsersRoleProvider : RoleProvider { #region - private string _ApplicationName; + private string _applicationName; #endregion #region Properties @@ -28,7 +29,7 @@ namespace umbraco.providers { get { - return _ApplicationName; + return _applicationName; } set { @@ -38,7 +39,7 @@ namespace umbraco.providers if (value.Length > 0x100) throw new ProviderException("Provider application name too long."); - _ApplicationName = value; + _applicationName = value; } } #endregion @@ -70,9 +71,9 @@ namespace umbraco.providers // Initialize the abstract base class. base.Initialize(name, config); - this._ApplicationName = config["applicationName"]; - if (string.IsNullOrEmpty(this._ApplicationName)) - this._ApplicationName = SecUtility.GetDefaultAppName(); + this._applicationName = config["applicationName"]; + if (string.IsNullOrEmpty(this._applicationName)) + this._applicationName = SecUtility.GetDefaultAppName(); } #endregion diff --git a/src/umbraco.providers/members/UmbracoMembershipProvider.cs b/src/umbraco.providers/members/UmbracoMembershipProvider.cs index c4c130b2c3..77ddfac649 100644 --- a/src/umbraco.providers/members/UmbracoMembershipProvider.cs +++ b/src/umbraco.providers/members/UmbracoMembershipProvider.cs @@ -29,7 +29,7 @@ namespace umbraco.providers.members /// /// Custom Membership Provider for Umbraco Members (User authentication for Frontend applications NOT umbraco CMS) /// - + [Obsolete("This has been superceded by Umbraco.Web.Security.Providers.MembersMembershipProvider")] public class UmbracoMembershipProvider : UmbracoMembershipProviderBase { public UmbracoMembershipProvider() diff --git a/src/umbraco.providers/members/UmbracoRoleProvider.cs b/src/umbraco.providers/members/UmbracoRoleProvider.cs index bbae8aabfa..bfb8863ed0 100644 --- a/src/umbraco.providers/members/UmbracoRoleProvider.cs +++ b/src/umbraco.providers/members/UmbracoRoleProvider.cs @@ -16,11 +16,15 @@ using System.Collections; namespace umbraco.providers.members { + /// + /// A role provider for members + /// + [Obsolete("This has been superceded by Umbraco.Web.Security.Providers.MembersRoleProvider")] public class UmbracoRoleProvider : RoleProvider { #region - private string _ApplicationName = Member.UmbracoRoleProviderName; + private string _applicationName = Member.UmbracoRoleProviderName; #endregion #region Properties @@ -31,7 +35,7 @@ namespace umbraco.providers.members /// The name of the application to store and retrieve role information for. public override string ApplicationName { get { - return _ApplicationName; + return _applicationName; } set { if (string.IsNullOrEmpty(value)) @@ -40,7 +44,7 @@ namespace umbraco.providers.members if (value.Length > 0x100) throw new ProviderException("Provider application name too long."); - _ApplicationName = value; + _applicationName = value; } } #endregion @@ -70,9 +74,9 @@ namespace umbraco.providers.members // Initialize the abstract base class. base.Initialize(name, config); - this._ApplicationName = config["applicationName"]; - if (string.IsNullOrEmpty(this._ApplicationName)) - this._ApplicationName = SecUtility.GetDefaultAppName(); + this._applicationName = config["applicationName"]; + if (string.IsNullOrEmpty(this._applicationName)) + this._applicationName = SecUtility.GetDefaultAppName(); } #endregion From fb9569d914e7ee442358a440f3a53f8126d48c0f Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Jan 2014 13:20:00 +1100 Subject: [PATCH 05/71] Fixes user membership providers to throw exceptions on duplicate emails when the provider is configured to not allow duplicates. --- .../UmbracoServiceMembershipProvider.cs | 12 +++- .../Providers/UsersMembershipProvider.cs | 8 +++ .../umbraco/users/EditUser.aspx.cs | 24 +++---- .../UsersMembershipProvider.cs | 68 +++++++++---------- 4 files changed, 63 insertions(+), 49 deletions(-) diff --git a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs index 28c3b930b7..b199b32f8b 100644 --- a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs @@ -456,9 +456,19 @@ namespace Umbraco.Web.Security.Providers if (m == null) { throw new ProviderException(string.Format("No member with the username '{0}' found", user.UserName)); - } + } + if (RequiresUniqueEmail && user.Email.Trim().IsNullOrWhiteSpace() == false) + { + int totalRecs; + var byEmail = MemberService.FindMembersByEmail(user.Email.Trim(), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact); + if (byEmail.Count(x => x.Id != m.Id) > 0) + { + throw new ProviderException(string.Format("A member with the email '{0}' already exists", user.Email)); + } + } m.Email = user.Email; + m.IsApproved = user.IsApproved; m.IsLockedOut = user.IsLockedOut; if (user.IsLockedOut) diff --git a/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs index d8bfceba43..e3ede8f6d8 100644 --- a/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs @@ -33,6 +33,14 @@ namespace Umbraco.Web.Security.Providers get { return "UsersMembershipProvider"; } } + /// + /// For backwards compatibility, this provider supports this option + /// + public override bool AllowManuallyChangingPassword + { + get { return true; } + } + protected override MembershipUser ConvertToMembershipUser(IUser entity) { //the provider user key is always the int id diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs index b85835788d..f8e2719e84 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/users/EditUser.aspx.cs @@ -340,7 +340,7 @@ namespace umbraco.cms.presentation.user channelInfo.HasMenu = true; ImageButton save = channelInfo.Menu.NewImageButton(); save.ImageUrl = SystemDirectories.Umbraco + "/images/editor/save.gif"; - save.Click += new ImageClickEventHandler(SaveUser_Click); + save.Click += SaveUser_Click; save.ID = "save"; if (!IsPostBack) { @@ -366,17 +366,17 @@ namespace umbraco.cms.presentation.user lname.Text = (user == null) ? u.LoginName : user.UserName; email.Text = (user == null) ? u.Email : user.Email; - // Prevent users from changing information if logged in through active directory membership provider - // active directory-mapped accounts have empty passwords by default... so set update user fields to read only - // this will not be a security issue because empty passwords are not allowed in membership provider. - // This might change in version 4.0 - if (string.IsNullOrEmpty(u.GetPassword())) - { - uname.ReadOnly = true; - lname.ReadOnly = true; - email.ReadOnly = true; - passw.Visible = false; - } + //// Prevent users from changing information if logged in through a custom provider + //// custom provider mapped accounts have empty passwords by default... so set update user fields to read only + //// this will not be a security issue because empty passwords are not allowed in membership provider. + //// This might change in version 4.0 + //if (string.IsNullOrEmpty(u.GetPassword())) + //{ + // uname.ReadOnly = true; + // lname.ReadOnly = true; + // email.ReadOnly = true; + // passw.Visible = false; + //} contentPicker.Value = u.StartNodeId.ToString(CultureInfo.InvariantCulture); mediaPicker.Value = u.StartMediaId.ToString(CultureInfo.InvariantCulture); diff --git a/src/umbraco.providers/UsersMembershipProvider.cs b/src/umbraco.providers/UsersMembershipProvider.cs index ad03da826f..6561482b89 100644 --- a/src/umbraco.providers/UsersMembershipProvider.cs +++ b/src/umbraco.providers/UsersMembershipProvider.cs @@ -43,7 +43,15 @@ namespace umbraco.providers { get { return true; } } - + + /// + /// For backwards compatibility, this provider supports this option + /// + public override bool AllowManuallyChangingPassword + { + get { return true; } + } + public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); @@ -63,42 +71,23 @@ namespace umbraco.providers /// /// true if the password was updated successfully; otherwise, false. /// - /// - /// During installation the application will not be configured, if this is the case and the 'default' password - /// is stored in the database then we will validate the user - this will allow for an admin password reset if required - /// protected override bool PerformChangePassword(string username, string oldPassword, string newPassword) { + //NOTE: due to backwards compatibilty reasons (and UX reasons), this provider doesn't care about the old password and + // allows simply setting the password manually so we don't really care about the old password. + // This is allowed based on the overridden AllowManuallyChangingPassword option. + var user = new User(username); + //encrypt/hash the new one + string salt; + var encodedPassword = EncryptOrHashNewPassword(newPassword, out salt); - if (ApplicationContext.Current.IsConfigured == false && oldPassword == "default" - || ValidateUser(username, oldPassword)) - { - var args = new ValidatePasswordEventArgs(username, newPassword, false); - OnValidatingPassword(args); - - if (args.Cancel) - { - if (args.FailureInformation != null) - throw args.FailureInformation; - throw new MembershipPasswordException("Change password canceled due to password validation failure."); - } - - var user = new User(username); - //encrypt/hash the new one - string salt; - var encodedPassword = EncryptOrHashNewPassword(newPassword, out salt); - - //Yes, it's true, this actually makes a db call to set the password - user.Password = FormatPasswordForStorage(encodedPassword, salt); - //call this just for fun. - user.Save(); - - return true; - } - - return false; + //Yes, it's true, this actually makes a db call to set the password + user.Password = FormatPasswordForStorage(encodedPassword, salt); + //call this just for fun. + user.Save(); + return true; } /// @@ -452,10 +441,19 @@ namespace umbraco.providers { var found = User.GetAllByLoginName(user.UserName, false).ToArray(); if (found == null || found.Any() == false) - throw new MembershipPasswordException("The supplied user is not found"); + { + throw new ProviderException("The supplied user is not found"); + } var m = found.First(); - + if (RequiresUniqueEmail && user.Email.Trim().IsNullOrWhiteSpace() == false) + { + var byEmail = User.getAllByEmail(user.Email, true); + if (byEmail.Count(x => x.Id != m.Id) > 0) + { + throw new ProviderException(string.Format("A member with the email '{0}' already exists", user.Email)); + } + } var typedUser = user as UsersMembershipUser; if (typedUser == null) @@ -471,8 +469,6 @@ namespace umbraco.providers //This keeps compatibility - even though this logic to update name and user type should not exist here User.Update(m.Id, typedUser.FullName.Trim(), typedUser.UserName, typedUser.Email, user.IsApproved == false, user.IsLockedOut, typedUser.UserType); } - - m.Save(); } From 9bd8d729fa6a9bd6f1b4cf00c7ea57cdb72bbd67 Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Jan 2014 14:07:18 +1100 Subject: [PATCH 06/71] publicizes user stuff, changes the IUser.Id to an int - no need for it to be an object and casted everywhere. Updates the login logic to perform the mapping logic for custom membership providers with an extension method. --- .../Models/Membership/IProfile.cs | 4 + src/Umbraco.Core/Models/Membership/IUser.cs | 2 +- src/Umbraco.Core/Models/Membership/User.cs | 12 ++- src/Umbraco.Core/Services/IUserService.cs | 2 +- src/Umbraco.Core/Services/UserService.cs | 3 +- .../Services/UserServiceExtensions.cs | 52 ++++++++++++ src/Umbraco.Core/Umbraco.Core.csproj | 1 + .../umbraco/login.aspx.cs | 83 +++++++++---------- 8 files changed, 109 insertions(+), 50 deletions(-) create mode 100644 src/Umbraco.Core/Services/UserServiceExtensions.cs diff --git a/src/Umbraco.Core/Models/Membership/IProfile.cs b/src/Umbraco.Core/Models/Membership/IProfile.cs index fbbff85e7d..749c3371b8 100644 --- a/src/Umbraco.Core/Models/Membership/IProfile.cs +++ b/src/Umbraco.Core/Models/Membership/IProfile.cs @@ -3,6 +3,10 @@ /// /// Defines the the Profile interface /// + /// + /// This interface is pretty useless but has been exposed publicly from 6.x so we're stuck with it. It would make more sense + /// if the Id was an int but since it's not people have to cast it to int all of the time! + /// public interface IProfile { object Id { get; set; } diff --git a/src/Umbraco.Core/Models/Membership/IUser.cs b/src/Umbraco.Core/Models/Membership/IUser.cs index b15e5845e5..ab9c02b1b2 100644 --- a/src/Umbraco.Core/Models/Membership/IUser.cs +++ b/src/Umbraco.Core/Models/Membership/IUser.cs @@ -9,7 +9,7 @@ namespace Umbraco.Core.Models.Membership /// Will be left internal until a proper Membership implementation is part of the roadmap public interface IUser : IMembershipUser, IProfile { - new object Id { get; set; } + new int Id { get; set; } int SessionTimeout { get; set; } int StartContentId { get; set; } diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index 52350b3748..b35fd04bba 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -19,7 +19,7 @@ namespace Umbraco.Core.Models.Membership /// [Serializable] [DataContract(IsReference = true)] - internal class User : TracksChangesEntityBase, IUser + public class User : TracksChangesEntityBase, IUser { public User(IUserType userType) { @@ -45,7 +45,7 @@ namespace Umbraco.Core.Models.Membership private readonly IUserType _userType; private bool _hasIdentity; - private object _id; + private int _id; private string _name; private Type _userTypeKey; private readonly List _addedSections; @@ -242,6 +242,12 @@ namespace Umbraco.Core.Models.Membership #region Implementation of IProfile + object IProfile.Id + { + get { return Id; } + set { Id = (int)value; } + } + [DataMember] public string Name { @@ -355,7 +361,7 @@ namespace Umbraco.Core.Models.Membership } [DataMember] - public object Id + public int Id { get { return _id; } set diff --git a/src/Umbraco.Core/Services/IUserService.cs b/src/Umbraco.Core/Services/IUserService.cs index 840cd9a685..a55bd4b771 100644 --- a/src/Umbraco.Core/Services/IUserService.cs +++ b/src/Umbraco.Core/Services/IUserService.cs @@ -7,7 +7,7 @@ namespace Umbraco.Core.Services /// /// Defines the UserService, which is an easy access to operations involving and eventually Users. /// - internal interface IUserService : IMembershipUserService + public interface IUserService : IMembershipUserService { /// /// Gets an IProfile by User Id. diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 5ac259cafb..8939101ac8 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Web.Security; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; @@ -16,7 +15,7 @@ namespace Umbraco.Core.Services /// /// Represents the UserService, which is an easy access to operations involving , and eventually Backoffice Users. /// - internal class UserService : IUserService + public class UserService : IUserService { private readonly RepositoryFactory _repositoryFactory; private readonly IDatabaseUnitOfWorkProvider _uowProvider; diff --git a/src/Umbraco.Core/Services/UserServiceExtensions.cs b/src/Umbraco.Core/Services/UserServiceExtensions.cs new file mode 100644 index 0000000000..b97a40ace8 --- /dev/null +++ b/src/Umbraco.Core/Services/UserServiceExtensions.cs @@ -0,0 +1,52 @@ +using System; +using System.Web.Security; +using Umbraco.Core.Models.Membership; + +namespace Umbraco.Core.Services +{ + internal static class UserServiceExtensions + { + /// + /// Maps a custom provider's information to an umbraco user account + /// + /// + /// + /// + /// To maintain compatibility we have to check the login name if the provider key lookup fails but otherwise + /// we'll store the provider user key in the login column. + /// + public static IUser CreateUserMappingForCustomProvider(this IUserService userService, MembershipUser member) + { + if (member == null) throw new ArgumentNullException("member"); + + + var valToLookup = member.ProviderUserKey == null ? member.UserName : member.ProviderUserKey.ToString(); + var found = userService.GetByUsername(valToLookup); + if (found == null && member.ProviderUserKey != null) + { + //try by username + found = userService.GetByUsername(member.UserName); + } + + if (found == null) + { + var writer = userService.GetUserTypeByAlias("writer"); + if (writer == null) + { + throw new InvalidOperationException("Could not map the custom user to an Umbraco user, no 'writer' user type could be found"); + } + var user = new User( + member.UserName, + member.Email ?? Guid.NewGuid().ToString("N") + "@example.com", //email cannot be empty + member.ProviderUserKey == null ? member.UserName : member.ProviderUserKey.ToString(), + Guid.NewGuid().ToString("N"), //pass cannot be empty + writer); + user.AddAllowedSection(Constants.Applications.Content); + userService.Save(user); + return user; + } + + return found; + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 0c7025fe00..c31a353390 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -787,6 +787,7 @@ + diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs index 36008e7fac..3773e1ffab 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/login.aspx.cs @@ -11,14 +11,17 @@ using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using Umbraco.Core.Logging; -using umbraco.BusinessLogic; using System.Web.Security; using umbraco.businesslogic.Exceptions; using Umbraco.Core.IO; using umbraco.cms.businesslogic.web; using System.Linq; using Umbraco.Core; +using Umbraco.Core.Models.Membership; using Umbraco.Core.Security; +using Umbraco.Core.Services; +using Umbraco.Web; +using User = umbraco.BusinessLogic.User; namespace umbraco.cms.presentation { @@ -83,40 +86,51 @@ namespace umbraco.cms.presentation // Authenticate users by using the provider specified in umbracoSettings.config if (BackOfficeProvider.ValidateUser(lname.Text, passw.Text)) { + IUser user; if (BackOfficeProvider.IsUmbracoUsersProvider() == false) { - CustomProviderMapping(lname.Text, BackOfficeProvider.GetUser(lname.Text, false).Email); + user = ApplicationContext.Services.UserService.CreateUserMappingForCustomProvider( + BackOfficeProvider.GetUser(lname.Text, false)); } - - - var u = new User(lname.Text); - doLogin(u); + else + { + user = ApplicationContext.Services.UserService.GetByUsername(lname.Text); + if (user == null) + { + throw new InvalidOperationException("No IUser found with username " + lname.Text); + } + } + + //do the login + UmbracoContext.Current.Security.PerformLogin(user.Id); // Check if the user should be redirected to live editing - if (UmbracoSettings.EnableCanvasEditing && u.DefaultToLiveEditing) + if (UmbracoSettings.EnableCanvasEditing) { - int startNode = u.StartNodeId; - // If the startnode is -1 (access to all content), we'll redirect to the top root node - if (startNode == -1) + //if live editing is enabled, we have to check if we need to redirect there but it is not supported + // on the new IUser so we need to get the legacy user object to check + var u = new User(user.Id); + if (u.DefaultToLiveEditing) { - if (Document.CountLeafNodes(-1, Document._objectType) > 0) + var startNode = u.StartNodeId; + // If the startnode is -1 (access to all content), we'll redirect to the top root node + if (startNode == -1) { - //get the first document - var firstNodeId = Document.TopMostNodeIds(Document._objectType).First(); - startNode = new Document(firstNodeId).Id; - } - else - { - throw new Exception("There's currently no content to edit. Please contact your system administrator"); + if (Document.CountLeafNodes(-1, Document._objectType) > 0) + { + //get the first document + var firstNodeId = Document.TopMostNodeIds(Document._objectType).First(); + startNode = new Document(firstNodeId).Id; + } + else + { + throw new Exception("There's currently no content to edit. Please contact your system administrator"); + } } + var redir = String.Format("{0}/canvas.aspx?redir=/{1}.aspx", SystemDirectories.Umbraco, startNode); + Response.Redirect(redir, true); } - string redir = String.Format("{0}/canvas.aspx?redir=/{1}.aspx", SystemDirectories.Umbraco, startNode); - Response.Redirect(redir, true); - } - else if (u.DefaultToLiveEditing) - { - throw new UserAuthorizationException("Canvas editing isn't enabled. It can be enabled via the UmbracoSettings.config"); - } + } if (hf_height.Value != "undefined") { @@ -173,24 +187,7 @@ namespace umbraco.cms.presentation && Uri.IsWellFormedUriString(url, UriKind.Relative); return isLocal; } - - /// - /// Maps a custom provider's information to an umbraco user account - /// - /// Name of the login. - /// Email address of the user - private static void CustomProviderMapping(string loginName, string email) - { - // Password is not copied over because it is stored in active directory for security! - // The user is create with default access to content and as a writer user type - if (BusinessLogic.User.getUserId(loginName) == -1) - { - BusinessLogic.User.MakeNew(loginName, loginName, string.Empty, email ?? "", UserType.GetUserType(2)); - var u = new User(loginName); - u.addApplication(Constants.Applications.Content); - } - } - + /// /// ClientLoader control. /// From 2956aee4e3bd94341b4203e945b739dbb89308ae Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Jan 2014 15:26:45 +1100 Subject: [PATCH 07/71] Fixes: U4-4108 The backoffice should not be accessible when the app is not configured, it should redirect to the installer and U4-4106 Set the new membership providers to be shipped as default. --- src/Umbraco.Web.UI/web.Template.config | 4 ++-- src/Umbraco.Web/UmbracoModule.cs | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Web.UI/web.Template.config b/src/Umbraco.Web.UI/web.Template.config index 8a01746b35..7964e798db 100644 --- a/src/Umbraco.Web.UI/web.Template.config +++ b/src/Umbraco.Web.UI/web.Template.config @@ -156,8 +156,8 @@ - - + + diff --git a/src/Umbraco.Web/UmbracoModule.cs b/src/Umbraco.Web/UmbracoModule.cs index f058b85461..8f7e5fc208 100644 --- a/src/Umbraco.Web/UmbracoModule.cs +++ b/src/Umbraco.Web/UmbracoModule.cs @@ -81,7 +81,14 @@ namespace Umbraco.Web if (UmbracoContext.Current.RoutingContext == null) throw new InvalidOperationException("The UmbracoContext.RoutingContext has not been assigned, ProcessRequest cannot proceed unless there is a RoutingContext assigned to the UmbracoContext"); - var umbracoContext = UmbracoContext.Current; + var umbracoContext = UmbracoContext.Current; + + //if it's a back office request then we need to ensure we're configured - otherwise redirect to installer + if (httpContext.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) + && EnsureIsConfigured(httpContext, umbracoContext.OriginalRequestUrl) == false) + { + return; + } // do not process but remap to handler if it is a base rest request if (BaseRest.BaseRestHandler.IsBaseRestRequest(umbracoContext.OriginalRequestUrl)) From ffde0f48cfeb86e47fcb35b54d4691e3ef29a72a Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 10:35:30 +1100 Subject: [PATCH 08/71] Starts wrapping MemberTypeService from the legacy MemberType object. Changes the User.Id to an int - no more casting. Changes CreateMember to CreateMemberWithIdentity for consistency. Adds raiseEvent params to the create/save methods. Updates the MemberTypeService to have consistent naming conventions. Starts wrapping more of the MemberService from the legacy Member object. --- src/umbraco.cms/businesslogic/ContentType.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/umbraco.cms/businesslogic/ContentType.cs b/src/umbraco.cms/businesslogic/ContentType.cs index 1f14459c40..b31be8a804 100644 --- a/src/umbraco.cms/businesslogic/ContentType.cs +++ b/src/umbraco.cms/businesslogic/ContentType.cs @@ -1149,6 +1149,15 @@ namespace umbraco.cms.businesslogic return; } } + else if (nodeObjectType == new Guid(Constants.ObjectTypes.MemberType)) + { + var memberType = ApplicationContext.Current.Services.MemberTypeService.Get(Id); + if (memberType != null) + { + PopulateContentTypeFromContentTypeBase(memberType); + return; + } + } // TODO: Load master content types using (var dr = SqlHelper.ExecuteReader("Select allowAtRoot, isContainer, Alias,icon,thumbnail,description from cmsContentType where nodeid=" + Id) @@ -1183,9 +1192,8 @@ namespace umbraco.cms.businesslogic RemoveFromDataTypeCache(ct.Alias); // clear anything that uses this as master content type - //TODO: Update to load all content types - //Should this include "ct.nodeObjectType == media.MediaType._objectType" ? - if (ct.nodeObjectType == DocumentType._objectType) + if (ct.nodeObjectType == DocumentType._objectType + || ct.nodeObjectType == media.MediaType._objectType) { //NOTE Changed from "DocumentType.GetAllAsList().FindAll(dt => dt.MasterContentType == id)" to loading master contenttypes directly from the db. //Related to http://issues.umbraco.org/issue/U4-1714 From 56dec485a5c63a583503ad41259c6f8cad73ea8f Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 10:41:57 +1100 Subject: [PATCH 09/71] Starts wrapping MemberTypeService from the legacy MemberType object. Changes the User.Id to an int - no more casting. Changes CreateMember to CreateMemberWithIdentity for consistency. Adds raiseEvent params to the create/save methods. Updates the MemberTypeService to have consistent naming conventions. Starts wrapping more of the MemberService from the legacy Member object. --- src/Umbraco.Core/Models/EntityExtensions.cs | 27 +++++ src/Umbraco.Core/Services/IMemberService.cs | 11 ++ .../Services/IMemberTypeService.cs | 8 +- .../Services/IMembershipMemberService.cs | 5 +- .../Services/IMembershipUserService.cs | 2 +- src/Umbraco.Core/Services/MemberService.cs | 50 ++++++++- .../Services/MemberTypeService.cs | 30 +++--- src/Umbraco.Core/Services/UserService.cs | 53 +++++---- src/Umbraco.Core/Umbraco.Core.csproj | 1 + .../UmbracoServiceMembershipProviderTests.cs | 6 +- .../NotificationsRepositoryTest.cs | 14 +-- .../Services/UserServiceTests.cs | 28 ++--- .../businesslogic/member/Member.cs | 89 ++++++++------- .../businesslogic/member/MemberType.cs | 102 +++++++++--------- 14 files changed, 255 insertions(+), 171 deletions(-) create mode 100644 src/Umbraco.Core/Models/EntityExtensions.cs diff --git a/src/Umbraco.Core/Models/EntityExtensions.cs b/src/Umbraco.Core/Models/EntityExtensions.cs new file mode 100644 index 0000000000..f461c4007c --- /dev/null +++ b/src/Umbraco.Core/Models/EntityExtensions.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Umbraco.Core.Models.EntityBase; + +namespace Umbraco.Core.Models +{ + public static class EntityExtensions + { + + /// + /// Returns true if this entity has just been created and persisted to the data store + /// + /// + /// + /// + /// This is useful when handling events to determine if an entity is a brand new entity or was + /// already existing. + /// + public static bool IsNewEntity(this IEntity entity) + { + var dirty = (IRememberBeingDirty)entity; + return dirty.WasPropertyDirty("Id"); + } + } +} diff --git a/src/Umbraco.Core/Services/IMemberService.cs b/src/Umbraco.Core/Services/IMemberService.cs index 05bcafba38..3634688f68 100644 --- a/src/Umbraco.Core/Services/IMemberService.cs +++ b/src/Umbraco.Core/Services/IMemberService.cs @@ -65,6 +65,17 @@ namespace Umbraco.Core.Services /// void DeleteMembersOfType(int memberTypeId); + /// + /// Find members based on their display name + /// + /// + /// + /// + /// + /// + /// + IEnumerable FindMembersByDisplayName(string displayNameToMatch, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith); + /// /// Get members based on a property search /// diff --git a/src/Umbraco.Core/Services/IMemberTypeService.cs b/src/Umbraco.Core/Services/IMemberTypeService.cs index 399c1500ce..7989becce1 100644 --- a/src/Umbraco.Core/Services/IMemberTypeService.cs +++ b/src/Umbraco.Core/Services/IMemberTypeService.cs @@ -4,27 +4,27 @@ using Umbraco.Core.Models; namespace Umbraco.Core.Services { internal interface IMemberTypeService : IService - { + { /// /// Gets a list of all available objects /// /// Optional list of ids /// An Enumerable list of objects - IEnumerable GetAllMemberTypes(params int[] ids); + IEnumerable GetAll(params int[] ids); /// /// Gets an object by its Id /// /// Id of the to retrieve /// - IMemberType GetMemberType(int id); + IMemberType Get(int id); /// /// Gets an object by its Alias /// /// Alias of the to retrieve /// - IMemberType GetMemberType(string alias); + IMemberType Get(string alias); /// /// Saves a single object diff --git a/src/Umbraco.Core/Services/IMembershipMemberService.cs b/src/Umbraco.Core/Services/IMembershipMemberService.cs index 01fa2954f0..e4d10f131f 100644 --- a/src/Umbraco.Core/Services/IMembershipMemberService.cs +++ b/src/Umbraco.Core/Services/IMembershipMemberService.cs @@ -15,7 +15,7 @@ namespace Umbraco.Core.Services /// public interface IMembershipMemberService : IMembershipMemberService { - IMember CreateMember(string email, string username, string password, IMemberType memberType); + IMember CreateMemberWithIdentity(string email, string username, string password, IMemberType memberType, bool raiseEvents = true); } /// @@ -47,8 +47,9 @@ namespace Umbraco.Core.Services /// /// /// + /// /// - T CreateMember(string username, string email, string password, string memberTypeAlias); + T CreateMember(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true); T GetById(object id); diff --git a/src/Umbraco.Core/Services/IMembershipUserService.cs b/src/Umbraco.Core/Services/IMembershipUserService.cs index 75382e5c46..57be495f47 100644 --- a/src/Umbraco.Core/Services/IMembershipUserService.cs +++ b/src/Umbraco.Core/Services/IMembershipUserService.cs @@ -11,7 +11,7 @@ namespace Umbraco.Core.Services public interface IMembershipUserService : IMembershipMemberService { - IUser CreateMember(string username, string email, string password, IUserType userType); + IUser CreateMemberWithIdentity(string username, string email, string password, IUserType userType, bool raiseEvents = true); } } \ No newline at end of file diff --git a/src/Umbraco.Core/Services/MemberService.cs b/src/Umbraco.Core/Services/MemberService.cs index a256430879..73929e443d 100644 --- a/src/Umbraco.Core/Services/MemberService.cs +++ b/src/Umbraco.Core/Services/MemberService.cs @@ -205,6 +205,38 @@ namespace Umbraco.Core.Services } } + public IEnumerable FindMembersByDisplayName(string displayNameToMatch, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith) + { + var uow = _uowProvider.GetUnitOfWork(); + using (var repository = _repositoryFactory.CreateMemberRepository(uow)) + { + var query = new Query(); + + switch (matchType) + { + case StringPropertyMatchType.Exact: + query.Where(member => member.Name.Equals(displayNameToMatch)); + break; + case StringPropertyMatchType.Contains: + query.Where(member => member.Name.Contains(displayNameToMatch)); + break; + case StringPropertyMatchType.StartsWith: + query.Where(member => member.Name.StartsWith(displayNameToMatch)); + break; + case StringPropertyMatchType.EndsWith: + query.Where(member => member.Name.EndsWith(displayNameToMatch)); + break; + case StringPropertyMatchType.Wildcard: + query.Where(member => member.Name.SqlWildcard(displayNameToMatch, TextColumnType.NVarchar)); + break; + default: + throw new ArgumentOutOfRangeException("matchType"); + } + + return repository.GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, dto => dto.Name); + } + } + /// /// Does a search for members that contain the specified string in their email address /// @@ -536,11 +568,17 @@ namespace Umbraco.Core.Services } } - public IMember CreateMember(string email, string username, string password, IMemberType memberType) + public IMember CreateMemberWithIdentity(string email, string username, string password, IMemberType memberType, bool raiseEvents = true) { if (memberType == null) throw new ArgumentNullException("memberType"); - var member = new Member(email, email, username, password, -1, memberType); + var member = new Member(username, email.ToLower().Trim(), username, password, -1, memberType); + + if (raiseEvents) + { + if (Saving.IsRaisedEventCancelled(new SaveEventArgs(member), this)) + return member; + } var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMemberRepository(uow)) @@ -553,6 +591,9 @@ namespace Umbraco.Core.Services CreateAndSaveMemberXml(xml, member.Id, uow.Database); } + if (raiseEvents) + Saved.RaiseEvent(new SaveEventArgs(member, false), this); + return member; } @@ -563,8 +604,9 @@ namespace Umbraco.Core.Services /// /// /// + /// /// - public IMember CreateMember(string email, string username, string password, string memberTypeAlias) + public IMember CreateMember(string email, string username, string password, string memberTypeAlias, bool raiseEvents = true) { var uow = _uowProvider.GetUnitOfWork(); IMemberType memberType; @@ -580,7 +622,7 @@ namespace Umbraco.Core.Services throw new ArgumentException(string.Format("No MemberType matching the passed in Alias: '{0}' was found", memberTypeAlias)); } - return CreateMember(email, username, password, memberTypeAlias); + return CreateMemberWithIdentity(email, username, password, memberType, raiseEvents); } /// diff --git a/src/Umbraco.Core/Services/MemberTypeService.cs b/src/Umbraco.Core/Services/MemberTypeService.cs index 2c1237c7b1..df323f8951 100644 --- a/src/Umbraco.Core/Services/MemberTypeService.cs +++ b/src/Umbraco.Core/Services/MemberTypeService.cs @@ -36,7 +36,7 @@ namespace Umbraco.Core.Services _memberService = memberService; } - public IEnumerable GetAllMemberTypes(params int[] ids) + public IEnumerable GetAll(params int[] ids) { using (var repository = _repositoryFactory.CreateMemberTypeRepository(_uowProvider.GetUnitOfWork())) { @@ -49,7 +49,7 @@ namespace Umbraco.Core.Services /// /// Id of the to retrieve /// - public IMemberType GetMemberType(int id) + public IMemberType Get(int id) { using (var repository = _repositoryFactory.CreateMemberTypeRepository(_uowProvider.GetUnitOfWork())) { @@ -62,7 +62,7 @@ namespace Umbraco.Core.Services /// /// Alias of the to retrieve /// - public IMemberType GetMemberType(string alias) + public IMemberType Get(string alias) { using (var repository = _repositoryFactory.CreateMemberTypeRepository(_uowProvider.GetUnitOfWork())) { @@ -75,7 +75,7 @@ namespace Umbraco.Core.Services public void Save(IMemberType memberType, int userId = 0) { - if (SavingMemberType.IsRaisedEventCancelled(new SaveEventArgs(memberType), this)) + if (Saving.IsRaisedEventCancelled(new SaveEventArgs(memberType), this)) return; using (new WriteLock(Locker)) @@ -91,14 +91,14 @@ namespace Umbraco.Core.Services UpdateContentXmlStructure(memberType); } - SavedMemberType.RaiseEvent(new SaveEventArgs(memberType, false), this); + Saved.RaiseEvent(new SaveEventArgs(memberType, false), this); } public void Save(IEnumerable memberTypes, int userId = 0) { var asArray = memberTypes.ToArray(); - if (SavingMemberType.IsRaisedEventCancelled(new SaveEventArgs(asArray), this)) + if (Saving.IsRaisedEventCancelled(new SaveEventArgs(asArray), this)) return; using (new WriteLock(Locker)) @@ -118,12 +118,12 @@ namespace Umbraco.Core.Services UpdateContentXmlStructure(asArray.Cast().ToArray()); } - SavedMemberType.RaiseEvent(new SaveEventArgs(asArray, false), this); + Saved.RaiseEvent(new SaveEventArgs(asArray, false), this); } public void Delete(IMemberType memberType, int userId = 0) { - if (DeletingMemberType.IsRaisedEventCancelled(new DeleteEventArgs(memberType), this)) + if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs(memberType), this)) return; using (new WriteLock(Locker)) @@ -136,7 +136,7 @@ namespace Umbraco.Core.Services repository.Delete(memberType); uow.Commit(); - DeletedMemberType.RaiseEvent(new DeleteEventArgs(memberType, false), this); + Deleted.RaiseEvent(new DeleteEventArgs(memberType, false), this); } } } @@ -145,7 +145,7 @@ namespace Umbraco.Core.Services { var asArray = memberTypes.ToArray(); - if (DeletingMemberType.IsRaisedEventCancelled(new DeleteEventArgs(asArray), this)) + if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs(asArray), this)) return; using (new WriteLock(Locker)) @@ -165,7 +165,7 @@ namespace Umbraco.Core.Services uow.Commit(); - DeletedMemberType.RaiseEvent(new DeleteEventArgs(asArray, false), this); + Deleted.RaiseEvent(new DeleteEventArgs(asArray, false), this); } } } @@ -195,21 +195,21 @@ namespace Umbraco.Core.Services /// /// Occurs before Save /// - public static event TypedEventHandler> SavingMemberType; + public static event TypedEventHandler> Saving; /// /// Occurs after Save /// - public static event TypedEventHandler> SavedMemberType; + public static event TypedEventHandler> Saved; /// /// Occurs before Delete /// - public static event TypedEventHandler> DeletingMemberType; + public static event TypedEventHandler> Deleting; /// /// Occurs after Delete /// - public static event TypedEventHandler> DeletedMemberType; + public static event TypedEventHandler> Deleted; } } \ No newline at end of file diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 8939101ac8..2349547c52 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -75,10 +75,12 @@ namespace Umbraco.Core.Services } } - public IUser CreateMember(string username, string email, string password, IUserType userType) + public IUser CreateMemberWithIdentity(string username, string email, string password, IUserType userType, bool raiseEvents = true) { if (userType == null) throw new ArgumentNullException("userType"); + //TODO: PUT lock here!! + var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateUserRepository(uow)) { @@ -101,14 +103,23 @@ namespace Umbraco.Core.Services IsApproved = true }; + if (raiseEvents) + { + if (SavingUser.IsRaisedEventCancelled(new SaveEventArgs(user), this)) + return user; + } + repository.AddOrUpdate(user); uow.Commit(); + if (raiseEvents) + SavedUser.RaiseEvent(new SaveEventArgs(user, false), this); + return user; } } - public IUser CreateMember(string username, string email, string password, string memberTypeAlias) + public IUser CreateMember(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true) { var userType = GetUserTypeByAlias(memberTypeAlias); if (userType == null) @@ -116,7 +127,7 @@ namespace Umbraco.Core.Services throw new ArgumentException("The user type " + memberTypeAlias + " could not be resolved"); } - return CreateMember(username, email, password, userType); + return CreateMemberWithIdentity(username, email, password, userType); } public IUser GetById(object id) @@ -156,7 +167,7 @@ namespace Umbraco.Core.Services public void Delete(IUser membershipUser) { - if (UserDeleting.IsRaisedEventCancelled(new DeleteEventArgs(membershipUser), this)) + if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs(membershipUser), this)) return; var uow = _uowProvider.GetUnitOfWork(); @@ -166,14 +177,14 @@ namespace Umbraco.Core.Services uow.Commit(); } - UserDeleted.RaiseEvent(new DeleteEventArgs(membershipUser, false), this); + DeletedUser.RaiseEvent(new DeleteEventArgs(membershipUser, false), this); } public void Save(IUser membershipUser, bool raiseEvents = true) { if (raiseEvents) { - if (UserSaving.IsRaisedEventCancelled(new SaveEventArgs(membershipUser), this)) + if (SavingUser.IsRaisedEventCancelled(new SaveEventArgs(membershipUser), this)) return; } @@ -185,14 +196,14 @@ namespace Umbraco.Core.Services } if (raiseEvents) - UserSaved.RaiseEvent(new SaveEventArgs(membershipUser, false), this); + SavedUser.RaiseEvent(new SaveEventArgs(membershipUser, false), this); } public void Save(IEnumerable members, bool raiseEvents = true) { if (raiseEvents) { - if (UserSaving.IsRaisedEventCancelled(new SaveEventArgs(members), this)) + if (SavingUser.IsRaisedEventCancelled(new SaveEventArgs(members), this)) return; } @@ -208,7 +219,7 @@ namespace Umbraco.Core.Services } if (raiseEvents) - UserSaved.RaiseEvent(new SaveEventArgs(members, false), this); + SavedUser.RaiseEvent(new SaveEventArgs(members, false), this); } public IEnumerable FindMembersByEmail(string emailStringToMatch, int pageIndex, int pageSize, out int totalRecords, StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith) @@ -383,7 +394,7 @@ namespace Umbraco.Core.Services { if (raiseEvents) { - if (UserTypeSaving.IsRaisedEventCancelled(new SaveEventArgs(userType), this)) + if (SavingUserType.IsRaisedEventCancelled(new SaveEventArgs(userType), this)) return; } @@ -395,12 +406,12 @@ namespace Umbraco.Core.Services } if (raiseEvents) - UserTypeSaved.RaiseEvent(new SaveEventArgs(userType, false), this); + SavedUserType.RaiseEvent(new SaveEventArgs(userType, false), this); } public void DeleteUserType(IUserType userType) { - if (UserTypeDeleting.IsRaisedEventCancelled(new DeleteEventArgs(userType), this)) + if (DeletingUserType.IsRaisedEventCancelled(new DeleteEventArgs(userType), this)) return; var uow = _uowProvider.GetUnitOfWork(); @@ -410,7 +421,7 @@ namespace Umbraco.Core.Services uow.Commit(); } - UserTypeDeleted.RaiseEvent(new DeleteEventArgs(userType, false), this); + DeletedUserType.RaiseEvent(new DeleteEventArgs(userType, false), this); } /// @@ -486,41 +497,41 @@ namespace Umbraco.Core.Services /// /// Occurs before Save /// - public static event TypedEventHandler> UserSaving; + public static event TypedEventHandler> SavingUser; /// /// Occurs after Save /// - public static event TypedEventHandler> UserSaved; + public static event TypedEventHandler> SavedUser; /// /// Occurs before Delete /// - public static event TypedEventHandler> UserDeleting; + public static event TypedEventHandler> DeletingUser; /// /// Occurs after Delete /// - public static event TypedEventHandler> UserDeleted; + public static event TypedEventHandler> DeletedUser; /// /// Occurs before Save /// - public static event TypedEventHandler> UserTypeSaving; + public static event TypedEventHandler> SavingUserType; /// /// Occurs after Save /// - public static event TypedEventHandler> UserTypeSaved; + public static event TypedEventHandler> SavedUserType; /// /// Occurs before Delete /// - public static event TypedEventHandler> UserTypeDeleting; + public static event TypedEventHandler> DeletingUserType; /// /// Occurs after Delete /// - public static event TypedEventHandler> UserTypeDeleted; + public static event TypedEventHandler> DeletedUserType; } } \ No newline at end of file diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index c31a353390..d76ec949ea 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -189,6 +189,7 @@ + diff --git a/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs b/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs index 35092f6bb6..804a1cd7b3 100644 --- a/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs +++ b/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs @@ -94,7 +94,7 @@ namespace Umbraco.Tests.Membership mServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); mServiceMock.Setup(service => service.GetDefaultMemberType()).Returns("Member"); mServiceMock.Setup( - service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string u, string e, string p, string m) => { createdMember = new Member("test", e, u, p, memberType); @@ -125,7 +125,7 @@ namespace Umbraco.Tests.Membership mServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); mServiceMock.Setup(service => service.GetDefaultMemberType()).Returns("Member"); mServiceMock.Setup( - service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string u, string e, string p, string m) => { createdMember = new Member("test", e, u, p, memberType); @@ -158,7 +158,7 @@ namespace Umbraco.Tests.Membership mServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); mServiceMock.Setup(service => service.GetDefaultMemberType()).Returns("Member"); mServiceMock.Setup( - service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Callback((string u, string e, string p, string m) => { createdMember = new Member("test", e, u, p, memberType); diff --git a/src/Umbraco.Tests/Persistence/Repositories/NotificationsRepositoryTest.cs b/src/Umbraco.Tests/Persistence/Repositories/NotificationsRepositoryTest.cs index 643c8d8b50..a026d2656d 100644 --- a/src/Umbraco.Tests/Persistence/Repositories/NotificationsRepositoryTest.cs +++ b/src/Umbraco.Tests/Persistence/Repositories/NotificationsRepositoryTest.cs @@ -26,7 +26,7 @@ namespace Umbraco.Tests.Persistence.Repositories var node = new NodeDto {CreateDate = DateTime.Now, Level = 1, NodeObjectType = Guid.Parse(Constants.ObjectTypes.ContentItem), ParentId = -1, Path = "-1,123", SortOrder = 1, Text = "hello", Trashed = false, UniqueId = Guid.NewGuid(), UserId = 0}; var result = unitOfWork.Database.Insert(node); var entity = Mock.Of(e => e.Id == node.NodeId); - var user = Mock.Of(e => e.Id == (object)node.UserId); + var user = Mock.Of(e => e.Id == node.UserId); var notification = repo.CreateNotification(user, entity, "A"); @@ -46,8 +46,8 @@ namespace Umbraco.Tests.Persistence.Repositories var userDto = new UserDto { ContentStartId = -1, DefaultPermissions = "", Email = "test" , Login = "test" , MediaStartId = -1, Password = "test" , Type = 1, UserName = "test" , UserLanguage = "en" }; unitOfWork.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == (object)userDto.Id); - var userAdmin = Mock.Of(e => e.Id == (object)0); + var userNew = Mock.Of(e => e.Id == userDto.Id); + var userAdmin = Mock.Of(e => e.Id == 0); for (var i = 0; i < 10; i++) { @@ -80,7 +80,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var userDto = new UserDto { ContentStartId = -1, DefaultPermissions = "", Email = "test" + i, Login = "test" + i, MediaStartId = -1, Password = "test", Type = 1, UserName = "test" + i, UserLanguage = "en" }; unitOfWork.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == (object)userDto.Id); + var userNew = Mock.Of(e => e.Id == userDto.Id); var notification = repo.CreateNotification(userNew, (i % 2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); } @@ -107,7 +107,7 @@ namespace Umbraco.Tests.Persistence.Repositories { var userDto = new UserDto { ContentStartId = -1, DefaultPermissions = "", Email = "test" + i, Login = "test" + i, MediaStartId = -1, Password = "test", Type = 1, UserName = "test" + i, UserLanguage = "en" }; unitOfWork.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == (object)userDto.Id); + var userNew = Mock.Of(e => e.Id == userDto.Id); var notification = repo.CreateNotification(userNew, (i % 2 == 0) ? entity1 : entity2, i.ToString(CultureInfo.InvariantCulture)); } @@ -126,8 +126,8 @@ namespace Umbraco.Tests.Persistence.Repositories var userDto = new UserDto { ContentStartId = -1, DefaultPermissions = "", Email = "test", Login = "test", MediaStartId = -1, Password = "test", Type = 1, UserName = "test", UserLanguage = "en" }; unitOfWork.Database.Insert(userDto); - var userNew = Mock.Of(e => e.Id == (object)userDto.Id); - var userAdmin = Mock.Of(e => e.Id == (object)0); + var userNew = Mock.Of(e => e.Id == userDto.Id); + var userAdmin = Mock.Of(e => e.Id == 0); for (var i = 0; i < 10; i++) { diff --git a/src/Umbraco.Tests/Services/UserServiceTests.cs b/src/Umbraco.Tests/Services/UserServiceTests.cs index 50229a5440..e76b07e30c 100644 --- a/src/Umbraco.Tests/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests/Services/UserServiceTests.cs @@ -35,7 +35,7 @@ namespace Umbraco.Tests.Services // Arrange var userService = ServiceContext.UserService; var userType = userService.GetUserTypeByAlias("admin"); - var user = ServiceContext.UserService.CreateMember("test1", "test1@test.com", "123456", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("test1", "test1@test.com", "123456", userType); var contentType = MockedContentTypes.CreateSimpleContentType(); ServiceContext.ContentTypeService.Save(contentType); var content = new[] @@ -62,7 +62,7 @@ namespace Umbraco.Tests.Services // Arrange var userService = ServiceContext.UserService; var userType = userService.GetUserTypeByAlias("admin"); - var user = ServiceContext.UserService.CreateMember("test1", "test1@test.com", "123456", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("test1", "test1@test.com", "123456", userType); var contentType = MockedContentTypes.CreateSimpleContentType(); ServiceContext.ContentTypeService.Save(contentType); var content = new[] @@ -96,7 +96,7 @@ namespace Umbraco.Tests.Services { var userType = MockedUserType.CreateUserType(); ServiceContext.UserService.SaveUserType(userType); - var user = ServiceContext.UserService.CreateMember("JohnDoe", "john@umbraco.io", "12345", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("JohnDoe", "john@umbraco.io", "12345", userType); ServiceContext.UserService.Delete(user); var deleted = ServiceContext.UserService.GetById(user.Id); @@ -110,7 +110,7 @@ namespace Umbraco.Tests.Services { var userType = MockedUserType.CreateUserType(); ServiceContext.UserService.SaveUserType(userType); - var user = ServiceContext.UserService.CreateMember("JohnDoe", "john@umbraco.io", "12345", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("JohnDoe", "john@umbraco.io", "12345", userType); Assert.IsTrue(ServiceContext.UserService.Exists("JohnDoe")); Assert.IsFalse(ServiceContext.UserService.Exists("notFound")); @@ -121,7 +121,7 @@ namespace Umbraco.Tests.Services { var userType = MockedUserType.CreateUserType(); ServiceContext.UserService.SaveUserType(userType); - var user = ServiceContext.UserService.CreateMember("JohnDoe", "john@umbraco.io", "12345", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("JohnDoe", "john@umbraco.io", "12345", userType); Assert.IsNotNull(ServiceContext.UserService.GetByEmail(user.Email)); Assert.IsNull(ServiceContext.UserService.GetByEmail("do@not.find")); @@ -132,7 +132,7 @@ namespace Umbraco.Tests.Services { var userType = MockedUserType.CreateUserType(); ServiceContext.UserService.SaveUserType(userType); - var user = ServiceContext.UserService.CreateMember("JohnDoe", "john@umbraco.io", "12345", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("JohnDoe", "john@umbraco.io", "12345", userType); Assert.IsNotNull(ServiceContext.UserService.GetByUsername(user.Username)); Assert.IsNull(ServiceContext.UserService.GetByUsername("notFound")); @@ -143,7 +143,7 @@ namespace Umbraco.Tests.Services { var userType = MockedUserType.CreateUserType(); ServiceContext.UserService.SaveUserType(userType); - var user = ServiceContext.UserService.CreateMember("JohnDoe", "john@umbraco.io", "12345", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("JohnDoe", "john@umbraco.io", "12345", userType); Assert.IsNotNull(ServiceContext.UserService.GetById(user.Id)); Assert.IsNull(ServiceContext.UserService.GetById(9876)); @@ -325,7 +325,7 @@ namespace Umbraco.Tests.Services var userType = userService.GetUserTypeByAlias("admin"); // Act - var membershipUser = userService.CreateMember("JohnDoe", "john@umbraco.io", "12345", userType); + var membershipUser = userService.CreateMemberWithIdentity("JohnDoe", "john@umbraco.io", "12345", userType); // Assert Assert.That(membershipUser.HasIdentity, Is.True); @@ -347,7 +347,7 @@ namespace Umbraco.Tests.Services var hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); var encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); - var membershipUser = userService.CreateMember("JohnDoe", "john@umbraco.io", encodedPassword, userType); + var membershipUser = userService.CreateMemberWithIdentity("JohnDoe", "john@umbraco.io", encodedPassword, userType); // Assert Assert.That(membershipUser.HasIdentity, Is.True); @@ -363,8 +363,8 @@ namespace Umbraco.Tests.Services { var userType = ServiceContext.UserService.GetUserTypeByAlias("admin"); - var user1 = ServiceContext.UserService.CreateMember("test1", "test1@test.com", "test1", userType); - var user2 = ServiceContext.UserService.CreateMember("test2", "test2@test.com", "test2", userType); + var user1 = ServiceContext.UserService.CreateMemberWithIdentity("test1", "test1@test.com", "test1", userType); + var user2 = ServiceContext.UserService.CreateMemberWithIdentity("test2", "test2@test.com", "test2", userType); //adds some allowed sections user1.AddAllowedSection("test"); @@ -388,7 +388,7 @@ namespace Umbraco.Tests.Services { // Arrange var userType = ServiceContext.UserService.GetUserTypeByAlias("admin"); - var user = ServiceContext.UserService.CreateMember("test1", "test1@test.com", "test1", userType); + var user = ServiceContext.UserService.CreateMemberWithIdentity("test1", "test1@test.com", "test1", userType); // Act @@ -405,7 +405,7 @@ namespace Umbraco.Tests.Services { // Arrange var userType = ServiceContext.UserService.GetUserTypeByAlias("admin"); - var user = (IUser)ServiceContext.UserService.CreateMember("test1", "test1@test.com", "test1", userType); + var user = (IUser)ServiceContext.UserService.CreateMemberWithIdentity("test1", "test1@test.com", "test1", userType); // Act @@ -422,7 +422,7 @@ namespace Umbraco.Tests.Services { // Arrange var userType = ServiceContext.UserService.GetUserTypeByAlias("admin"); - var originalUser = (User)ServiceContext.UserService.CreateMember("test1", "test1@test.com", "test1", userType); + var originalUser = (User)ServiceContext.UserService.CreateMemberWithIdentity("test1", "test1@test.com", "test1", userType); // Act diff --git a/src/umbraco.cms/businesslogic/member/Member.cs b/src/umbraco.cms/businesslogic/member/Member.cs index ef26845304..31139ae398 100644 --- a/src/umbraco.cms/businesslogic/member/Member.cs +++ b/src/umbraco.cms/businesslogic/member/Member.cs @@ -125,6 +125,9 @@ namespace umbraco.cms.businesslogic.member public static Member[] getAllOtherMembers() { + //NOTE: This hasn't been ported to the new service layer because it is an edge case, it is only used to render the tree nodes but in v7 we plan on + // changing how the members are shown and not having to worry about letters. + var tmp = new List(); using (var dr = SqlHelper.ExecuteReader( string.Format(_sQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')", "umbracoNode.text"), @@ -157,26 +160,19 @@ namespace umbraco.cms.businesslogic.member public static Member[] GetMemberByName(string usernameToMatch, bool matchByNameInsteadOfLogin) { - string field = matchByNameInsteadOfLogin ? "umbracoNode.text" : "cmsMember.loginName"; - - var tmp = new List(); - using (var dr = SqlHelper.ExecuteReader( - string.Format(_sQLOptimizedMany.Trim(), - string.Format("{0} like @letter", field), - "umbracoNode.text"), - SqlHelper.CreateParameter("@nodeObjectType", Member._objectType), - SqlHelper.CreateParameter("@letter", usernameToMatch + "%"))) + int totalRecs; + if (matchByNameInsteadOfLogin) { - while (dr.Read()) - { - var m = new Member(dr.GetInt("id"), true); - m.PopulateMemberFromReader(dr); - tmp.Add(m); - } + var found = ApplicationContext.Current.Services.MemberService.FindMembersByDisplayName( + usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); + return found.Select(x => new Member(x)).ToArray(); + } + else + { + var found = ApplicationContext.Current.Services.MemberService.FindMembersByUsername( + usernameToMatch, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.StartsWith); + return found.Select(x => new Member(x)).ToArray(); } - - return tmp.ToArray(); - } /// @@ -216,17 +212,16 @@ namespace umbraco.cms.businesslogic.member [MethodImpl(MethodImplOptions.Synchronized)] public static Member MakeNew(string Name, string LoginName, string Email, MemberType mbt, User u) { - if (mbt == null) throw new ArgumentNullException("mbt"); - + if (mbt == null) throw new ArgumentNullException("mbt"); var loginName = (string.IsNullOrEmpty(LoginName) == false) ? LoginName : Name; - - if (string.IsNullOrEmpty(loginName)) - throw new ArgumentException("The loginname must be different from an empty string", "loginName"); - + Mandate.ParameterNotNullOrEmpty(LoginName, "LoginName"); + + //NOTE: This check is ONLY for backwards compatibility, this check shouldn't really be here it is up to the Membership provider + // logic to deal with this but it was here before so we can't really change that. // Test for e-mail if (Email != "" && GetMemberFromEmail(Email) != null && Membership.Providers[UmbracoMemberProviderName].RequiresUniqueEmail) throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email)); - else if (GetMemberFromLoginName(loginName) != null) + if (GetMemberFromLoginName(loginName) != null) throw new Exception(string.Format("Duplicate User name! A member with the user name {0} already exists", loginName)); // Lowercased to prevent duplicates @@ -345,7 +340,7 @@ namespace umbraco.cms.businesslogic.member return null; } } - + [Obsolete("This method will not work if the password format is encrypted since the encryption that is performed is not static and a new value will be created each time the same string is encrypted")] public static Member GetMemberFromLoginAndEncodedPassword(string loginName, string password) { @@ -442,7 +437,7 @@ namespace umbraco.cms.businesslogic.member } return _password; - } + } set { // We need to use the provider for this in order for hashing, etc. support @@ -570,11 +565,11 @@ namespace umbraco.cms.businesslogic.member //If the version is empty we update with the latest version from the current IContent. if (Version == Guid.Empty) Version = Content.Version; - + _email = Content.Email; _loginName = Content.Username; _password = Content.Password; - + } @@ -624,7 +619,7 @@ namespace umbraco.cms.businesslogic.member { DateTime date; - if(DateTime.TryParse(property.Value.ToString(), out date)) + if (DateTime.TryParse(property.Value.ToString(), out date)) poco.Date = date; } else if (dbType.Equals("Nvarchar")) @@ -663,7 +658,7 @@ namespace umbraco.cms.businesslogic.member FireAfterSave(e); } } - + /// /// Xmlrepresentation of a member /// @@ -731,7 +726,7 @@ namespace umbraco.cms.businesslogic.member { return Content.Password; } - + /// /// Adds the member to group with the specified id /// @@ -874,14 +869,14 @@ namespace umbraco.cms.businesslogic.member GetCacheKey(m.Id), TimeSpan.FromMinutes(30), () => - { - // Debug information - HttpContext.Current.Trace.Write("member", - string.Format("Member added to cache: {0}/{1} ({2})", - m.Text, m.LoginName, m.Id)); + { + // Debug information + HttpContext.Current.Trace.Write("member", + string.Format("Member added to cache: {0}/{1} ({2})", + m.Text, m.LoginName, m.Id)); - return m; - }); + return m; + }); m.FireAfterAddToCache(e); } @@ -923,14 +918,14 @@ namespace umbraco.cms.businesslogic.member GetCacheKey(m.Id), TimeSpan.FromMinutes(30), () => - { - // Debug information - HttpContext.Current.Trace.Write("member", - string.Format("Member added to cache: {0}/{1} ({2})", - m.Text, m.LoginName, m.Id)); + { + // Debug information + HttpContext.Current.Trace.Write("member", + string.Format("Member added to cache: {0}/{1} ({2})", + m.Text, m.LoginName, m.Id)); - return m; - }); + return m; + }); m.FireAfterAddToCache(e); } @@ -1070,7 +1065,7 @@ namespace umbraco.cms.businesslogic.member return HttpContext.Current.User.Identity.IsAuthenticated; } - + /// /// Gets the current visitors memberid /// diff --git a/src/umbraco.cms/businesslogic/member/MemberType.cs b/src/umbraco.cms/businesslogic/member/MemberType.cs index 449531315c..9d16490365 100644 --- a/src/umbraco.cms/businesslogic/member/MemberType.cs +++ b/src/umbraco.cms/businesslogic/member/MemberType.cs @@ -2,27 +2,35 @@ using System; using System.Runtime.CompilerServices; using System.Xml; using Umbraco.Core.Logging; -using umbraco.cms.businesslogic.propertytype; using System.Linq; using umbraco.BusinessLogic; using Umbraco.Core; +using Umbraco.Core.Models; +using PropertyType = umbraco.cms.businesslogic.propertytype.PropertyType; namespace umbraco.cms.businesslogic.member { /// MemberType /// /// Due to the inheritance of the ContentType class, it enables definition of generic datafields on a Members. - /// + [Obsolete("Obsolete, Use Umbraco.Core.Models.MemberType", false)] public class MemberType : ContentType { #region Private Members - private static Guid _objectType = new Guid(Constants.ObjectTypes.MemberType); - + internal static readonly Guid ObjectType = new Guid(Constants.ObjectTypes.MemberType); + private IMemberType _contentType; + #endregion #region Constructors + internal MemberType(IMemberType memberType) + : base(memberType) + { + SetupNode(memberType); + } + /// /// Initializes a new instance of the MemberType class. /// @@ -70,7 +78,7 @@ namespace umbraco.cms.businesslogic.member /// True if the Member can edit the data public bool MemberCanEdit(PropertyType pt) { - if (propertyTypeRegistered(pt)) + if (PropertyTypeRegistered(pt)) { var memberCanEdit = SqlHelper.ExecuteScalar("Select memberCanEdit from cmsMemberType where NodeId = " + this.Id + " And propertytypeId = " + pt.Id); return (Convert.ToBoolean(memberCanEdit)); @@ -85,7 +93,7 @@ namespace umbraco.cms.businesslogic.member /// True if the data should be displayed on the profilepage public bool ViewOnProfile(PropertyType pt) { - if(propertyTypeRegistered(pt)) + if(PropertyTypeRegistered(pt)) { return Convert.ToBoolean(SqlHelper.ExecuteScalar("Select viewOnProfile from cmsMemberType where NodeId = " + this.Id + " And propertytypeId = " + pt.Id)); } @@ -101,7 +109,7 @@ namespace umbraco.cms.businesslogic.member { int tmpval = 0; if (value) tmpval = 1; - if (propertyTypeRegistered(pt)) + if (PropertyTypeRegistered(pt)) SqlHelper.ExecuteNonQuery("Update cmsMemberType set memberCanEdit = " + tmpval + " where NodeId = " + this.Id + " And propertytypeId = " + pt.Id); else SqlHelper.ExecuteNonQuery("insert into cmsMemberType (NodeId, propertytypeid, memberCanEdit,viewOnProfile) values (" + this.Id + "," + pt.Id + ", " + tmpval + ",0)"); @@ -117,7 +125,7 @@ namespace umbraco.cms.businesslogic.member { int tmpval = 0; if (value) tmpval = 1; - if (propertyTypeRegistered(pt)) + if (PropertyTypeRegistered(pt)) SqlHelper.ExecuteNonQuery("Update cmsMemberType set viewOnProfile = " + tmpval + " where NodeId = " + this.Id +" And propertytypeId = "+pt.Id); else SqlHelper.ExecuteNonQuery("insert into cmsMemberType (NodeId, propertytypeid, viewOnProfile) values ("+this.Id+","+pt.Id+", "+tmpval+")"); @@ -132,34 +140,31 @@ namespace umbraco.cms.businesslogic.member /// public override void delete() { - DeleteEventArgs e = new DeleteEventArgs(); + var e = new DeleteEventArgs(); FireBeforeDelete(e); - if (!e.Cancel) { + if (e.Cancel == false) { + + ApplicationContext.Current.Services.MemberTypeService.Delete(_contentType); // delete all documents of this type - Member.DeleteFromType(this); - - // delete membertype specific data - SqlHelper.ExecuteNonQuery("Delete from cmsMemberType where nodeId = " + this.Id); - - // Delete contentType - base.delete(); FireAfterDelete(e); } } /// - /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility + /// Used to persist object changes to the database /// public override void Save() { - SaveEventArgs e = new SaveEventArgs(); + var e = new SaveEventArgs(); FireBeforeSave(e); - if (!e.Cancel) + if (e.Cancel == false) { + ApplicationContext.Current.Services.MemberTypeService.Save(_contentType); + base.Save(); FireAfterSave(e); } } @@ -218,18 +223,8 @@ namespace umbraco.cms.businesslogic.member /// The MemberType with the given Alias public new static MemberType GetByAlias(string Alias) { - try - { - return - new MemberType( - SqlHelper.ExecuteScalar(@"SELECT nodeid from cmsContentType INNER JOIN umbracoNode on cmsContentType.nodeId = umbracoNode.id WHERE nodeObjectType=@nodeObjectType AND alias=@alias", - SqlHelper.CreateParameter("@nodeObjectType", MemberType._objectType), - SqlHelper.CreateParameter("@alias", Alias))); - } - catch - { - return null; - } + var result = ApplicationContext.Current.Services.MemberTypeService.Get(Alias); + return result == null ? null : new MemberType(result); } /// @@ -240,21 +235,17 @@ namespace umbraco.cms.businesslogic.member [MethodImpl(MethodImplOptions.Synchronized)] public static MemberType MakeNew(User u, string Text) { - int ParentId = -1; - int level = 1; - Guid uniqueId = Guid.NewGuid(); - CMSNode n = CMSNode.MakeNew(ParentId, _objectType, u.Id, level, Text, uniqueId); - - ContentType.Create(n.Id, Text, "", - //don't format the alias if it equals this. See: http://issues.umbraco.org/issue/U4-3968 - Text != "_umbracoSystemDefaultProtectType"); - - MemberType mt = new MemberType(n.Id); - mt.IconUrl = "member.gif"; - NewEventArgs e = new NewEventArgs(); - mt.OnNew(e); - - return mt; + var mt = new Umbraco.Core.Models.MemberType(-1) + { + Level = 1, + Name = Text, + Icon = "member.gif" + }; + ApplicationContext.Current.Services.MemberTypeService.Save(mt); + var legacy = new MemberType(mt); + var e = new NewEventArgs(); + legacy.OnNew(e); + return legacy; } /// @@ -264,18 +255,23 @@ namespace umbraco.cms.businesslogic.member { get { - Guid[] Ids = CMSNode.getAllUniquesFromObjectType(_objectType); - - MemberType[] retVal = new MemberType[Ids.Length]; - for (int i = 0; i < Ids.Length; i++) retVal[i] = new MemberType(Ids[i]); - return retVal; + var result = ApplicationContext.Current.Services.MemberTypeService.GetAll(); + return result.Select(x => new MemberType(x)).ToArray(); } } #endregion #region Private Methods - private bool propertyTypeRegistered(PropertyType pt) + private void SetupNode(IMemberType contentType) + { + _contentType = contentType; + + base.PopulateContentTypeFromContentTypeBase(_contentType); + base.PopulateCMSNodeFromUmbracoEntity(_contentType, ObjectType); + } + + private bool PropertyTypeRegistered(PropertyType pt) { return (SqlHelper.ExecuteScalar("Select count(pk) as tmp from cmsMemberType where NodeId = " + this.Id + " And propertytypeId = " + pt.Id) > 0); } From f4534aa94c53d9da8bd53330ede09328a6afee2a Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 10:55:22 +1100 Subject: [PATCH 10/71] adds unit tests for member type can view/can edit properties --- .../Services/MemberTypeServiceTests.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/Umbraco.Tests/Services/MemberTypeServiceTests.cs b/src/Umbraco.Tests/Services/MemberTypeServiceTests.cs index 3bbb6b7bf6..bf93abe8e7 100644 --- a/src/Umbraco.Tests/Services/MemberTypeServiceTests.cs +++ b/src/Umbraco.Tests/Services/MemberTypeServiceTests.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; +using umbraco.cms.presentation.create.controls; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; @@ -24,6 +25,66 @@ namespace Umbraco.Tests.Services base.TearDown(); } + [Test] + public void Member_Cannot_Edit_Property() + { + IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); + ServiceContext.MemberTypeService.Save(memberType); + //re-get + memberType = ServiceContext.MemberTypeService.Get(memberType.Id); + foreach (var p in memberType.PropertyTypes) + { + Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); + } + } + + [Test] + public void Member_Can_Edit_Property() + { + IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); + ServiceContext.MemberTypeService.Save(memberType); + var prop = memberType.PropertyTypes.First().Alias; + memberType.SetMemberCanEditProperty(prop, true); + ServiceContext.MemberTypeService.Save(memberType); + //re-get + memberType = ServiceContext.MemberTypeService.Get(memberType.Id); + foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) + { + Assert.IsFalse(memberType.MemberCanEditProperty(p.Alias)); + } + Assert.IsTrue(memberType.MemberCanEditProperty(prop)); + } + + [Test] + public void Member_Cannot_View_Property() + { + IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); + ServiceContext.MemberTypeService.Save(memberType); + //re-get + memberType = ServiceContext.MemberTypeService.Get(memberType.Id); + foreach (var p in memberType.PropertyTypes) + { + Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); + } + } + + [Test] + public void Member_Can_View_Property() + { + IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); + ServiceContext.MemberTypeService.Save(memberType); + var prop = memberType.PropertyTypes.First().Alias; + memberType.SetMemberCanViewProperty(prop, true); + ServiceContext.MemberTypeService.Save(memberType); + //re-get + memberType = ServiceContext.MemberTypeService.Get(memberType.Id); + foreach (var p in memberType.PropertyTypes.Where(x => x.Alias != prop)) + { + Assert.IsFalse(memberType.MemberCanViewProperty(p.Alias)); + } + Assert.IsTrue(memberType.MemberCanViewProperty(prop)); + } + [Test] public void Deleting_PropertyType_Removes_The_Property_From_Member() { From 80697cf9ca3a983ba9db7c7cf67b2d51c70525b2 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 10:57:24 +1100 Subject: [PATCH 11/71] MemberType fully wraps new MemberTypeService --- .../businesslogic/member/MemberType.cs | 37 ++++--------------- 1 file changed, 7 insertions(+), 30 deletions(-) diff --git a/src/umbraco.cms/businesslogic/member/MemberType.cs b/src/umbraco.cms/businesslogic/member/MemberType.cs index 9d16490365..f1f448a8f1 100644 --- a/src/umbraco.cms/businesslogic/member/MemberType.cs +++ b/src/umbraco.cms/businesslogic/member/MemberType.cs @@ -78,12 +78,7 @@ namespace umbraco.cms.businesslogic.member /// True if the Member can edit the data public bool MemberCanEdit(PropertyType pt) { - if (PropertyTypeRegistered(pt)) - { - var memberCanEdit = SqlHelper.ExecuteScalar("Select memberCanEdit from cmsMemberType where NodeId = " + this.Id + " And propertytypeId = " + pt.Id); - return (Convert.ToBoolean(memberCanEdit)); - } - return false; + return _contentType.MemberCanEditProperty(pt.Alias); } /// @@ -93,11 +88,7 @@ namespace umbraco.cms.businesslogic.member /// True if the data should be displayed on the profilepage public bool ViewOnProfile(PropertyType pt) { - if(PropertyTypeRegistered(pt)) - { - return Convert.ToBoolean(SqlHelper.ExecuteScalar("Select viewOnProfile from cmsMemberType where NodeId = " + this.Id + " And propertytypeId = " + pt.Id)); - } - return false; + return _contentType.MemberCanViewProperty(pt.Alias); } /// @@ -106,14 +97,9 @@ namespace umbraco.cms.businesslogic.member /// PropertyType /// True/False if Members of the type shoúld be able to edit the data public void setMemberCanEdit(PropertyType pt, bool value) - { - int tmpval = 0; - if (value) tmpval = 1; - if (PropertyTypeRegistered(pt)) - SqlHelper.ExecuteNonQuery("Update cmsMemberType set memberCanEdit = " + tmpval + " where NodeId = " + this.Id + " And propertytypeId = " + pt.Id); - else - SqlHelper.ExecuteNonQuery("insert into cmsMemberType (NodeId, propertytypeid, memberCanEdit,viewOnProfile) values (" + this.Id + "," + pt.Id + ", " + tmpval + ",0)"); - + { + _contentType.SetMemberCanEditProperty(pt.Alias, value); + ApplicationContext.Current.Services.MemberTypeService.Save(_contentType); } /// @@ -123,12 +109,8 @@ namespace umbraco.cms.businesslogic.member /// True/False if the data should be displayed public void setMemberViewOnProfile(PropertyType pt, bool value) { - int tmpval = 0; - if (value) tmpval = 1; - if (PropertyTypeRegistered(pt)) - SqlHelper.ExecuteNonQuery("Update cmsMemberType set viewOnProfile = " + tmpval + " where NodeId = " + this.Id +" And propertytypeId = "+pt.Id); - else - SqlHelper.ExecuteNonQuery("insert into cmsMemberType (NodeId, propertytypeid, viewOnProfile) values ("+this.Id+","+pt.Id+", "+tmpval+")"); + _contentType.SetMemberCanViewProperty(pt.Alias, value); + ApplicationContext.Current.Services.MemberTypeService.Save(_contentType); } /// @@ -271,11 +253,6 @@ namespace umbraco.cms.businesslogic.member base.PopulateCMSNodeFromUmbracoEntity(_contentType, ObjectType); } - private bool PropertyTypeRegistered(PropertyType pt) - { - return (SqlHelper.ExecuteScalar("Select count(pk) as tmp from cmsMemberType where NodeId = " + this.Id + " And propertytypeId = " + pt.Id) > 0); - } - #endregion #region Events From a272675ed8eb30de7ed2ac9f0e578bcebc256ecf Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 11:41:01 +1100 Subject: [PATCH 12/71] Wraps the MemberService from the legacy Member object --- src/Umbraco.Core/Models/Member.cs | 1 + .../Security/MembershipProviderExtensions.cs | 2 + src/Umbraco.Core/Services/MemberService.cs | 6 + src/umbraco.cms/businesslogic/media/Media.cs | 13 +- .../businesslogic/member/Member.cs | 418 +++++++++--------- .../businesslogic/member/MemberType.cs | 24 +- 6 files changed, 236 insertions(+), 228 deletions(-) diff --git a/src/Umbraco.Core/Models/Member.cs b/src/Umbraco.Core/Models/Member.cs index dee87d5616..7bd43233b2 100644 --- a/src/Umbraco.Core/Models/Member.cs +++ b/src/Umbraco.Core/Models/Member.cs @@ -31,6 +31,7 @@ namespace Umbraco.Core.Models _contentType = contentType; } + //TODO: Should we just get rid of this one? no reason to have a level set. internal Member(string name, string email, string username, string password, int parentId, IMemberType contentType) : base(name, parentId, contentType, new PropertyCollection()) { diff --git a/src/Umbraco.Core/Security/MembershipProviderExtensions.cs b/src/Umbraco.Core/Security/MembershipProviderExtensions.cs index 747f6c42c0..ed64f179b7 100644 --- a/src/Umbraco.Core/Security/MembershipProviderExtensions.cs +++ b/src/Umbraco.Core/Security/MembershipProviderExtensions.cs @@ -30,6 +30,8 @@ namespace Umbraco.Core.Security return (membershipProvider is UmbracoMembershipProviderBase); } + //TODO: Add role provider checks too + public static UmbracoMembershipProviderBase AsUmbracoMembershipProvider(this MembershipProvider membershipProvider) { return (UmbracoMembershipProviderBase)membershipProvider; diff --git a/src/Umbraco.Core/Services/MemberService.cs b/src/Umbraco.Core/Services/MemberService.cs index 73929e443d..5f79cfb03b 100644 --- a/src/Umbraco.Core/Services/MemberService.cs +++ b/src/Umbraco.Core/Services/MemberService.cs @@ -577,7 +577,10 @@ namespace Umbraco.Core.Services if (raiseEvents) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs(member), this)) + { + member.WasCancelled = true; return member; + } } var uow = _uowProvider.GetUnitOfWork(); @@ -709,7 +712,10 @@ namespace Umbraco.Core.Services if (raiseEvents) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs(member), this)) + { return; + } + } var uow = _uowProvider.GetUnitOfWork(); diff --git a/src/umbraco.cms/businesslogic/media/Media.cs b/src/umbraco.cms/businesslogic/media/Media.cs index 4b425f0981..6d8f8180a3 100644 --- a/src/umbraco.cms/businesslogic/media/Media.cs +++ b/src/umbraco.cms/businesslogic/media/Media.cs @@ -22,18 +22,7 @@ namespace umbraco.cms.businesslogic.media #region Constants and static members protected internal IMedia MediaItem; - private const string m_SQLOptimizedMany = @" - select - count(children.id) as children, cmsContentType.isContainer, umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level, umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate, umbracoNode.nodeUser, umbracoNode.text, - cmsContentType.icon, cmsContentType.alias, cmsContentType.thumbnail, cmsContentType.description, cmsContentType.nodeId as contentTypeId - from umbracoNode - left join umbracoNode children on children.parentId = umbracoNode.id - inner join cmsContent on cmsContent.nodeId = umbracoNode.id - inner join cmsContentType on cmsContentType.nodeId = cmsContent.contentType - where umbracoNode.nodeObjectType = @nodeObjectType AND {0} - group by cmsContentType.isContainer, umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level, umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate, umbracoNode.nodeUser, umbracoNode.text, - cmsContentType.icon, cmsContentType.alias, cmsContentType.thumbnail, cmsContentType.description, cmsContentType.nodeId - order by {1}"; + #endregion #region Constructors diff --git a/src/umbraco.cms/businesslogic/member/Member.cs b/src/umbraco.cms/businesslogic/member/Member.cs index 31139ae398..ce83c7ed14 100644 --- a/src/umbraco.cms/businesslogic/member/Member.cs +++ b/src/umbraco.cms/businesslogic/member/Member.cs @@ -11,6 +11,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Models; +using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.Querying; using umbraco.cms.businesslogic.cache; @@ -56,12 +57,10 @@ namespace umbraco.cms.businesslogic.member #endregion #region Private members - private string _text; - private string _email; - private string _password; - private string _loginName; + private Hashtable _groups = null; - protected internal IMember Content; + protected internal IMember MemberItem; + #endregion #region Constructors @@ -128,20 +127,21 @@ namespace umbraco.cms.businesslogic.member //NOTE: This hasn't been ported to the new service layer because it is an edge case, it is only used to render the tree nodes but in v7 we plan on // changing how the members are shown and not having to worry about letters. - var tmp = new List(); + var ids = new List(); using (var dr = SqlHelper.ExecuteReader( string.Format(_sQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')", "umbracoNode.text"), SqlHelper.CreateParameter("@nodeObjectType", Member._objectType))) { + while (dr.Read()) { - var m = new Member(dr.GetInt("id"), true); - m.PopulateMemberFromReader(dr); - tmp.Add(m); + ids.Add(dr.GetInt("id")); } } - return tmp.ToArray(); + return ApplicationContext.Current.Services.MemberService.GetAllMembers(ids.ToArray()) + .Select(x => new Member(x)) + .ToArray(); } /// @@ -224,37 +224,22 @@ namespace umbraco.cms.businesslogic.member if (GetMemberFromLoginName(loginName) != null) throw new Exception(string.Format("Duplicate User name! A member with the user name {0} already exists", loginName)); - // Lowercased to prevent duplicates - Email = Email.ToLower(); - var newId = Guid.NewGuid(); + var model = ApplicationContext.Current.Services.MemberService.CreateMemberWithIdentity( + Email.ToLower(), loginName, "", mbt.MemberTypeItem); + model.Name = Name; - //create the cms node first - var newNode = MakeNew(-1, _objectType, u.Id, 1, Name, newId); - - //we need to create an empty member and set the underlying text property - var tmp = new Member(newId, true); - tmp.SetText(Name); - - //create the content data for the new member - tmp.CreateContent(mbt); - - // Create member specific data .. - SqlHelper.ExecuteNonQuery( - "insert into cmsMember (nodeId,Email,LoginName,Password) values (@id,@email,@loginName,'')", - SqlHelper.CreateParameter("@id", tmp.Id), - SqlHelper.CreateParameter("@loginName", loginName), - SqlHelper.CreateParameter("@email", Email)); - - //read the whole object from the db - var m = new Member(newId); + //The content object will only have the 'WasCancelled' flag set to 'True' if the 'Creating' event has been cancelled, so we return null. + if (((Entity)model).WasCancelled) + return null; + var legacy = new Member(model); var e = new NewEventArgs(); - m.OnNew(e); + legacy.OnNew(e); + + legacy.Save(); - m.Save(); - - return m; + return legacy; } /// @@ -319,6 +304,7 @@ namespace umbraco.cms.businesslogic.member /// Member login /// Member password /// The member with the credentials - null if none exists + [Obsolete("Use the MembershipProvider methods to validate a member")] public static Member GetMemberFromLoginNameAndPassword(string loginName, string password) { if (IsMember(loginName)) @@ -399,25 +385,82 @@ namespace umbraco.cms.businesslogic.member #region Public Properties - /// - /// The name of the member - /// + public override int sortOrder + { + get + { + return MemberItem == null ? base.sortOrder : MemberItem.SortOrder; + } + set + { + if (MemberItem == null) + { + base.sortOrder = value; + } + else + { + MemberItem.SortOrder = value; + } + } + } + + public override int Level + { + get + { + return MemberItem == null ? base.Level : MemberItem.Level; + } + set + { + if (MemberItem == null) + { + base.Level = value; + } + else + { + MemberItem.Level = value; + } + } + } + + public override int ParentId + { + get + { + return MemberItem == null ? base.ParentId : MemberItem.ParentId; + } + } + + public override string Path + { + get + { + return MemberItem == null ? base.Path : MemberItem.Path; + } + set + { + if (MemberItem == null) + { + base.Path = value; + } + else + { + MemberItem.Path = value; + } + } + } + + [Obsolete("Obsolete, Use Name property on Umbraco.Core.Models.Content", false)] public override string Text { get { - if (string.IsNullOrEmpty(_text)) - { - _text = SqlHelper.ExecuteScalar( - "select text from umbracoNode where id = @id", - SqlHelper.CreateParameter("@id", Id)); - } - return _text; + return MemberItem.Name; } set { - _text = value; - base.Text = value; + value = value.Trim(); + MemberItem.Name = value; } } @@ -429,14 +472,7 @@ namespace umbraco.cms.businesslogic.member { get { - if (string.IsNullOrEmpty(_password)) - { - _password = SqlHelper.ExecuteScalar( - "select Password from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); - } - return _password; - + return MemberItem.Password; } set { @@ -444,7 +480,7 @@ namespace umbraco.cms.businesslogic.member // To write directly to the db use the ChangePassword method // this is not pretty but nessecary due to a design flaw (the membership provider should have been a part of the cms project) var helper = new MemberShipHelper(); - ChangePassword(helper.EncodePassword(value, Membership.Provider.PasswordFormat)); + MemberItem.Password = helper.EncodePassword(value, Membership.Provider.PasswordFormat); } } @@ -455,13 +491,7 @@ namespace umbraco.cms.businesslogic.member { get { - if (string.IsNullOrEmpty(_loginName)) - { - _loginName = SqlHelper.ExecuteScalar( - "select LoginName from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); - } - return _loginName; + return MemberItem.Username; } set { @@ -469,11 +499,7 @@ namespace umbraco.cms.businesslogic.member throw new ArgumentException("The loginname must be different from an empty string", "LoginName"); if (value.Contains(",")) throw new ArgumentException("The parameter 'LoginName' must not contain commas."); - SqlHelper.ExecuteNonQuery( - "update cmsMember set LoginName = @loginName where nodeId = @id", - SqlHelper.CreateParameter("@loginName", value), - SqlHelper.CreateParameter("@id", Id)); - _loginName = value; + MemberItem.Username = value; } } @@ -497,39 +523,11 @@ namespace umbraco.cms.businesslogic.member { get { - if (string.IsNullOrEmpty(_email)) - { - _email = SqlHelper.ExecuteScalar( - "select Email from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); - } - - return string.IsNullOrWhiteSpace(_email) ? _email : _email.ToLower(); + return MemberItem.Email.IsNullOrWhiteSpace() ? string.Empty : MemberItem.Email.ToLower(); } set { - var oldEmail = Email; - var newEmail = string.IsNullOrWhiteSpace(value) ? value : value.ToLower(); - var requireUniqueEmail = Membership.Providers[UmbracoMemberProviderName].RequiresUniqueEmail; - - var howManyMembersWithEmail = 0; - var membersWithEmail = GetMembersFromEmail(newEmail); - if (membersWithEmail != null) - howManyMembersWithEmail = membersWithEmail.Length; - - if (((oldEmail == newEmail && howManyMembersWithEmail > 1) || - (oldEmail != newEmail && howManyMembersWithEmail > 0)) - && requireUniqueEmail) - { - // If the value hasn't changed and there are more than 1 member with that email, then throw - // If the value has changed and there are any member with that new email, then throw - throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", newEmail)); - } - SqlHelper.ExecuteNonQuery( - "update cmsMember set Email = @email where nodeId = @id", - SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@email", newEmail)); - // Set the backing field to new value - _email = newEmail; + MemberItem.Email = value == null ? "" : value.ToLower(); } } #endregion @@ -555,21 +553,16 @@ namespace umbraco.cms.businesslogic.member private void SetupNode(IMember content) { - Content = content; + MemberItem = content; //Also need to set the ContentBase item to this one so all the propery values load from it - ContentBase = Content; + ContentBase = MemberItem; //Setting private properties from IContentBase replacing CMSNode.setupNode() / CMSNode.PopulateCMSNodeFromReader() - base.PopulateCMSNodeFromUmbracoEntity(Content, _objectType); + base.PopulateCMSNodeFromUmbracoEntity(MemberItem, _objectType); //If the version is empty we update with the latest version from the current IContent. if (Version == Guid.Empty) - Version = Content.Version; - - _email = Content.Email; - _loginName = Content.Username; - _password = Content.Password; - + Version = MemberItem.Version; } @@ -578,85 +571,124 @@ namespace umbraco.cms.businesslogic.member /// public override void Save() { + //Due to backwards compatibility with this API we need to check for duplicate emails here if required. + // This check should not be done here, as this logic is based on the MembershipProvider + var requireUniqueEmail = Membership.Providers[UmbracoMemberProviderName].RequiresUniqueEmail; + //check if there's anyone with this email in the db that isn't us + if (requireUniqueEmail && GetMembersFromEmail(Email).Any(x => x.Id != Id)) + { + throw new Exception(string.Format("Duplicate Email! A member with the e-mail {0} already exists", Email)); + } + var e = new SaveEventArgs(); FireBeforeSave(e); + foreach (var property in GenericProperties) + { + MemberItem.SetValue(property.PropertyType.Alias, property.Value); + } + if (!e.Cancel) { - var db = ApplicationContext.Current.DatabaseContext.Database; - using (var transaction = db.GetTransaction()) - { - foreach (var property in GenericProperties) - { - var poco = new PropertyDataDto - { - Id = property.Id, - PropertyTypeId = property.PropertyType.Id, - NodeId = Id, - VersionId = property.VersionId - }; - if (property.Value != null) - { - string dbType = property.PropertyType.DataTypeDefinition.DbType; - if (dbType.Equals("Integer")) - { - if (property.Value is bool || property.PropertyType.DataTypeDefinition.DataType.Id == new Guid("38b352c1-e9f8-4fd8-9324-9a2eab06d97a")) - { - poco.Integer = property.Value != null && string.IsNullOrEmpty(property.Value.ToString()) - ? 0 - : Convert.ToInt32(property.Value); - } - else - { - int value = 0; - if (int.TryParse(property.Value.ToString(), out value)) - { - poco.Integer = value; - } - } - } - else if (dbType.Equals("Date")) - { - DateTime date; + + ApplicationContext.Current.Services.MemberService.Save(MemberItem); - if (DateTime.TryParse(property.Value.ToString(), out date)) - poco.Date = date; - } - else if (dbType.Equals("Nvarchar")) - { - poco.VarChar = property.Value.ToString(); - } - else - { - poco.Text = property.Value.ToString(); - } - } - bool isNew = db.IsNew(poco); - if (isNew) - { - db.Insert(poco); - } - else - { - db.Update(poco); - } - } - transaction.Complete(); - } + //base.VersionDate = MemberItem.UpdateDate; - // re-generate xml - var xd = new XmlDocument(); + base.Save(); + + XmlDocument xd = new XmlDocument(); XmlGenerate(xd); // generate preview for blame history? if (UmbracoSettings.EnableGlobalPreviewStorage) { - // Version as new guid to ensure different versions are generated as members are not versioned currently! + // Version as new guid to ensure different versions are generated as media are not versioned currently! SavePreviewXml(generateXmlWithoutSaving(xd), Guid.NewGuid()); } FireAfterSave(e); } + + //var e = new SaveEventArgs(); + //FireBeforeSave(e); + + //if (!e.Cancel) + //{ + // var db = ApplicationContext.Current.DatabaseContext.Database; + // using (var transaction = db.GetTransaction()) + // { + // foreach (var property in GenericProperties) + // { + // var poco = new PropertyDataDto + // { + // Id = property.Id, + // PropertyTypeId = property.PropertyType.Id, + // NodeId = Id, + // VersionId = property.VersionId + // }; + // if (property.Value != null) + // { + // string dbType = property.PropertyType.DataTypeDefinition.DbType; + // if (dbType.Equals("Integer")) + // { + // if (property.Value is bool || property.PropertyType.DataTypeDefinition.DataType.Id == new Guid("38b352c1-e9f8-4fd8-9324-9a2eab06d97a")) + // { + // poco.Integer = property.Value != null && string.IsNullOrEmpty(property.Value.ToString()) + // ? 0 + // : Convert.ToInt32(property.Value); + // } + // else + // { + // int value = 0; + // if (int.TryParse(property.Value.ToString(), out value)) + // { + // poco.Integer = value; + // } + // } + // } + // else if (dbType.Equals("Date")) + // { + // DateTime date; + + // if (DateTime.TryParse(property.Value.ToString(), out date)) + // poco.Date = date; + // } + // else if (dbType.Equals("Nvarchar")) + // { + // poco.VarChar = property.Value.ToString(); + // } + // else + // { + // poco.Text = property.Value.ToString(); + // } + // } + // bool isNew = db.IsNew(poco); + // if (isNew) + // { + // db.Insert(poco); + // } + // else + // { + // db.Update(poco); + // } + // } + // transaction.Complete(); + // } + + // // re-generate xml + // var xd = new XmlDocument(); + // XmlGenerate(xd); + + // // generate preview for blame history? + // if (UmbracoSettings.EnableGlobalPreviewStorage) + // { + // // Version as new guid to ensure different versions are generated as members are not versioned currently! + // SavePreviewXml(generateXmlWithoutSaving(xd), Guid.NewGuid()); + // } + + // FireAfterSave(e); + //} } /// @@ -679,6 +711,7 @@ namespace umbraco.cms.businesslogic.member /// /// Deltes the current member /// + [Obsolete("Obsolete, Use Umbraco.Core.Services.MemberService.Delete()", false)] public override void delete() { var e = new DeleteEventArgs(); @@ -686,15 +719,15 @@ namespace umbraco.cms.businesslogic.member if (!e.Cancel) { - // delete all relations to groups - foreach (int groupId in this.Groups.Keys) + if (MemberItem != null) { - RemoveGroup(groupId); + ApplicationContext.Current.Services.MemberService.Delete(MemberItem); + } + else + { + var member = ApplicationContext.Current.Services.MemberService.GetById(Id); + ApplicationContext.Current.Services.MemberService.Delete(member); } - - // delete memeberspecific data! - SqlHelper.ExecuteNonQuery("Delete from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); // Delete all content and cmsnode specific data! base.delete(); @@ -704,18 +737,13 @@ namespace umbraco.cms.businesslogic.member } /// - /// Sets the password for the user - ensure it is encrypted or hashed based on the active membership provider. + /// Sets the password for the user - ensure it is encrypted or hashed based on the active membership provider - you must + /// call Save() after using this method /// /// public void ChangePassword(string newPassword) { - SqlHelper.ExecuteNonQuery( - "update cmsMember set Password = @password where nodeId = @id", - SqlHelper.CreateParameter("@password", newPassword), - SqlHelper.CreateParameter("@id", Id)); - - //update this object's password - _password = newPassword; + Password = newPassword; } /// @@ -724,7 +752,7 @@ namespace umbraco.cms.businesslogic.member /// public string GetPassword() { - return Content.Password; + return MemberItem.Password; } /// @@ -784,24 +812,6 @@ namespace umbraco.cms.businesslogic.member return node; } - protected void PopulateMemberFromReader(IRecordsReader dr) - { - - SetupNodeForTree(dr.GetGuid("uniqueId"), - _objectType, dr.GetShort("level"), - dr.GetInt("parentId"), - dr.GetInt("nodeUser"), - dr.GetString("path"), - dr.GetString("text"), - dr.GetDateTime("createDate"), false); - - if (!dr.IsNull("Email")) - _email = dr.GetString("Email"); - _loginName = dr.GetString("LoginName"); - _password = dr.GetString("Password"); - - } - #endregion #region Private methods diff --git a/src/umbraco.cms/businesslogic/member/MemberType.cs b/src/umbraco.cms/businesslogic/member/MemberType.cs index f1f448a8f1..f9f3c5a45f 100644 --- a/src/umbraco.cms/businesslogic/member/MemberType.cs +++ b/src/umbraco.cms/businesslogic/member/MemberType.cs @@ -19,7 +19,7 @@ namespace umbraco.cms.businesslogic.member #region Private Members internal static readonly Guid ObjectType = new Guid(Constants.ObjectTypes.MemberType); - private IMemberType _contentType; + internal IMemberType MemberTypeItem; #endregion @@ -78,7 +78,7 @@ namespace umbraco.cms.businesslogic.member /// True if the Member can edit the data public bool MemberCanEdit(PropertyType pt) { - return _contentType.MemberCanEditProperty(pt.Alias); + return MemberTypeItem.MemberCanEditProperty(pt.Alias); } /// @@ -88,7 +88,7 @@ namespace umbraco.cms.businesslogic.member /// True if the data should be displayed on the profilepage public bool ViewOnProfile(PropertyType pt) { - return _contentType.MemberCanViewProperty(pt.Alias); + return MemberTypeItem.MemberCanViewProperty(pt.Alias); } /// @@ -98,8 +98,8 @@ namespace umbraco.cms.businesslogic.member /// True/False if Members of the type shoúld be able to edit the data public void setMemberCanEdit(PropertyType pt, bool value) { - _contentType.SetMemberCanEditProperty(pt.Alias, value); - ApplicationContext.Current.Services.MemberTypeService.Save(_contentType); + MemberTypeItem.SetMemberCanEditProperty(pt.Alias, value); + ApplicationContext.Current.Services.MemberTypeService.Save(MemberTypeItem); } /// @@ -109,8 +109,8 @@ namespace umbraco.cms.businesslogic.member /// True/False if the data should be displayed public void setMemberViewOnProfile(PropertyType pt, bool value) { - _contentType.SetMemberCanViewProperty(pt.Alias, value); - ApplicationContext.Current.Services.MemberTypeService.Save(_contentType); + MemberTypeItem.SetMemberCanViewProperty(pt.Alias, value); + ApplicationContext.Current.Services.MemberTypeService.Save(MemberTypeItem); } /// @@ -128,7 +128,7 @@ namespace umbraco.cms.businesslogic.member if (e.Cancel == false) { - ApplicationContext.Current.Services.MemberTypeService.Delete(_contentType); + ApplicationContext.Current.Services.MemberTypeService.Delete(MemberTypeItem); // delete all documents of this type FireAfterDelete(e); @@ -145,7 +145,7 @@ namespace umbraco.cms.businesslogic.member if (e.Cancel == false) { - ApplicationContext.Current.Services.MemberTypeService.Save(_contentType); + ApplicationContext.Current.Services.MemberTypeService.Save(MemberTypeItem); base.Save(); FireAfterSave(e); } @@ -247,10 +247,10 @@ namespace umbraco.cms.businesslogic.member private void SetupNode(IMemberType contentType) { - _contentType = contentType; + MemberTypeItem = contentType; - base.PopulateContentTypeFromContentTypeBase(_contentType); - base.PopulateCMSNodeFromUmbracoEntity(_contentType, ObjectType); + base.PopulateContentTypeFromContentTypeBase(MemberTypeItem); + base.PopulateCMSNodeFromUmbracoEntity(MemberTypeItem, ObjectType); } #endregion From 011be60205d14aaa20bafab34f0ba04f9d28c7e7 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 12:30:28 +1100 Subject: [PATCH 13/71] Finishes wrapping the member service and fixes a few bugs - ensures the RepositoryBase doesn't keep enumerating when getting all --- .../Persistence/Repositories/RepositoryBase.cs | 13 ++++++++----- src/Umbraco.Core/Services/MemberService.cs | 2 +- src/umbraco.cms/businesslogic/member/MemberType.cs | 6 +++++- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/Umbraco.Core/Persistence/Repositories/RepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/RepositoryBase.cs index 26e97beff7..6a896a54cb 100644 --- a/src/Umbraco.Core/Persistence/Repositories/RepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/RepositoryBase.cs @@ -55,7 +55,7 @@ namespace Umbraco.Core.Persistence.Repositories /// public void AddOrUpdate(TEntity entity) { - if (!entity.HasIdentity) + if (entity.HasIdentity == false) { _work.RegisterAdded(entity, this); } @@ -101,7 +101,7 @@ namespace Umbraco.Core.Persistence.Repositories { //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 - TracksChangesEntityBase asEntity = entity as TracksChangesEntityBase; + var asEntity = entity as TracksChangesEntityBase; if (asEntity != null) { asEntity.ResetDirtyProperties(false); @@ -132,13 +132,16 @@ namespace Umbraco.Core.Persistence.Repositories { if (ids.Any()) { - var entities = _cache.GetByIds(typeof(TEntity), ids.Select(id => id is int ? ConvertIdToGuid(id) : ConvertStringIdToGuid(id.ToString())).ToList()); + var entities = _cache.GetByIds( + typeof (TEntity), ids.Select(id => id is int ? ConvertIdToGuid(id) : ConvertStringIdToGuid(id.ToString())).ToList()) + .ToArray(); + if (ids.Count().Equals(entities.Count()) && entities.Any(x => x == null) == false) return entities.Select(x => (TEntity)x); } else { - var allEntities = _cache.GetAllByType(typeof(TEntity)); + var allEntities = _cache.GetAllByType(typeof (TEntity)).ToArray(); if (allEntities.Any()) { @@ -151,7 +154,7 @@ namespace Umbraco.Core.Persistence.Repositories } } - var entityCollection = PerformGetAll(ids); + var entityCollection = PerformGetAll(ids).ToArray(); foreach (var entity in entityCollection) { diff --git a/src/Umbraco.Core/Services/MemberService.cs b/src/Umbraco.Core/Services/MemberService.cs index 5f79cfb03b..35e58a7a3e 100644 --- a/src/Umbraco.Core/Services/MemberService.cs +++ b/src/Umbraco.Core/Services/MemberService.cs @@ -676,7 +676,7 @@ namespace Umbraco.Core.Services { using (var repository = _repositoryFactory.CreateMemberRepository(_uowProvider.GetUnitOfWork())) { - var query = Query.Builder.Where(x => x.Username == userName); + var query = Query.Builder.Where(x => x.Username.Equals(userName)); var member = repository.GetByQuery(query).FirstOrDefault(); return member; diff --git a/src/umbraco.cms/businesslogic/member/MemberType.cs b/src/umbraco.cms/businesslogic/member/MemberType.cs index f9f3c5a45f..e0bcd8bf73 100644 --- a/src/umbraco.cms/businesslogic/member/MemberType.cs +++ b/src/umbraco.cms/businesslogic/member/MemberType.cs @@ -217,11 +217,15 @@ namespace umbraco.cms.businesslogic.member [MethodImpl(MethodImplOptions.Synchronized)] public static MemberType MakeNew(User u, string Text) { + var alias = helpers.Casing.SafeAliasWithForcingCheck(Text); + //special case, if it stars with an underscore, we have to re-add it for member types + if (Text.StartsWith("_")) alias = "_" + alias; var mt = new Umbraco.Core.Models.MemberType(-1) { Level = 1, Name = Text, - Icon = "member.gif" + Icon = "member.gif", + Alias = alias }; ApplicationContext.Current.Services.MemberTypeService.Save(mt); var legacy = new MemberType(mt); From 6377b9aa50539e456b0cef8d7ef7b5e95ca5e8a1 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 13:33:58 +1100 Subject: [PATCH 14/71] Fixes some underlying type conversions, fixes more of the member type wrapping, updates contenttypecontrolnew to work with member types properly, ensures the property type cache is cleared when member types change. --- src/Umbraco.Core/Models/ContentBase.cs | 6 +- src/Umbraco.Core/Models/Member.cs | 78 +++++------ .../Cache/CacheRefresherEventHandler.cs | 28 +++- .../Cache/DistributedCacheExtensions.cs | 74 +++++++--- .../controls/ContentTypeControlNew.ascx.cs | 128 ++++++++++-------- .../businesslogic/member/MemberType.cs | 10 ++ 6 files changed, 197 insertions(+), 127 deletions(-) diff --git a/src/Umbraco.Core/Models/ContentBase.cs b/src/Umbraco.Core/Models/ContentBase.cs index 9a5e735e9e..9531860051 100644 --- a/src/Umbraco.Core/Models/ContentBase.cs +++ b/src/Umbraco.Core/Models/ContentBase.cs @@ -306,10 +306,8 @@ namespace Umbraco.Core.Models /// Value as a public virtual TPassType GetValue(string propertyTypeAlias) { - if (Properties[propertyTypeAlias].Value is TPassType) - return (TPassType)Properties[propertyTypeAlias].Value; - - return (TPassType)Convert.ChangeType(Properties[propertyTypeAlias].Value, typeof(TPassType)); + var convertAttempt = Properties[propertyTypeAlias].Value.TryConvertTo(); + return convertAttempt.Success ? convertAttempt.Result : default(TPassType); } /// diff --git a/src/Umbraco.Core/Models/Member.cs b/src/Umbraco.Core/Models/Member.cs index 7bd43233b2..48683071d6 100644 --- a/src/Umbraco.Core/Models/Member.cs +++ b/src/Umbraco.Core/Models/Member.cs @@ -207,13 +207,12 @@ namespace Umbraco.Core.Models { get { - if (Properties[Constants.Conventions.Member.IsApproved].Value == null) - return default(bool); - - if (Properties[Constants.Conventions.Member.IsApproved].Value is bool) - return (bool)Properties[Constants.Conventions.Member.IsApproved].Value; - - return (bool)Convert.ChangeType(Properties[Constants.Conventions.Member.IsApproved].Value, typeof(bool)); + var tryConvert = Properties[Constants.Conventions.Member.IsApproved].Value.TryConvertTo(); + if (tryConvert.Success) + { + return tryConvert.Result; + } + return default(bool); } set { @@ -233,13 +232,12 @@ namespace Umbraco.Core.Models { get { - if (Properties[Constants.Conventions.Member.IsLockedOut].Value == null) - return default(bool); - - if (Properties[Constants.Conventions.Member.IsLockedOut].Value is bool) - return (bool)Properties[Constants.Conventions.Member.IsLockedOut].Value; - - return (bool)Convert.ChangeType(Properties[Constants.Conventions.Member.IsLockedOut].Value, typeof(bool)); + var tryConvert = Properties[Constants.Conventions.Member.IsLockedOut].Value.TryConvertTo(); + if (tryConvert.Success) + { + return tryConvert.Result; + } + return default(bool); } set { @@ -259,13 +257,12 @@ namespace Umbraco.Core.Models { get { - if (Properties[Constants.Conventions.Member.LastLoginDate].Value == null) - return default(DateTime); - - if (Properties[Constants.Conventions.Member.LastLoginDate].Value is DateTime) - return (DateTime)Properties[Constants.Conventions.Member.LastLoginDate].Value; - - return (DateTime)Convert.ChangeType(Properties[Constants.Conventions.Member.LastLoginDate].Value, typeof(DateTime)); + var tryConvert = Properties[Constants.Conventions.Member.LastLoginDate].Value.TryConvertTo(); + if (tryConvert.Success) + { + return tryConvert.Result; + } + return default(DateTime); } set { @@ -285,13 +282,12 @@ namespace Umbraco.Core.Models { get { - if (Properties[Constants.Conventions.Member.LastPasswordChangeDate].Value == null) - return default(DateTime); - - if (Properties[Constants.Conventions.Member.LastPasswordChangeDate].Value is DateTime) - return (DateTime)Properties[Constants.Conventions.Member.LastPasswordChangeDate].Value; - - return (DateTime)Convert.ChangeType(Properties[Constants.Conventions.Member.LastPasswordChangeDate].Value, typeof(DateTime)); + var tryConvert = Properties[Constants.Conventions.Member.LastPasswordChangeDate].Value.TryConvertTo(); + if (tryConvert.Success) + { + return tryConvert.Result; + } + return default(DateTime); } set { @@ -311,13 +307,12 @@ namespace Umbraco.Core.Models { get { - if (Properties[Constants.Conventions.Member.LastLockoutDate].Value == null) - return default(DateTime); - - if (Properties[Constants.Conventions.Member.LastLockoutDate].Value is DateTime) - return (DateTime)Properties[Constants.Conventions.Member.LastLockoutDate].Value; - - return (DateTime)Convert.ChangeType(Properties[Constants.Conventions.Member.LastLockoutDate].Value, typeof(DateTime)); + var tryConvert = Properties[Constants.Conventions.Member.LastLockoutDate].Value.TryConvertTo(); + if (tryConvert.Success) + { + return tryConvert.Result; + } + return default(DateTime); } set { @@ -338,13 +333,12 @@ namespace Umbraco.Core.Models { get { - if (Properties[Constants.Conventions.Member.FailedPasswordAttempts].Value == null) - return default(int); - - if (Properties[Constants.Conventions.Member.FailedPasswordAttempts].Value is int) - return (int)Properties[Constants.Conventions.Member.FailedPasswordAttempts].Value; - - return (int)Convert.ChangeType(Properties[Constants.Conventions.Member.FailedPasswordAttempts].Value, typeof(int)); + var tryConvert = Properties[Constants.Conventions.Member.FailedPasswordAttempts].Value.TryConvertTo(); + if (tryConvert.Success) + { + return tryConvert.Result; + } + return default(int); } set { diff --git a/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs b/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs index cb1dd65029..22dd740310 100644 --- a/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs +++ b/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs @@ -86,6 +86,8 @@ namespace Umbraco.Web.Cache ContentTypeService.SavedMediaType += ContentTypeServiceSavedMediaType; ContentTypeService.DeletedContentType += ContentTypeServiceDeletedContentType; ContentTypeService.DeletedMediaType += ContentTypeServiceDeletedMediaType; + MemberTypeService.Saved += MemberTypeServiceSaved; + MemberTypeService.Deleted += MemberTypeServiceDeleted; //Bind to user events @@ -363,7 +365,7 @@ namespace Umbraco.Web.Cache } #endregion - #region Content/media Type event handlers + #region Content/media/member Type event handlers /// /// Fires when a media type is deleted /// @@ -384,6 +386,16 @@ namespace Umbraco.Web.Cache e.DeletedEntities.ForEach(contentType => DistributedCache.Instance.RemoveContentTypeCache(contentType)); } + /// + /// Fires when a member type is deleted + /// + /// + /// + static void MemberTypeServiceDeleted(IMemberTypeService sender, Core.Events.DeleteEventArgs e) + { + e.DeletedEntities.ForEach(contentType => DistributedCache.Instance.RemoveMemberTypeCache(contentType)); + } + /// /// Fires when a media type is saved /// @@ -402,7 +414,19 @@ namespace Umbraco.Web.Cache static void ContentTypeServiceSavedContentType(IContentTypeService sender, Core.Events.SaveEventArgs e) { e.SavedEntities.ForEach(contentType => DistributedCache.Instance.RefreshContentTypeCache(contentType)); - } + } + + /// + /// Fires when a member type is saved + /// + /// + /// + static void MemberTypeServiceSaved(IMemberTypeService sender, Core.Events.SaveEventArgs e) + { + e.SavedEntities.ForEach(x => DistributedCache.Instance.RefreshMemberTypeCache(x)); + } + + #endregion #region User event handlers diff --git a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs index 274705439e..f4f70e32ba 100644 --- a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs +++ b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs @@ -353,7 +353,7 @@ namespace Umbraco.Web.Cache } #endregion - #region Content type cache + #region Document type cache /// /// Remove all cache for a given content type @@ -364,27 +364,11 @@ namespace Umbraco.Web.Cache { if (contentType != null) { - //dc.Refresh(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, contentType); dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId), ContentTypeCacheRefresher.SerializeToJsonPayload(false, contentType)); } } - /// - /// Remove all cache for a given media type - /// - /// - /// - public static void RefreshMediaTypeCache(this DistributedCache dc, IMediaType mediaType) - { - if (mediaType != null) - { - //dc.Refresh(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, mediaType); - dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId), - ContentTypeCacheRefresher.SerializeToJsonPayload(false, mediaType)); - } - } - /// /// Remove all cache for a given content type /// @@ -394,12 +378,29 @@ namespace Umbraco.Web.Cache { if (contentType != null) { - //dc.Remove(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, contentType); dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId), ContentTypeCacheRefresher.SerializeToJsonPayload(true, contentType)); } } + #endregion + + #region Media type cache + + /// + /// Remove all cache for a given media type + /// + /// + /// + public static void RefreshMediaTypeCache(this DistributedCache dc, IMediaType mediaType) + { + if (mediaType != null) + { + dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId), + ContentTypeCacheRefresher.SerializeToJsonPayload(false, mediaType)); + } + } + /// /// Remove all cache for a given media type /// @@ -409,13 +410,46 @@ namespace Umbraco.Web.Cache { if (mediaType != null) { - //dc.Remove(new Guid(DistributedCache.ContentTypeCacheRefresherId), x => x.Id, mediaType); dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId), ContentTypeCacheRefresher.SerializeToJsonPayload(true, mediaType)); } - } + } + #endregion + #region Media type cache + + /// + /// Remove all cache for a given media type + /// + /// + /// + public static void RefreshMemberTypeCache(this DistributedCache dc, IMemberType memberType) + { + if (memberType != null) + { + dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId), + ContentTypeCacheRefresher.SerializeToJsonPayload(false, memberType)); + } + } + + /// + /// Remove all cache for a given media type + /// + /// + /// + public static void RemoveMemberTypeCache(this DistributedCache dc, IMemberType memberType) + { + if (memberType != null) + { + dc.RefreshByJson(new Guid(DistributedCache.ContentTypeCacheRefresherId), + ContentTypeCacheRefresher.SerializeToJsonPayload(true, memberType)); + } + } + + #endregion + + #region Stylesheet Cache public static void RefreshStylesheetPropertyCache(this DistributedCache dc, global::umbraco.cms.businesslogic.web.StylesheetProperty styleSheetProperty) diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControlNew.ascx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControlNew.ascx.cs index 9173f9f681..c621efb30a 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControlNew.ascx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/ContentTypeControlNew.ascx.cs @@ -292,8 +292,10 @@ namespace umbraco.controls //to avoid the multiple cache flushing when each property is set using the legacy ContentType class, //which has been reduced to the else-clause. //For IContentType and IMediaType the cache will only be flushed upon saving. - if (_contentType.ContentTypeItem is IContentType || _contentType.ContentTypeItem is IMediaType) - { + //if (_contentType.ContentTypeItem is IContentType + // || _contentType.ContentTypeItem is IMediaType + // || _contentType.ContentTypeItem is IMemberType) + //{ _contentType.ContentTypeItem.Name = txtName.Text; _contentType.ContentTypeItem.Alias = txtAlias.Text; _contentType.ContentTypeItem.Icon = ddlIcons.SelectedValue; @@ -331,40 +333,40 @@ namespace umbraco.controls } _contentType.Save(); - } - else //Legacy approach for supporting MemberType - { - if (asyncState.HasNameChanged()) - _contentType.Text = txtName.Text; + //} + //else //Legacy approach for supporting MemberType + //{ + // if (asyncState.HasNameChanged()) + // _contentType.Text = txtName.Text; - if (asyncState.HasAliasChanged()) - _contentType.Alias = txtAlias.Text; + // if (asyncState.HasAliasChanged()) + // _contentType.Alias = txtAlias.Text; - _contentType.IconUrl = ddlIcons.SelectedValue; - _contentType.Description = description.Text; - _contentType.Thumbnail = ddlThumbnails.SelectedValue; + // _contentType.IconUrl = ddlIcons.SelectedValue; + // _contentType.Description = description.Text; + // _contentType.Thumbnail = ddlThumbnails.SelectedValue; - SavePropertyTypesLegacy(asyncState.SaveArgs); + // SavePropertyTypesLegacy(asyncState.SaveArgs); - var tabs = SaveTabs(); - foreach (var tab in tabs) - { - _contentType.SetTabName(tab.Item1, tab.Item2); - _contentType.SetTabSortOrder(tab.Item1, tab.Item3); - } + // var tabs = SaveTabs(); + // foreach (var tab in tabs) + // { + // _contentType.SetTabName(tab.Item1, tab.Item2); + // _contentType.SetTabSortOrder(tab.Item1, tab.Item3); + // } - _contentType.AllowedChildContentTypeIDs = SaveAllowedChildTypes(); - _contentType.AllowAtRoot = allowAtRoot.Checked; + // _contentType.AllowedChildContentTypeIDs = SaveAllowedChildTypes(); + // _contentType.AllowAtRoot = allowAtRoot.Checked; - _contentType.Save(); + // _contentType.Save(); - // Only if the doctype alias changed, cause a regeneration of the xml cache file since - // the xml element names will need to be updated to reflect the new alias - if (asyncState.HasAliasChanged() || asyncState.HasAnyPropertyAliasChanged(_contentType)) - { - _contentType.RebuildXmlStructuresForContent(); - } - } + // // Only if the doctype alias changed, cause a regeneration of the xml cache file since + // // the xml element names will need to be updated to reflect the new alias + // if (asyncState.HasAliasChanged() || asyncState.HasAnyPropertyAliasChanged(_contentType)) + // { + // _contentType.RebuildXmlStructuresForContent(); + // } + //} Trace.Write("ContentTypeControlNew", "task completing"); }; @@ -1042,8 +1044,10 @@ jQuery(document).ready(function() {{ refreshDropDowns(); }}); int propertyId = int.Parse(e.Item.Cells[0].Text); string rawName = string.Empty; - if (_contentType.ContentTypeItem is IContentType || _contentType.ContentTypeItem is IMediaType) - { + //if (_contentType.ContentTypeItem is IContentType + // || _contentType.ContentTypeItem is IMediaType + // || _contentType.ContentTypeItem is IMemberType) + //{ var propertyType = _contentType.ContentTypeItem.PropertyTypes.FirstOrDefault(x => x.Id == propertyId); if (propertyType != null && string.IsNullOrEmpty(propertyType.Alias) == false) { @@ -1051,13 +1055,13 @@ jQuery(document).ready(function() {{ refreshDropDowns(); }}); _contentType.ContentTypeItem.RemovePropertyType(propertyType.Alias); _contentType.Save(); } - } - else - { - cms.businesslogic.propertytype.PropertyType pt = cms.businesslogic.propertytype.PropertyType.GetPropertyType(propertyId); - rawName = pt.GetRawName(); - pt.delete(); - } + //} + //else + //{ + // cms.businesslogic.propertytype.PropertyType pt = cms.businesslogic.propertytype.PropertyType.GetPropertyType(propertyId); + // rawName = pt.GetRawName(); + // pt.delete(); + //} RaiseBubbleEvent(new object(), new SaveClickEventArgs("Property ´" + rawName + "´ deleted")); @@ -1128,20 +1132,22 @@ jQuery(document).ready(function() {{ refreshDropDowns(); }}); //we need to re-set the UmbracoContext since it will be nulled and our cache handlers need it global::Umbraco.Web.UmbracoContext.Current = asyncState.UmbracoContext; - if (_contentType.ContentTypeItem is IContentType || _contentType.ContentTypeItem is IMediaType) - { + //if (_contentType.ContentTypeItem is IContentType + // || _contentType.ContentTypeItem is IMediaType + // || _contentType.ContentTypeItem is IMemberType) + //{ _contentType.ContentTypeItem.RemovePropertyType(asyncState.GenericPropertyWrapper.PropertyType.Alias); _contentType.Save(); - } - else - { - //if it is not a document type or a media type, then continue to call the legacy delete() method. - //the new API for document type and media type's will ensure that the data is removed correctly and that - //the cache is flushed correctly (using events). If it is not one of these types, we'll rever to the - //legacy operation (... like for members i suppose ?) - asyncState.GenericPropertyWrapper.GenricPropertyControl.PropertyType.delete(); + //} + //else + //{ + // //if it is not a document type or a media type, then continue to call the legacy delete() method. + // //the new API for document type and media type's will ensure that the data is removed correctly and that + // //the cache is flushed correctly (using events). If it is not one of these types, we'll rever to the + // //legacy operation (... like for members i suppose ?) + // asyncState.GenericPropertyWrapper.GenricPropertyControl.PropertyType.delete(); - } + //} Trace.Write("ContentTypeControlNew", "task completing"); }; @@ -1277,15 +1283,17 @@ jQuery(document).ready(function() {{ refreshDropDowns(); }}); { if (txtNewTab.Text.Trim() != "") { - if (_contentType.ContentTypeItem is IContentType || _contentType.ContentTypeItem is IMediaType) - { + //if (_contentType.ContentTypeItem is IContentType + // || _contentType.ContentTypeItem is IMediaType + // || _contentType.ContentTypeItem is IMemberType) + //{ _contentType.ContentTypeItem.AddPropertyGroup(txtNewTab.Text); _contentType.Save(); - } - else - { - _contentType.AddVirtualTab(txtNewTab.Text); - } + //} + //else + //{ + // _contentType.AddVirtualTab(txtNewTab.Text); + //} LoadContentType(); @@ -1317,15 +1325,17 @@ Umbraco.Controls.TabView.onActiveTabChange(function(tabviewid, tabid, tabs) { if (e.CommandName == "Delete") { int propertyGroupId = int.Parse(e.Item.Cells[0].Text); - if (_contentType.ContentTypeItem is IContentType || _contentType.ContentTypeItem is IMediaType) - { + //if (_contentType.ContentTypeItem is IContentType + // || _contentType.ContentTypeItem is IMediaType + // || _contentType.ContentTypeItem is IMemberType) + //{ var propertyGroup = _contentType.ContentTypeItem.PropertyGroups.FirstOrDefault(x => x.Id == propertyGroupId); if (propertyGroup != null && string.IsNullOrEmpty(propertyGroup.Name) == false) { _contentType.ContentTypeItem.PropertyGroups.Remove(propertyGroup.Name); _contentType.Save(); } - } + //} _contentType.DeleteVirtualTab(propertyGroupId); diff --git a/src/umbraco.cms/businesslogic/member/MemberType.cs b/src/umbraco.cms/businesslogic/member/MemberType.cs index e0bcd8bf73..7df9c80fa3 100644 --- a/src/umbraco.cms/businesslogic/member/MemberType.cs +++ b/src/umbraco.cms/businesslogic/member/MemberType.cs @@ -247,6 +247,16 @@ namespace umbraco.cms.businesslogic.member } #endregion + #region Protected Methods + + protected override void setupNode() + { + var memberType = ApplicationContext.Current.Services.MemberTypeService.Get(Id); + SetupNode(memberType); + } + + #endregion + #region Private Methods private void SetupNode(IMemberType contentType) From 4735f27a66f80ac3c91b0cdc048f8513f1b35bdf Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 14:55:41 +1100 Subject: [PATCH 15/71] Fixes more naming conventions with CreateMemberWithIdentity, fixes memberTasks to ensure the name is set, fixes new membership providers which had the name/email call reversed. Updates the cache refresher event handler to listen to MemberService events instead of the old legacy API events. --- .../Services/IMembershipMemberService.cs | 4 +-- src/Umbraco.Core/Services/MemberService.cs | 4 +-- src/Umbraco.Core/Services/UserService.cs | 2 +- .../UmbracoServiceMembershipProviderTests.cs | 12 +++---- .../Cache/CacheRefresherEventHandler.cs | 32 ++++++++++++------- .../Cache/DistributedCacheExtensions.cs | 1 + .../UmbracoServiceMembershipProvider.cs | 2 +- .../umbraco/create/memberTasks.cs | 15 +++++++-- 8 files changed, 46 insertions(+), 26 deletions(-) diff --git a/src/Umbraco.Core/Services/IMembershipMemberService.cs b/src/Umbraco.Core/Services/IMembershipMemberService.cs index e4d10f131f..b27b8f660a 100644 --- a/src/Umbraco.Core/Services/IMembershipMemberService.cs +++ b/src/Umbraco.Core/Services/IMembershipMemberService.cs @@ -15,7 +15,7 @@ namespace Umbraco.Core.Services /// public interface IMembershipMemberService : IMembershipMemberService { - IMember CreateMemberWithIdentity(string email, string username, string password, IMemberType memberType, bool raiseEvents = true); + IMember CreateMemberWithIdentity(string username, string email, string password, IMemberType memberType, bool raiseEvents = true); } /// @@ -49,7 +49,7 @@ namespace Umbraco.Core.Services /// /// /// - T CreateMember(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true); + T CreateMemberWithIdentity(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true); T GetById(object id); diff --git a/src/Umbraco.Core/Services/MemberService.cs b/src/Umbraco.Core/Services/MemberService.cs index 35e58a7a3e..0f4c958306 100644 --- a/src/Umbraco.Core/Services/MemberService.cs +++ b/src/Umbraco.Core/Services/MemberService.cs @@ -568,7 +568,7 @@ namespace Umbraco.Core.Services } } - public IMember CreateMemberWithIdentity(string email, string username, string password, IMemberType memberType, bool raiseEvents = true) + public IMember CreateMemberWithIdentity(string username, string email, string password, IMemberType memberType, bool raiseEvents = true) { if (memberType == null) throw new ArgumentNullException("memberType"); @@ -609,7 +609,7 @@ namespace Umbraco.Core.Services /// /// /// - public IMember CreateMember(string email, string username, string password, string memberTypeAlias, bool raiseEvents = true) + public IMember CreateMemberWithIdentity(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true) { var uow = _uowProvider.GetUnitOfWork(); IMemberType memberType; diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 2349547c52..589ed43046 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -119,7 +119,7 @@ namespace Umbraco.Core.Services } } - public IUser CreateMember(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true) + public IUser CreateMemberWithIdentity(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true) { var userType = GetUserTypeByAlias(memberTypeAlias); if (userType == null) diff --git a/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs b/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs index 804a1cd7b3..b39bdeeab2 100644 --- a/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs +++ b/src/Umbraco.Tests/Membership/UmbracoServiceMembershipProviderTests.cs @@ -94,8 +94,8 @@ namespace Umbraco.Tests.Membership mServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); mServiceMock.Setup(service => service.GetDefaultMemberType()).Returns("Member"); mServiceMock.Setup( - service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((string u, string e, string p, string m) => + service => service.CreateMemberWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((string u, string e, string p, string m, bool b) => { createdMember = new Member("test", e, u, p, memberType); }) @@ -125,8 +125,8 @@ namespace Umbraco.Tests.Membership mServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); mServiceMock.Setup(service => service.GetDefaultMemberType()).Returns("Member"); mServiceMock.Setup( - service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((string u, string e, string p, string m) => + service => service.CreateMemberWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((string u, string e, string p, string m, bool b) => { createdMember = new Member("test", e, u, p, memberType); }) @@ -158,8 +158,8 @@ namespace Umbraco.Tests.Membership mServiceMock.Setup(service => service.GetByEmail("test@test.com")).Returns(() => null); mServiceMock.Setup(service => service.GetDefaultMemberType()).Returns("Member"); mServiceMock.Setup( - service => service.CreateMember(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((string u, string e, string p, string m) => + service => service.CreateMemberWithIdentity(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((string u, string e, string p, string m, bool b) => { createdMember = new Member("test", e, u, p, memberType); }) diff --git a/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs b/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs index 22dd740310..818c5f5d58 100644 --- a/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs +++ b/src/Umbraco.Web/Cache/CacheRefresherEventHandler.cs @@ -115,8 +115,8 @@ namespace Umbraco.Web.Cache //Bind to member events - Member.AfterSave += MemberAfterSave; - Member.BeforeDelete += MemberBeforeDelete; + MemberService.Saved += MemberServiceSaved; + MemberService.Deleted += MemberServiceDeleted; //Bind to media events @@ -132,6 +132,8 @@ namespace Umbraco.Web.Cache ContentService.Copied += ContentServiceCopied; } + + #region Content service event handlers /// @@ -540,37 +542,45 @@ namespace Umbraco.Web.Cache #endregion #region Media event handlers - static void MediaServiceTrashing(IMediaService sender, Core.Events.MoveEventArgs e) + static void MediaServiceTrashing(IMediaService sender, Core.Events.MoveEventArgs e) { DistributedCache.Instance.RemoveMediaCache(e.Entity); } - static void MediaServiceMoving(IMediaService sender, Core.Events.MoveEventArgs e) + static void MediaServiceMoving(IMediaService sender, Core.Events.MoveEventArgs e) { DistributedCache.Instance.RefreshMediaCache(e.Entity); } - static void MediaServiceDeleting(IMediaService sender, Core.Events.DeleteEventArgs e) + static void MediaServiceDeleting(IMediaService sender, Core.Events.DeleteEventArgs e) { DistributedCache.Instance.RemoveMediaCache(e.DeletedEntities.ToArray()); } - static void MediaServiceSaved(IMediaService sender, Core.Events.SaveEventArgs e) + static void MediaServiceSaved(IMediaService sender, Core.Events.SaveEventArgs e) { DistributedCache.Instance.RefreshMediaCache(e.SavedEntities.ToArray()); } #endregion #region Member event handlers - static void MemberBeforeDelete(Member sender, DeleteEventArgs e) + + void MemberServiceDeleted(IMemberService sender, Core.Events.DeleteEventArgs e) { - DistributedCache.Instance.RemoveMemberCache(sender.Id); + foreach (var m in e.DeletedEntities.ToArray()) + { + DistributedCache.Instance.RemoveMemberCache(m.Id); + } } - static void MemberAfterSave(Member sender, SaveEventArgs e) + void MemberServiceSaved(IMemberService sender, Core.Events.SaveEventArgs e) { - DistributedCache.Instance.RefreshMemberCache(sender.Id); - } + foreach (var m in e.SavedEntities.ToArray()) + { + DistributedCache.Instance.RefreshMemberCache(m.Id); + } + } + #endregion } } \ No newline at end of file diff --git a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs index f4f70e32ba..a1339ec8cd 100644 --- a/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs +++ b/src/Umbraco.Web/Cache/DistributedCacheExtensions.cs @@ -255,6 +255,7 @@ namespace Umbraco.Web.Cache { dc.Remove(new Guid(DistributedCache.MemberCacheRefresherId), memberId); } + #endregion #region Media Cache diff --git a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs index b199b32f8b..dd92a50c57 100644 --- a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs @@ -148,7 +148,7 @@ namespace Umbraco.Web.Security.Providers string salt; var encodedPassword = EncryptOrHashNewPassword(password, out salt); - var member = MemberService.CreateMember( + var member = MemberService.CreateMemberWithIdentity( username, email, FormatPasswordForStorage(encodedPassword, salt), diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/create/memberTasks.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/create/memberTasks.cs index c60c8474eb..cb602098b8 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/create/memberTasks.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/create/memberTasks.cs @@ -78,15 +78,24 @@ namespace umbraco string loginName = nameAndMail.Length > 2 ? nameAndMail[3] : ""; if (Membership.Provider.IsUmbracoMembershipProvider() && TypeID != -1) { - var dt = new MemberType(TypeID); - var provider = (providers.members.UmbracoMembershipProvider) Membership.Provider; + var dt = new MemberType(TypeID); + var provider = (UmbracoMembershipProviderBase)Membership.Provider; MembershipCreateStatus status; + + //First create with the membership provider //TODO: We are not supporting q/a - passing in empty here var created = provider.CreateUser(dt.Alias, loginName.Replace(" ", "").ToLower(), //dunno why we're doing this but that's how it has been so i'll leave it i guess password, email, "", "", true, Guid.NewGuid(), out status); + if (status != MembershipCreateStatus.Success) + { + throw new Exception("Error creating Member: " + status); + } + //update the name var member = Member.GetMemberFromLoginName(created.UserName); + member.Text = name; + member.Save(); var e = new NewMemberUIEventArgs(); this.OnNewMember(e, password, member); @@ -95,7 +104,7 @@ namespace umbraco } else { - var mc = new MembershipCreateStatus(); + MembershipCreateStatus mc; Membership.CreateUser(name, password, email, "empty", "empty", true, out mc); if (mc != MembershipCreateStatus.Success) { From 668265f1acae41acfc41e16dbae49fc62f7e1367 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 15:11:54 +1100 Subject: [PATCH 16/71] Allows forcing pass change with new provider, updates conventions to not allow editing of question/answer - unfortunately cannot make the other ones readonly because noEdit data type is the wrong clr type. --- src/Umbraco.Core/Constants-Conventions.cs | 4 ++-- .../Security/Providers/MembersMembershipProvider.cs | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Core/Constants-Conventions.cs b/src/Umbraco.Core/Constants-Conventions.cs index c2b5fa9f54..7ecac29782 100644 --- a/src/Umbraco.Core/Constants-Conventions.cs +++ b/src/Umbraco.Core/Constants-Conventions.cs @@ -228,7 +228,7 @@ namespace Umbraco.Core }, { PasswordAnswer, - new PropertyType(new Guid(PropertyEditors.Textbox), DataTypeDatabaseType.Nvarchar) + new PropertyType(new Guid(PropertyEditors.NoEdit), DataTypeDatabaseType.Nvarchar) { Alias = PasswordAnswer, Name = PasswordAnswerLabel @@ -236,7 +236,7 @@ namespace Umbraco.Core }, { PasswordQuestion, - new PropertyType(new Guid(PropertyEditors.Textbox), DataTypeDatabaseType.Nvarchar) + new PropertyType(new Guid(PropertyEditors.NoEdit), DataTypeDatabaseType.Nvarchar) { Alias = PasswordQuestion, Name = PasswordQuestionLabel diff --git a/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs index 84de8f3367..70cf2201ee 100644 --- a/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/MembersMembershipProvider.cs @@ -36,6 +36,14 @@ namespace Umbraco.Web.Security.Providers get { return "MembersMembershipProvider"; } } + /// + /// For backwards compatibility, this provider supports this option + /// + public override bool AllowManuallyChangingPassword + { + get { return true; } + } + protected override MembershipUser ConvertToMembershipUser(IMember entity) { return entity.AsConcreteMembershipUser(Name); From 0be8039c8fd619192caff9b7b010844838109155 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 15:31:49 +1100 Subject: [PATCH 17/71] Changes how IProfile works which is now just exposed by the IUser instead of implemented, this cleans up the Id situation. --- src/Umbraco.Core/Models/Membership/IUser.cs | 13 ++--- src/Umbraco.Core/Models/Membership/User.cs | 53 ++++++++++++++------- src/Umbraco.Core/Services/UserService.cs | 4 +- 3 files changed, 45 insertions(+), 25 deletions(-) diff --git a/src/Umbraco.Core/Models/Membership/IUser.cs b/src/Umbraco.Core/Models/Membership/IUser.cs index ab9c02b1b2..4aee69705e 100644 --- a/src/Umbraco.Core/Models/Membership/IUser.cs +++ b/src/Umbraco.Core/Models/Membership/IUser.cs @@ -7,18 +7,14 @@ namespace Umbraco.Core.Models.Membership /// Defines the interface for a /// /// Will be left internal until a proper Membership implementation is part of the roadmap - public interface IUser : IMembershipUser, IProfile + public interface IUser : IMembershipUser { - new int Id { get; set; } - + string Name { get; set; } int SessionTimeout { get; set; } int StartContentId { get; set; } int StartMediaId { get; set; } string Language { get; set; } - //NOTE: I have removed this because it is obsolete in v7 and we are basically removing live editing for now - //bool DefaultToLiveEditing { get; set; } - IUserType UserType { get; } /// @@ -32,5 +28,10 @@ namespace Umbraco.Core.Models.Membership IEnumerable AllowedSections { get; } void RemoveAllowedSection(string sectionAlias); void AddAllowedSection(string sectionAlias); + + /// + /// Exposes the basic profile data + /// + IProfile ProfileData { get; } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index b35fd04bba..6d2f104013 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -58,7 +58,6 @@ namespace Umbraco.Core.Models.Membership private string _username; private string _email; private string _password; - private Guid _key; private bool _isApproved; private bool _isLockedOut; private string _language; @@ -239,14 +238,8 @@ namespace Umbraco.Core.Models.Membership public int FailedPasswordAttempts { get; set; } #endregion - - #region Implementation of IProfile - - object IProfile.Id - { - get { return Id; } - set { Id = (int)value; } - } + + #region Implementation of IUser [DataMember] public string Name @@ -255,17 +248,13 @@ namespace Umbraco.Core.Models.Membership set { SetPropertyValueAndDetectChanges(o => - { - _name = value; - return _name; - }, _name, NameSelector); + { + _name = value; + return _name; + }, _name, NameSelector); } } - #endregion - - #region Implementation of IUser - public IEnumerable AllowedSections { get { return _sectionCollection; } @@ -284,6 +273,11 @@ namespace Umbraco.Core.Models.Membership } } + public IProfile ProfileData + { + get { return new UserProfile(this); } + } + /// /// Used internally to check if we need to add a section in the repository to the db /// @@ -465,5 +459,30 @@ namespace Umbraco.Core.Models.Membership _removedSections.Add(e.OldItems.Cast().First()); } } + + /// + /// Internal class used to wrap the user in a profile + /// + private class UserProfile : IProfile + { + private readonly IUser _user; + + public UserProfile(IUser user) + { + _user = user; + } + + public object Id + { + get { return _user.Id; } + set { _user.Id = (int)value; } + } + + public string Name + { + get { return _user.Name; } + set { _user.Name = value; } + } + } } } \ No newline at end of file diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 589ed43046..fd43b496b1 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -343,13 +343,13 @@ namespace Umbraco.Core.Services public IProfile GetProfileById(int id) { var user = GetUserById(id); - return user; + return user.ProfileData; } public IProfile GetProfileByUserName(string login) { var user = GetByUsername(login); - return user; + return user.ProfileData; } public IUser GetUserById(int id) From 7c4412fc4be2cd37b1078323f9bf24bc68c02b55 Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 16:09:59 +1100 Subject: [PATCH 18/71] Ensures that Save() is called wherever member data is saved --- .../umbraco.presentation/library.cs | 6 +- .../umbracobase/baseLibrary.cs | 4 +- .../umbracobase/restExtension.cs | 8 +- src/umbraco.cms/businesslogic/web/Access.cs | 127 +++++++----------- .../members/MembershipEventHandler.cs | 1 + 5 files changed, 56 insertions(+), 90 deletions(-) diff --git a/src/Umbraco.Web/umbraco.presentation/library.cs b/src/Umbraco.Web/umbraco.presentation/library.cs index 5cc1b85e8e..3874ad7b3a 100644 --- a/src/Umbraco.Web/umbraco.presentation/library.cs +++ b/src/Umbraco.Web/umbraco.presentation/library.cs @@ -529,14 +529,14 @@ namespace umbraco string.Format( "{0}_{1}", CacheKeys.MemberLibraryCacheKey, MemberId), TimeSpan.FromSeconds(UmbracoSettings.UmbracoLibraryCacheDuration), - () => getMemberDo(MemberId)); + () => GetMemberDo(MemberId)); if (retVal != null) return retVal.CreateNavigator().Select("/"); } else { - return getMemberDo(MemberId).CreateNavigator().Select("/"); + return GetMemberDo(MemberId).CreateNavigator().Select("/"); } } @@ -548,7 +548,7 @@ namespace umbraco return xd.CreateNavigator().Select("/"); } - private static XmlDocument getMemberDo(int MemberId) + private static XmlDocument GetMemberDo(int MemberId) { Member m = new Member(MemberId); XmlDocument mXml = new XmlDocument(); diff --git a/src/Umbraco.Web/umbraco.presentation/umbracobase/baseLibrary.cs b/src/Umbraco.Web/umbraco.presentation/umbracobase/baseLibrary.cs index 888280df77..d16440e52b 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbracobase/baseLibrary.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbracobase/baseLibrary.cs @@ -127,14 +127,14 @@ namespace umbraco.presentation.umbracobase.library { myProperty.Value = value; retVal = "True"; - myMember.XmlGenerate(new XmlDocument()); + myMember.Save(); } } else { myProperty.Value = value; retVal = "True"; - myMember.XmlGenerate(new XmlDocument()); + myMember.Save(); } } diff --git a/src/Umbraco.Web/umbraco.presentation/umbracobase/restExtension.cs b/src/Umbraco.Web/umbraco.presentation/umbracobase/restExtension.cs index 8a02b65c14..0374ba5339 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbracobase/restExtension.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbracobase/restExtension.cs @@ -91,7 +91,7 @@ namespace umbraco.presentation.umbracobase allowed = false; } else //do member authentication stuff... - allowed = memberAuthentication(baseExt, currentMem); + allowed = MemberAuthentication(baseExt, currentMem); } } else @@ -138,7 +138,7 @@ namespace umbraco.presentation.umbracobase else { //do member authentication stuff... - allowed = memberAuthentication(attribute, currentMem); + allowed = MemberAuthentication(attribute, currentMem); } } @@ -186,7 +186,7 @@ namespace umbraco.presentation.umbracobase } } - private static bool memberAuthentication(RestExtensionMethod baseExt, Member currentMem) + private static bool MemberAuthentication(RestExtensionMethod baseExt, Member currentMem) { //Check group, type and ID bool memberAccess = false; @@ -235,7 +235,7 @@ namespace umbraco.presentation.umbracobase return memberAccess; } - private static bool memberAuthentication(XmlNode baseExt, Member currentMem) + private static bool MemberAuthentication(XmlNode baseExt, Member currentMem) { //Check group, type and ID bool memberAccess = false; diff --git a/src/umbraco.cms/businesslogic/web/Access.cs b/src/umbraco.cms/businesslogic/web/Access.cs index 8f0cffd4b2..555818952d 100644 --- a/src/umbraco.cms/businesslogic/web/Access.cs +++ b/src/umbraco.cms/businesslogic/web/Access.cs @@ -15,25 +15,18 @@ namespace umbraco.cms.businesslogic.web /// public class Access { - public Access() - { - // - // TODO: Add constructor logic here - // - } - - static private Hashtable _checkedPages = new Hashtable(); + static private readonly Hashtable CheckedPages = new Hashtable(); //must be volatile for double check lock to work static private volatile XmlDocument _accessXmlContent; static private string _accessXmlSource; - private static void clearCheckPages() + private static void ClearCheckPages() { - _checkedPages.Clear(); + CheckedPages.Clear(); } - static object _locko = new object(); + static readonly object Locko = new object(); public static XmlDocument AccessXml { @@ -41,7 +34,7 @@ namespace umbraco.cms.businesslogic.web { if (_accessXmlContent == null) { - lock (_locko) + lock (Locko) { if (_accessXmlContent == null) { @@ -80,7 +73,7 @@ namespace umbraco.cms.businesslogic.web new Access().FireBeforeAddMemberShipRoleToDocument(new Document(documentId), role, e); if (!e.Cancel) { - XmlElement x = (XmlElement)getPage(documentId); + XmlElement x = (XmlElement)GetPage(documentId); if (x == null) throw new Exception("Document is not protected!"); @@ -89,7 +82,7 @@ namespace umbraco.cms.businesslogic.web XmlElement groupXml = (XmlElement)AccessXml.CreateNode(XmlNodeType.Element, "group", ""); groupXml.SetAttribute("id", role); x.AppendChild(groupXml); - save(); + Save(); } } @@ -100,7 +93,7 @@ namespace umbraco.cms.businesslogic.web [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void AddMemberGroupToDocument(int DocumentId, int MemberGroupId) { - XmlElement x = (XmlElement) getPage(DocumentId); + XmlElement x = (XmlElement) GetPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); @@ -111,7 +104,7 @@ namespace umbraco.cms.businesslogic.web XmlElement groupXml = (XmlElement) AccessXml.CreateNode(XmlNodeType.Element, "group", ""); groupXml.SetAttribute("id", MemberGroupId.ToString()); x.AppendChild(groupXml); - save(); + Save(); } } } @@ -119,7 +112,7 @@ namespace umbraco.cms.businesslogic.web [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void AddMemberToDocument(int DocumentId, int MemberId) { - XmlElement x = (XmlElement) getPage(DocumentId); + XmlElement x = (XmlElement) GetPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); @@ -129,7 +122,7 @@ namespace umbraco.cms.businesslogic.web x.Attributes.GetNamedItem("memberId").Value = MemberId.ToString(); else x.SetAttribute("memberId", MemberId.ToString()); - save(); + Save(); } } @@ -139,7 +132,7 @@ namespace umbraco.cms.businesslogic.web new Access().FireBeforeAddMembershipUserToDocument(new Document(documentId), membershipUserName, e); if (!e.Cancel) { - XmlElement x = (XmlElement)getPage(documentId); + XmlElement x = (XmlElement)GetPage(documentId); if (x == null) throw new Exception("Document is not protected!"); @@ -148,7 +141,7 @@ namespace umbraco.cms.businesslogic.web x.Attributes.GetNamedItem("memberId").Value = membershipUserName; else x.SetAttribute("memberId", membershipUserName); - save(); + Save(); } new Access().FireAfterAddMembershipUserToDocument(new Document(documentId), membershipUserName, e); @@ -159,7 +152,7 @@ namespace umbraco.cms.businesslogic.web [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void RemoveMemberGroupFromDocument(int DocumentId, int MemberGroupId) { - XmlElement x = (XmlElement) getPage(DocumentId); + XmlElement x = (XmlElement) GetPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); @@ -169,7 +162,7 @@ namespace umbraco.cms.businesslogic.web if (xGroup != null) { x.RemoveChild(xGroup); - save(); + Save(); } } } @@ -180,7 +173,7 @@ namespace umbraco.cms.businesslogic.web new Access().FireBeforeRemoveMemberShipRoleFromDocument(new Document(documentId), role, e); if (!e.Cancel) { - XmlElement x = (XmlElement)getPage(documentId); + XmlElement x = (XmlElement)GetPage(documentId); if (x == null) throw new Exception("Document is not protected!"); @@ -188,7 +181,7 @@ namespace umbraco.cms.businesslogic.web XmlNode xGroup = x.SelectSingleNode("group [@id = '" + role + "']"); if (xGroup != null) { x.RemoveChild(xGroup); - save(); + Save(); } } @@ -208,7 +201,7 @@ namespace umbraco.cms.businesslogic.web hasChange = true; } if (hasChange) - save(); + Save(); } return hasChange; @@ -222,7 +215,7 @@ namespace umbraco.cms.businesslogic.web if (!e.Cancel) { - XmlElement x = (XmlElement)getPage(DocumentId); + XmlElement x = (XmlElement)GetPage(DocumentId); if (x == null) { x = (XmlElement)_accessXmlContent.CreateNode(XmlNodeType.Element, "page", ""); AccessXml.DocumentElement.AppendChild(x); @@ -235,9 +228,9 @@ namespace umbraco.cms.businesslogic.web x.SetAttribute("loginPage", LoginDocumentId.ToString()); x.SetAttribute("noRightsPage", ErrorDocumentId.ToString()); x.SetAttribute("simple", Simple.ToString()); - save(); + Save(); - clearCheckPages(); + ClearCheckPages(); new Access().FireAfterAddProtection(new Document(DocumentId), e); } @@ -245,7 +238,7 @@ namespace umbraco.cms.businesslogic.web public static void RemoveProtection(int DocumentId) { - XmlElement x = (XmlElement) getPage(DocumentId); + XmlElement x = (XmlElement) GetPage(DocumentId); if (x != null) { //event @@ -255,8 +248,8 @@ namespace umbraco.cms.businesslogic.web if (!e.Cancel) { x.ParentNode.RemoveChild(x); - save(); - clearCheckPages(); + Save(); + ClearCheckPages(); new Access().FireAfterRemoveProtection(new Document(DocumentId), e); } @@ -264,7 +257,7 @@ namespace umbraco.cms.businesslogic.web } } - private static void save() + private static void Save() { SaveEventArgs e = new SaveEventArgs(); @@ -290,7 +283,7 @@ namespace umbraco.cms.businesslogic.web isProtected = false; else { - XmlNode currentNode = getPage(getProtectedPage(d.Path)); + XmlNode currentNode = GetPage(GetProtectedPage(d.Path)); if (currentNode.SelectSingleNode("./group [@id=" + GroupId.ToString() + "]") != null) { isProtected = true; @@ -308,7 +301,7 @@ namespace umbraco.cms.businesslogic.web if (!IsProtected(documentId, d.Path)) isProtected = false; else { - XmlNode currentNode = getPage(getProtectedPage(d.Path)); + XmlNode currentNode = GetPage(GetProtectedPage(d.Path)); if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null) { isProtected = true; } @@ -323,7 +316,7 @@ namespace umbraco.cms.businesslogic.web if (!IsProtected(documentId, path)) return null; else { - XmlNode currentNode = getPage(getProtectedPage(path)); + XmlNode currentNode = GetPage(GetProtectedPage(path)); foreach (XmlNode n in currentNode.SelectNodes("./group")) { roles.Add(n.Attributes.GetNamedItem("id").Value); } @@ -341,7 +334,7 @@ namespace umbraco.cms.businesslogic.web return null; else { - XmlNode currentNode = getPage(getProtectedPage(d.Path)); + XmlNode currentNode = GetPage(GetProtectedPage(d.Path)); cms.businesslogic.member.MemberGroup[] mg = new umbraco.cms.businesslogic.member.MemberGroup[currentNode.SelectNodes("./group").Count]; int count = 0; foreach (XmlNode n in currentNode.SelectNodes("./group")) @@ -363,7 +356,7 @@ namespace umbraco.cms.businesslogic.web else if (GetProtectionType(DocumentId) != ProtectionType.Simple) throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead"); else { - XmlNode currentNode = getPage(getProtectedPage(d.Path)); + XmlNode currentNode = GetPage(GetProtectedPage(d.Path)); if (currentNode.Attributes.GetNamedItem("memberId") != null) return new cms.businesslogic.member.Member(int.Parse( currentNode.Attributes.GetNamedItem("memberId").Value)); @@ -382,7 +375,7 @@ namespace umbraco.cms.businesslogic.web else if (GetProtectionType(documentId) != ProtectionType.Simple) throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead"); else { - XmlNode currentNode = getPage(getProtectedPage(d.Path)); + XmlNode currentNode = GetPage(GetProtectedPage(d.Path)); if (currentNode.Attributes.GetNamedItem("memberId") != null) return Membership.GetUser(currentNode.Attributes.GetNamedItem("memberId").Value); else @@ -404,7 +397,7 @@ namespace umbraco.cms.businesslogic.web hasAccess = true; else { - XmlNode currentNode = getPage(getProtectedPage(d.Path)); + XmlNode currentNode = GetPage(GetProtectedPage(d.Path)); if (Member != null) { IDictionaryEnumerator ide = Member.Groups.GetEnumerator(); @@ -431,7 +424,7 @@ namespace umbraco.cms.businesslogic.web return true; else { MembershipUser member = Membership.GetUser(memberId); - XmlNode currentNode = getPage(getProtectedPage(node.Path)); + XmlNode currentNode = GetPage(GetProtectedPage(node.Path)); if (member != null) { foreach(string role in Roles.GetRolesForUser()) { @@ -445,41 +438,13 @@ namespace umbraco.cms.businesslogic.web return hasAccess; } - [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] - private static bool HasAccess(int DocumentId, string Path, cms.businesslogic.member.Member Member) - { - bool hasAccess = false; - - if (!IsProtected(DocumentId, Path)) - hasAccess = true; - else - { - XmlNode currentNode = getPage(getProtectedPage(Path)); - if (Member != null) - { - IDictionaryEnumerator ide = Member.Groups.GetEnumerator(); - while(ide.MoveNext()) - { - cms.businesslogic.member.MemberGroup mg = (cms.businesslogic.member.MemberGroup) ide.Value; - if (currentNode.SelectSingleNode("./group [@id=" + mg.Id.ToString() + "]") != null) - { - hasAccess = true; - break; - } - } - } - } - - return hasAccess; - } - - public static bool HasAccess(int documentId, string path, MembershipUser member) { + public static bool HasAccess(int documentId, string path, MembershipUser member) { bool hasAccess = false; if (!IsProtected(documentId, path)) hasAccess = true; else { - XmlNode currentNode = getPage(getProtectedPage(path)); + XmlNode currentNode = GetPage(GetProtectedPage(path)); if (member != null) { string[] roles = Roles.GetRolesForUser(member.UserName); foreach(string role in roles) { @@ -496,7 +461,7 @@ namespace umbraco.cms.businesslogic.web public static ProtectionType GetProtectionType(int DocumentId) { - XmlNode x = getPage(DocumentId); + XmlNode x = GetPage(DocumentId); try { if (bool.Parse(x.Attributes.GetNamedItem("simple").Value)) @@ -515,11 +480,11 @@ namespace umbraco.cms.businesslogic.web { bool isProtected = false; - if (!_checkedPages.ContainsKey(DocumentId)) + if (!CheckedPages.ContainsKey(DocumentId)) { foreach(string id in Path.Split(',')) { - if (getPage(int.Parse(id)) != null) + if (GetPage(int.Parse(id)) != null) { isProtected = true; break; @@ -529,39 +494,39 @@ namespace umbraco.cms.businesslogic.web // Add thread safe updating to the hashtable if (System.Web.HttpContext.Current != null) System.Web.HttpContext.Current.Application.Lock(); - if (!_checkedPages.ContainsKey(DocumentId)) - _checkedPages.Add(DocumentId, isProtected); + if (!CheckedPages.ContainsKey(DocumentId)) + CheckedPages.Add(DocumentId, isProtected); if (System.Web.HttpContext.Current != null) System.Web.HttpContext.Current.Application.UnLock(); } else - isProtected = (bool) _checkedPages[DocumentId]; + isProtected = (bool) CheckedPages[DocumentId]; return isProtected; } public static int GetErrorPage(string Path) { - return int.Parse(getPage(getProtectedPage(Path)).Attributes.GetNamedItem("noRightsPage").Value); + return int.Parse(GetPage(GetProtectedPage(Path)).Attributes.GetNamedItem("noRightsPage").Value); } public static int GetLoginPage(string Path) { - return int.Parse(getPage(getProtectedPage(Path)).Attributes.GetNamedItem("loginPage").Value); + return int.Parse(GetPage(GetProtectedPage(Path)).Attributes.GetNamedItem("loginPage").Value); } - private static int getProtectedPage(string Path) + private static int GetProtectedPage(string Path) { int protectedPage = 0; foreach(string id in Path.Split(',')) - if (getPage(int.Parse(id)) != null) + if (GetPage(int.Parse(id)) != null) protectedPage = int.Parse(id); return protectedPage; } - private static XmlNode getPage(int documentId) + private static XmlNode GetPage(int documentId) { XmlNode x = AccessXml.SelectSingleNode("/access/page [@id=" + documentId.ToString() + "]"); return x; diff --git a/src/umbraco.providers/members/MembershipEventHandler.cs b/src/umbraco.providers/members/MembershipEventHandler.cs index 71330dd8e0..7d8687f788 100644 --- a/src/umbraco.providers/members/MembershipEventHandler.cs +++ b/src/umbraco.providers/members/MembershipEventHandler.cs @@ -28,6 +28,7 @@ namespace umbraco.providers.members if (property != null) { property.Value = 1; + sender.Save(); } } } From 585b42af483093b292043dd15c5a1fd6e232575c Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 16:13:29 +1100 Subject: [PATCH 19/71] More Save()'s missing and removes the extra calls to XmlGenerate - should save some processing time. --- src/Umbraco.Web/BaseRest/MemberRest.cs | 4 ++-- src/Umbraco.Web/Controllers/ProfileController.cs | 4 +--- .../umbraco/controls/Images/UploadMediaImage.ascx.cs | 2 -- .../umbraco.presentation/umbraco/members/EditMember.aspx.cs | 4 +--- 4 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/Umbraco.Web/BaseRest/MemberRest.cs b/src/Umbraco.Web/BaseRest/MemberRest.cs index 1184c1e03d..e305eb5bd2 100644 --- a/src/Umbraco.Web/BaseRest/MemberRest.cs +++ b/src/Umbraco.Web/BaseRest/MemberRest.cs @@ -100,14 +100,14 @@ namespace Umbraco.Web.BaseRest { prop.Value = value; ret = "True"; - m.XmlGenerate(new XmlDocument()); + m.Save(); } } else { prop.Value = value; ret = "True"; - m.XmlGenerate(new XmlDocument()); + m.Save(); } } diff --git a/src/Umbraco.Web/Controllers/ProfileController.cs b/src/Umbraco.Web/Controllers/ProfileController.cs index cfa2d387ca..f4da61b011 100644 --- a/src/Umbraco.Web/Controllers/ProfileController.cs +++ b/src/Umbraco.Web/Controllers/ProfileController.cs @@ -35,9 +35,7 @@ namespace Umbraco.Web.Controllers } member.Save(); - - member.XmlGenerate(new XmlDocument()); - + Member.AddMemberToCache(member); Response.Redirect("/"); diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Images/UploadMediaImage.ascx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Images/UploadMediaImage.ascx.cs index 7e58989c40..71b32f2b61 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Images/UploadMediaImage.ascx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/controls/Images/UploadMediaImage.ascx.cs @@ -76,8 +76,6 @@ namespace umbraco.controls.Images prop.Value = UploadField.Data.Value; media.Save(); - // Generate xml on image - media.XmlGenerate(new XmlDocument()); pane_upload.Visible = false; //this seems real ugly since we apparently already have the properties above (props)... but this data layer is insane and undecipherable:) diff --git a/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs b/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs index 0154b77382..39bfafd546 100644 --- a/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/umbraco/members/EditMember.aspx.cs @@ -311,9 +311,7 @@ namespace umbraco.cms.presentation.members { _document.getProperty(item.Key).Value = item.Value.Data.Value; } - - // refresh cache - _document.XmlGenerate(new System.Xml.XmlDocument()); + _document.Save(); } else From 64d1a484bdaece5146642f565172794e5d04319a Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 17:11:58 +1100 Subject: [PATCH 20/71] Fixes User Id issues with HasIdentity, wraps legacy UserType to the new service, fixes the uninstalling db schema to not throw exceptions and clog up the unit test log. --- src/Umbraco.Core/Models/Membership/User.cs | 47 +++--- .../Initial/DatabaseSchemaCreation.cs | 5 +- src/Umbraco.Core/Services/IUserService.cs | 56 +++++-- src/Umbraco.Core/Services/UserService.cs | 19 ++- .../Services/UserServiceTests.cs | 1 + .../config/umbracoSettings.config | 2 +- src/umbraco.businesslogic/User.cs | 4 +- src/umbraco.businesslogic/UserType.cs | 143 ++++++------------ 8 files changed, 143 insertions(+), 134 deletions(-) diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index 6d2f104013..d1ecd0971f 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -80,23 +80,42 @@ namespace Umbraco.Core.Models.Membership private static readonly PropertyInfo LanguageSelector = ExpressionHelper.GetPropertyInfo(x => x.Language); private static readonly PropertyInfo DefaultPermissionsSelector = ExpressionHelper.GetPropertyInfo>(x => x.DefaultPermissions); private static readonly PropertyInfo DefaultToLiveEditingSelector = ExpressionHelper.GetPropertyInfo(x => x.DefaultToLiveEditing); + private static readonly PropertyInfo HasIdentitySelector = ExpressionHelper.GetPropertyInfo(x => x.HasIdentity); #region Implementation of IEntity [IgnoreDataMember] - public bool HasIdentity { get { return Id != null || _hasIdentity; } } - - [IgnoreDataMember] - int IEntity.Id + public bool HasIdentity { get { - return int.Parse(Id.ToString()); + return _hasIdentity; + } + protected set + { + SetPropertyValueAndDetectChanges(o => + { + _hasIdentity = value; + return _hasIdentity; + }, _hasIdentity, HasIdentitySelector); + } + } + + [DataMember] + public int Id + { + get + { + return _id; } set { - Id = value; - _hasIdentity = true; + SetPropertyValueAndDetectChanges(o => + { + _id = value; + HasIdentity = true; //set the has Identity + return _id; + }, _id, IdSelector); } } @@ -354,20 +373,6 @@ namespace Umbraco.Core.Models.Membership } } - [DataMember] - public int Id - { - get { return _id; } - set - { - SetPropertyValueAndDetectChanges(o => - { - _id = value; - return _id; - }, _id, IdSelector); - } - } - [DataMember] public string Language { diff --git a/src/Umbraco.Core/Persistence/Migrations/Initial/DatabaseSchemaCreation.cs b/src/Umbraco.Core/Persistence/Migrations/Initial/DatabaseSchemaCreation.cs index df0cf13052..53f1938c00 100644 --- a/src/Umbraco.Core/Persistence/Migrations/Initial/DatabaseSchemaCreation.cs +++ b/src/Umbraco.Core/Persistence/Migrations/Initial/DatabaseSchemaCreation.cs @@ -80,7 +80,10 @@ namespace Umbraco.Core.Persistence.Migrations.Initial try { - _database.DropTable(tableName); + if (_database.TableExist(tableName)) + { + _database.DropTable(tableName); + } } catch (Exception ex) { diff --git a/src/Umbraco.Core/Services/IUserService.cs b/src/Umbraco.Core/Services/IUserService.cs index a55bd4b771..d6ca2514d5 100644 --- a/src/Umbraco.Core/Services/IUserService.cs +++ b/src/Umbraco.Core/Services/IUserService.cs @@ -15,10 +15,45 @@ namespace Umbraco.Core.Services /// Id of the User to retrieve /// IProfile GetProfileById(int id); + + /// + /// Get profile by username + /// + /// + /// IProfile GetProfileByUserName(string username); + /// + /// Get user by Id + /// + /// + /// IUser GetUserById(int id); + + /// + /// This is useful when an entire section is removed from config + /// + /// + void DeleteSectionFromAllUsers(string sectionAlias); + /// + /// Returns a list of the sections that the user is allowed access to + /// + /// + IEnumerable GetUserSections(IUser user); + + /// + /// Get permissions set for user and specified node ids + /// + /// + /// + /// + IEnumerable GetPermissions(IUser user, params int[] nodeIds); + + #region User types + + IEnumerable GetAllUserTypes(params int[] ids); + /// /// Gets an IUserType by its Alias /// @@ -26,6 +61,13 @@ namespace Umbraco.Core.Services /// IUserType GetUserTypeByAlias(string alias); + /// + /// Gets an IUserType by its Id + /// + /// + /// + IUserType GetUserTypeById(int id); + /// /// Gets an IUserType by its Name /// @@ -45,19 +87,7 @@ namespace Umbraco.Core.Services /// /// void DeleteUserType(IUserType userType); - - /// - /// This is useful when an entire section is removed from config - /// - /// - void DeleteSectionFromAllUsers(string sectionAlias); - /// - /// Returns a list of the sections that the user is allowed access to - /// - /// - IEnumerable GetUserSections(IUser user); - - IEnumerable GetPermissions(IUser user, params int[] nodeIds); + #endregion } } \ No newline at end of file diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index fd43b496b1..92ff2d5dc9 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -351,7 +351,7 @@ namespace Umbraco.Core.Services var user = GetByUsername(login); return user.ProfileData; } - + public IUser GetUserById(int id) { using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork())) @@ -360,6 +360,15 @@ namespace Umbraco.Core.Services } } + public IEnumerable GetAllUserTypes(params int[] ids) + { + var uow = _uowProvider.GetUnitOfWork(); + using (var repository = _repositoryFactory.CreateUserTypeRepository(uow)) + { + return repository.GetAll(ids); + } + } + /// /// Gets an IUserType by its Alias /// @@ -375,6 +384,14 @@ namespace Umbraco.Core.Services } } + public IUserType GetUserTypeById(int id) + { + using (var repository = _repositoryFactory.CreateUserTypeRepository(_uowProvider.GetUnitOfWork())) + { + return repository.Get(id); + } + } + /// /// Gets an IUserType by its Name /// diff --git a/src/Umbraco.Tests/Services/UserServiceTests.cs b/src/Umbraco.Tests/Services/UserServiceTests.cs index e76b07e30c..8658957ab9 100644 --- a/src/Umbraco.Tests/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests/Services/UserServiceTests.cs @@ -329,6 +329,7 @@ namespace Umbraco.Tests.Services // Assert Assert.That(membershipUser.HasIdentity, Is.True); + Assert.That(membershipUser.Id, Is.GreaterThan(0)); IUser user = membershipUser as User; Assert.That(user, Is.Not.Null); Assert.That(user.DefaultPermissions, Is.EqualTo(userType.Permissions)); diff --git a/src/Umbraco.Web.UI/config/umbracoSettings.config b/src/Umbraco.Web.UI/config/umbracoSettings.config index ff21ef8249..a467040eba 100644 --- a/src/Umbraco.Web.UI/config/umbracoSettings.config +++ b/src/Umbraco.Web.UI/config/umbracoSettings.config @@ -177,7 +177,7 @@ - + 0 diff --git a/src/umbraco.businesslogic/User.cs b/src/umbraco.businesslogic/User.cs index e2dd21d104..9a5bfc38e6 100644 --- a/src/umbraco.businesslogic/User.cs +++ b/src/umbraco.businesslogic/User.cs @@ -31,7 +31,7 @@ namespace umbraco.BusinessLogic private bool _userDisabled; private bool _defaultToLiveEditing; - private Hashtable _notifications = new Hashtable(); + private readonly Hashtable _notifications = new Hashtable(); private bool _notificationsInitialized = false; [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] @@ -42,7 +42,7 @@ namespace umbraco.BusinessLogic internal User(IUser user) { - _id = (int)user.Id; + _id = user.Id; _userNoConsole = user.IsLockedOut; _userDisabled = user.IsApproved; _name = user.Name; diff --git a/src/umbraco.businesslogic/UserType.cs b/src/umbraco.businesslogic/UserType.cs index e049a4023a..57308423b0 100644 --- a/src/umbraco.businesslogic/UserType.cs +++ b/src/umbraco.businesslogic/UserType.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Data; +using System.Globalization; +using System.Linq; using System.Runtime.CompilerServices; using System.Web; using System.Web.Caching; @@ -17,10 +19,20 @@ namespace umbraco.BusinessLogic public class UserType { + private Umbraco.Core.Models.Membership.IUserType _userType; + /// /// Creates a new empty instance of a UserType /// - public UserType() { } + public UserType() + { + _userType = new Umbraco.Core.Models.Membership.UserType(); + } + + internal UserType(Umbraco.Core.Models.Membership.IUserType userType) + { + _userType = userType; + } /// /// Creates a new instance of a UserType and attempts to @@ -43,8 +55,8 @@ namespace umbraco.BusinessLogic /// The name. public UserType(int id, string name) { - _id = id; - _name = name; + _userType.Id = id; + _userType.Name = name; } /// @@ -56,18 +68,12 @@ namespace umbraco.BusinessLogic /// public UserType(int id, string name, string defaultPermissions, string alias) { - _name = name; - _id = id; - _defaultPermissions = defaultPermissions; - _alias = alias; + _userType.Id = id; + _userType.Name = name; + _userType.Alias = alias; + _userType.Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); } - - private int _id; - private string _name; - private string _defaultPermissions; - private string _alias; - /// /// The cache storage for all user types /// @@ -75,40 +81,20 @@ namespace umbraco.BusinessLogic { get { - return ApplicationContext.Current.ApplicationCache.GetCacheItem( - CacheKeys.UserTypeCacheKey, - () => - { - var tmp = new List(); - using (var dr = SqlHelper.ExecuteReader("select id, userTypeName, userTypeAlias, userTypeDefaultPermissions from umbracoUserType")) - { - while (dr.Read()) - { - tmp.Add(new UserType( - dr.GetShort("id"), - dr.GetString("userTypeName"), - dr.GetString("userTypeDefaultPermissions"), - dr.GetString("userTypeAlias"))); - } - } - return tmp; - }); + return ApplicationContext.Current.Services.UserService.GetAllUserTypes() + .Select(x => new UserType(x)) + .ToList(); } } - - private static ISqlHelper SqlHelper - { - get { return Application.SqlHelper; } - } - + #region Public Properties /// /// Gets or sets the user type alias. /// public string Alias { - get { return _alias; } - set { _alias = value; } + get { return _userType.Alias; } + set { _userType.Alias = value; } } /// @@ -116,8 +102,8 @@ namespace umbraco.BusinessLogic /// public string Name { - get { return _name; } - set { _name = value; } + get { return _userType.Name; } + set { _userType.Name = value; } } /// @@ -125,7 +111,7 @@ namespace umbraco.BusinessLogic /// public int Id { - get { return _id; } + get { return _userType.Id; } } /// @@ -133,8 +119,8 @@ namespace umbraco.BusinessLogic /// public string DefaultPermissions { - get { return _defaultPermissions; } - set { _defaultPermissions = value; } + get { return string.Join("", _userType.Permissions); } + set { _userType.Permissions = value.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); } } /// @@ -153,19 +139,11 @@ namespace umbraco.BusinessLogic public void Save() { //ensure that this object has an ID specified (it exists in the database) - if (_id <= 0) + if (_userType.HasIdentity == false) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); - SqlHelper.ExecuteNonQuery(@" - update umbracoUserType set - userTypeAlias=@alias,userTypeName=@name,userTypeDefaultPermissions=@permissions - where id=@id", - SqlHelper.CreateParameter("@alias", _alias), - SqlHelper.CreateParameter("@name", _name), - SqlHelper.CreateParameter("@permissions", _defaultPermissions), - SqlHelper.CreateParameter("@id", _id) - ); - + ApplicationContext.Current.Services.UserService.SaveUserType(_userType); + //raise event OnUpdated(this, new EventArgs()); } @@ -176,10 +154,10 @@ namespace umbraco.BusinessLogic public void Delete() { //ensure that this object has an ID specified (it exists in the database) - if (_id <= 0) + if (_userType.HasIdentity == false) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); - SqlHelper.ExecuteNonQuery(@"delete from umbracoUserType where id=@id", SqlHelper.CreateParameter("@id", _id)); + ApplicationContext.Current.Services.UserService.DeleteUserType(_userType); //raise event OnDeleted(this, new EventArgs()); @@ -193,16 +171,8 @@ namespace umbraco.BusinessLogic /// and the data was loaded, false if it wasn't public bool LoadByPrimaryKey(int id) { - var userType = GetUserType(id); - if (userType == null) - return false; - - _id = userType.Id; - _alias = userType.Alias; - _defaultPermissions = userType.DefaultPermissions; - _name = userType.Name; - - return true; + _userType = ApplicationContext.Current.Services.UserService.GetUserTypeById(id); + return _userType != null; } /// @@ -221,37 +191,20 @@ namespace umbraco.BusinessLogic if (existing != null) throw new Exception("The UserType alias specified already exists"); - SqlHelper.ExecuteNonQuery(@" - insert into umbracoUserType - (userTypeAlias,userTypeName,userTypeDefaultPermissions) - values (@alias,@name,@permissions)", - SqlHelper.CreateParameter("@alias", alias), - SqlHelper.CreateParameter("@name", name), - SqlHelper.CreateParameter("@permissions", defaultPermissions)); - - //get it's id - var newId = SqlHelper.ExecuteScalar("SELECT MAX(id) FROM umbracoUserType WHERE userTypeAlias=@alias", SqlHelper.CreateParameter("@alias", alias)); - - //load the instance and return it - using (var dr = SqlHelper.ExecuteReader( - "select id, userTypeName, userTypeAlias, userTypeDefaultPermissions from umbracoUserType where id=@id", - SqlHelper.CreateParameter("@id", newId))) + var userType = new Umbraco.Core.Models.Membership.UserType { - if (dr.Read()) - { - var ut = new UserType( - dr.GetShort("id"), - dr.GetString("userTypeName"), - dr.GetString("userTypeDefaultPermissions"), - dr.GetString("userTypeAlias")); + Alias = alias, + Name = name, + Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)) + }; + ApplicationContext.Current.Services.UserService.SaveUserType(userType); - //raise event - OnNew(ut, new EventArgs()); + var legacy = new UserType(userType); + + //raise event + OnNew(legacy, new EventArgs()); - return ut; - } - throw new InvalidOperationException("Could not read the new User Type with id of " + newId); - } + return legacy; } /// From e2ac82abca757897b367405dd3faa95988b2e92d Mon Sep 17 00:00:00 2001 From: Shannon Date: Thu, 23 Jan 2014 18:44:41 +1100 Subject: [PATCH 21/71] Gets most of the User and UserType legacy objects wrapping the new services, yay! Now just need to sort out all the caching stuff which I have tasks for. --- src/Umbraco.Core/Models/Membership/IUser.cs | 5 +- src/Umbraco.Core/Models/Membership/User.cs | 20 +- .../Persistence/RepositoryFactory.cs | 3 + .../Services/IMembershipMemberService.cs | 2 +- src/Umbraco.Core/Services/IUserService.cs | 15 +- src/Umbraco.Core/Services/UserService.cs | 79 +-- .../Services/MemberServiceTests.cs | 4 +- .../Services/UserServiceTests.cs | 1 + .../TestHelpers/BaseDatabaseFactoryTest.cs | 2 + .../config/metablogConfig.config | 2 +- .../UmbracoServiceMembershipProvider.cs | 7 +- src/umbraco.businesslogic/User.cs | 457 +++++++----------- src/umbraco.businesslogic/UserType.cs | 46 +- 13 files changed, 291 insertions(+), 352 deletions(-) diff --git a/src/Umbraco.Core/Models/Membership/IUser.cs b/src/Umbraco.Core/Models/Membership/IUser.cs index 4aee69705e..c48b371f1a 100644 --- a/src/Umbraco.Core/Models/Membership/IUser.cs +++ b/src/Umbraco.Core/Models/Membership/IUser.cs @@ -15,7 +15,10 @@ namespace Umbraco.Core.Models.Membership int StartMediaId { get; set; } string Language { get; set; } - IUserType UserType { get; } + /// + /// Gets/sets the user type for the user + /// + IUserType UserType { get; set; } /// /// The default permission set for the user diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index d1ecd0971f..22cb80c727 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -5,6 +5,7 @@ using System.Collections.Specialized; using System.Linq; using System.Reflection; using System.Runtime.Serialization; +using Umbraco.Core.Configuration; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Persistence.Mappers; @@ -31,6 +32,7 @@ namespace Umbraco.Core.Models.Membership _sectionCollection = new ObservableCollection(); _addedSections = new List(); _removedSections = new List(); + _language = GlobalSettings.DefaultUILanguage; _sectionCollection.CollectionChanged += SectionCollectionChanged; } @@ -40,10 +42,10 @@ namespace Umbraco.Core.Models.Membership _name = name; _email = email; _username = username; - _password = password; + _password = password; } - private readonly IUserType _userType; + private IUserType _userType; private bool _hasIdentity; private int _id; private string _name; @@ -81,6 +83,7 @@ namespace Umbraco.Core.Models.Membership private static readonly PropertyInfo DefaultPermissionsSelector = ExpressionHelper.GetPropertyInfo>(x => x.DefaultPermissions); private static readonly PropertyInfo DefaultToLiveEditingSelector = ExpressionHelper.GetPropertyInfo(x => x.DefaultToLiveEditing); private static readonly PropertyInfo HasIdentitySelector = ExpressionHelper.GetPropertyInfo(x => x.HasIdentity); + private static readonly PropertyInfo UserTypeSelector = ExpressionHelper.GetPropertyInfo(x => x.UserType); #region Implementation of IEntity @@ -419,6 +422,19 @@ namespace Umbraco.Core.Models.Membership public IUserType UserType { get { return _userType; } + set + { + if (value.HasIdentity == false) + { + throw new InvalidOperationException("Cannot assign a User Type that has not been persisted"); + } + + SetPropertyValueAndDetectChanges(o => + { + _userType = value; + return _userType; + }, _userType, UserTypeSelector); + } } #endregion diff --git a/src/Umbraco.Core/Persistence/RepositoryFactory.cs b/src/Umbraco.Core/Persistence/RepositoryFactory.cs index b97e80d187..ce3568925e 100644 --- a/src/Umbraco.Core/Persistence/RepositoryFactory.cs +++ b/src/Umbraco.Core/Persistence/RepositoryFactory.cs @@ -124,6 +124,9 @@ namespace Umbraco.Core.Persistence internal virtual IUserRepository CreateUserRepository(IDatabaseUnitOfWork uow) { + //TODO: Should we cache users? we did in the legacy API, might be a good idea considering the amount we query for the current user but will + // need to check that, in v7 with the new forms auth way we shouldn't be querying for a user a lot of times but now that we're wrapping in v6 + // we need to ensure that the constant user lookups are cached! return new UserRepository( uow, NullCacheProvider.Current, diff --git a/src/Umbraco.Core/Services/IMembershipMemberService.cs b/src/Umbraco.Core/Services/IMembershipMemberService.cs index b27b8f660a..8827d71860 100644 --- a/src/Umbraco.Core/Services/IMembershipMemberService.cs +++ b/src/Umbraco.Core/Services/IMembershipMemberService.cs @@ -51,7 +51,7 @@ namespace Umbraco.Core.Services /// T CreateMemberWithIdentity(string username, string email, string password, string memberTypeAlias, bool raiseEvents = true); - T GetById(object id); + T GetById(int id); /// /// Get a member by email diff --git a/src/Umbraco.Core/Services/IUserService.cs b/src/Umbraco.Core/Services/IUserService.cs index d6ca2514d5..3c40d9d175 100644 --- a/src/Umbraco.Core/Services/IUserService.cs +++ b/src/Umbraco.Core/Services/IUserService.cs @@ -9,6 +9,13 @@ namespace Umbraco.Core.Services /// public interface IUserService : IMembershipUserService { + /// + /// To permanently delete the user pass in true, otherwise they will just be disabled + /// + /// + /// + void Delete(IUser user, bool deletePermanently); + /// /// Gets an IProfile by User Id. /// @@ -35,13 +42,7 @@ namespace Umbraco.Core.Services /// /// void DeleteSectionFromAllUsers(string sectionAlias); - - /// - /// Returns a list of the sections that the user is allowed access to - /// - /// - IEnumerable GetUserSections(IUser user); - + /// /// Get permissions set for user and specified node ids /// diff --git a/src/Umbraco.Core/Services/UserService.cs b/src/Umbraco.Core/Services/UserService.cs index 92ff2d5dc9..5891c88247 100644 --- a/src/Umbraco.Core/Services/UserService.cs +++ b/src/Umbraco.Core/Services/UserService.cs @@ -130,19 +130,14 @@ namespace Umbraco.Core.Services return CreateMemberWithIdentity(username, email, password, userType); } - public IUser GetById(object id) + public IUser GetById(int id) { - if (id is int) + using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork())) { - using (var repository = _repositoryFactory.CreateUserRepository(_uowProvider.GetUnitOfWork())) - { - var user = repository.Get((int) id); + var user = repository.Get((int)id); - return user; - } + return user; } - - return null; } public IUser GetByEmail(string email) @@ -165,19 +160,51 @@ namespace Umbraco.Core.Services } } + /// + /// This disables and renames the user, it does not delete them, use the overload to delete them + /// + /// public void Delete(IUser membershipUser) - { - if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs(membershipUser), this)) - return; - - var uow = _uowProvider.GetUnitOfWork(); - using (var repository = _repositoryFactory.CreateUserRepository(uow)) + { + //disable + membershipUser.IsApproved = false; + //can't rename if it's going to take up too many chars + if (membershipUser.Username.Length + 9 <= 125) { - repository.Delete(membershipUser); - uow.Commit(); + membershipUser.Username = DateTime.Now.ToString("yyyyMMdd") + "_" + membershipUser.Username; } + Save(membershipUser); - DeletedUser.RaiseEvent(new DeleteEventArgs(membershipUser, false), this); + //clear out the user logins! + var uow = _uowProvider.GetUnitOfWork(); + uow.Database.Execute("delete from umbracoUserLogins where userID = @id", new {id = membershipUser.Id}); + } + + /// + /// To permanently delete the user pass in true, otherwise they will just be disabled + /// + /// + /// + public void Delete(IUser user, bool deletePermanently) + { + if (deletePermanently == false) + { + Delete(user); + } + else + { + if (DeletingUser.IsRaisedEventCancelled(new DeleteEventArgs(user), this)) + return; + + var uow = _uowProvider.GetUnitOfWork(); + using (var repository = _repositoryFactory.CreateUserRepository(uow)) + { + repository.Delete(user); + uow.Commit(); + } + + DeletedUser.RaiseEvent(new DeleteEventArgs(user, false), this); + } } public void Save(IUser membershipUser, bool raiseEvents = true) @@ -461,22 +488,6 @@ namespace Umbraco.Core.Services } } - /// - /// Returns the user's applications that they are allowed to access - /// - /// - /// - public IEnumerable GetUserSections(IUser user) - { - //TODO: We need to cache this result - - var uow = _uowProvider.GetUnitOfWork(); - var sql = new Sql(); - sql.Select("app").From() - .Where(dto => dto.UserId == (int)user.Id); - return uow.Database.Fetch(sql); - } - /// /// Returns permissions for a given user for any number of nodes /// diff --git a/src/Umbraco.Tests/Services/MemberServiceTests.cs b/src/Umbraco.Tests/Services/MemberServiceTests.cs index 6529cbeee2..39bddf102e 100644 --- a/src/Umbraco.Tests/Services/MemberServiceTests.cs +++ b/src/Umbraco.Tests/Services/MemberServiceTests.cs @@ -108,8 +108,8 @@ namespace Umbraco.Tests.Services IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); - Assert.IsNotNull(ServiceContext.MemberService.GetById((object)member.Id)); - Assert.IsNull(ServiceContext.MemberService.GetById((object)9876)); + Assert.IsNotNull(ServiceContext.MemberService.GetById(member.Id)); + Assert.IsNull(ServiceContext.MemberService.GetById(9876)); } [Test] diff --git a/src/Umbraco.Tests/Services/UserServiceTests.cs b/src/Umbraco.Tests/Services/UserServiceTests.cs index 8658957ab9..0ebaf58e7e 100644 --- a/src/Umbraco.Tests/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests/Services/UserServiceTests.cs @@ -6,6 +6,7 @@ using NUnit.Framework; using Umbraco.Core.Models.Membership; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Services; +using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using umbraco.BusinessLogic.Actions; diff --git a/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs b/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs index 6bd46836ae..c030ad3c04 100644 --- a/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs +++ b/src/Umbraco.Tests/TestHelpers/BaseDatabaseFactoryTest.cs @@ -78,6 +78,8 @@ namespace Umbraco.Tests.TestHelpers using (DisposableTimer.TraceDuration("init")) { + //TODO: Somehow make this faster - takes 5s + + DatabaseContext.Initialize(dbFactory.ProviderName, dbFactory.ConnectionString); CreateSqlCeDatabase(); InitializeDatabase(); diff --git a/src/Umbraco.Web.UI/config/metablogConfig.config b/src/Umbraco.Web.UI/config/metablogConfig.config index 5621dbee75..82502df5e3 100644 --- a/src/Umbraco.Web.UI/config/metablogConfig.config +++ b/src/Umbraco.Web.UI/config/metablogConfig.config @@ -5,7 +5,7 @@ 0 1080 False - Base + umbBlog diff --git a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs index dd92a50c57..66892d316b 100644 --- a/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UmbracoServiceMembershipProvider.cs @@ -344,7 +344,12 @@ namespace Umbraco.Web.Security.Providers /// public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { - var member = MemberService.GetById(providerUserKey); + if ((providerUserKey is int) == false) + { + return null; + } + + var member = MemberService.GetById((int)providerUserKey); if (member == null) { return null; diff --git a/src/umbraco.businesslogic/User.cs b/src/umbraco.businesslogic/User.cs index 9a5bfc38e6..e4d9557bb9 100644 --- a/src/umbraco.businesslogic/User.cs +++ b/src/umbraco.businesslogic/User.cs @@ -6,6 +6,7 @@ using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Rdbms; +using Umbraco.Core.Persistence.Querying; using umbraco.DataLayer; using System.Collections.Generic; using System.Linq; @@ -18,19 +19,22 @@ namespace umbraco.BusinessLogic /// public class User { - private int _id; - private bool _isInitialized; - private string _name; - private string _loginname; - private int _startnodeid; - private int _startmediaid; - private string _email; - private string _language = ""; - private UserType _usertype; - private bool _userNoConsole; - private bool _userDisabled; - private bool _defaultToLiveEditing; + private IUser _user; + private int? _lazyId; + //private int _id; + //private bool _isInitialized; + //private string _name; + //private string _loginname; + //private int _startnodeid; + //private int _startmediaid; + //private string _email; + //private string _language = ""; + //private UserType _usertype; + //private bool _userNoConsole; + //private bool _userDisabled; + private bool? _defaultToLiveEditing; + private readonly Hashtable _notifications = new Hashtable(); private bool _notificationsInitialized = false; @@ -42,19 +46,20 @@ namespace umbraco.BusinessLogic internal User(IUser user) { - _id = user.Id; - _userNoConsole = user.IsLockedOut; - _userDisabled = user.IsApproved; - _name = user.Name; - _loginname = user.Username; - _email = user.Email; - _language = user.Language; - _startnodeid = user.StartContentId; - _startmediaid = user.StartMediaId; - //this is cached, so should be 'ok' - _usertype = UserType.GetUserType(user.UserType.Id); + _user = user; + //_id = user.Id; + //_userNoConsole = user.IsLockedOut; + //_userDisabled = user.IsApproved; + //_name = user.Name; + //_loginname = user.Username; + //_email = user.Email; + //_language = user.Language; + //_startnodeid = user.StartContentId; + //_startmediaid = user.StartMediaId; + + //_usertype = new UserType(_user.UserType); - _isInitialized = true; + //_isInitialized = true; } /// @@ -63,7 +68,7 @@ namespace umbraco.BusinessLogic /// The ID. public User(int ID) { - setupUser(ID); + SetupUser(ID); } /// @@ -73,7 +78,7 @@ namespace umbraco.BusinessLogic /// if set to true [no setup]. public User(int ID, bool noSetup) { - _id = ID; + _lazyId = ID; } /// @@ -83,7 +88,7 @@ namespace umbraco.BusinessLogic /// The password. public User(string Login, string Password) { - setupUser(getUserId(Login, Password)); + SetupUser(getUserId(Login, Password)); } /// @@ -92,33 +97,16 @@ namespace umbraco.BusinessLogic /// The login. public User(string Login) { - setupUser(getUserId(Login)); + SetupUser(getUserId(Login)); } - private void setupUser(int ID) + private void SetupUser(int ID) { - _id = ID; - - var dto = ApplicationContext.Current.DatabaseContext.Database.FirstOrDefault("WHERE id = @id", new { id = ID}); - if (dto != null) - { - _userNoConsole = dto.NoConsole; - _userDisabled = dto.Disabled; - _name = dto.UserName; - _loginname = dto.Login; - _email = dto.Email; - _language = dto.UserLanguage; - _startnodeid = dto.ContentStartId; - if (dto.MediaStartId.HasValue) - _startmediaid = dto.MediaStartId.Value; - _usertype = UserType.GetUserType(dto.Type); - _defaultToLiveEditing = dto.DefaultToLiveEditing; - } - else + _user = ApplicationContext.Current.Services.UserService.GetById(ID); + if (_user == null) { throw new ArgumentException("No User exists with ID " + ID); } - _isInitialized = true; } /// @@ -126,6 +114,7 @@ namespace umbraco.BusinessLogic /// public void Save() { + FlushFromCache(); OnSaving(EventArgs.Empty); } @@ -137,18 +126,13 @@ namespace umbraco.BusinessLogic { get { - if (_isInitialized == false) - setupUser(_id); - return _name; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.Name; } set { - _name = value; - - ApplicationContext.Current.DatabaseContext.Database.Update( - "SET UserName = @userName WHERE id = @id", new { userName = value, id = Id}); - - FlushFromCache(); + _user.Name = value; + } } @@ -160,18 +144,12 @@ namespace umbraco.BusinessLogic { get { - if (_isInitialized == false) - setupUser(_id); - return _email; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.Email; } set { - _email = value; - - ApplicationContext.Current.DatabaseContext.Database.Update( - "SET UserEmail = @email WHERE id = @id", new { email = value, id = Id }); - - FlushFromCache(); + _user.Email = value; } } @@ -183,18 +161,12 @@ namespace umbraco.BusinessLogic { get { - if (_isInitialized == false) - setupUser(_id); - return _language; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.Language; } set { - _language = value; - - ApplicationContext.Current.DatabaseContext.Database.Update( - "SET userLanguage = @language WHERE id = @id", new { language = value, id = Id }); - - FlushFromCache(); + _user.Language = value; } } @@ -210,10 +182,7 @@ namespace umbraco.BusinessLogic } set { - ApplicationContext.Current.DatabaseContext.Database.Update( - "SET UserPassword = @pw WHERE id = @id", new { pw = value, id = Id }); - - FlushFromCache(); + _user.Language = value; } } @@ -223,8 +192,8 @@ namespace umbraco.BusinessLogic /// public string GetPassword() { - return ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar( - "SELECT UserPassword FROM umbracoUser WHERE id = @id", new {id = Id}); + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.Password; } /// @@ -277,17 +246,16 @@ namespace umbraco.BusinessLogic /// public List GetApplications() { - if (_isInitialized == false) - setupUser(_id); + if (_lazyId.HasValue) SetupUser(_lazyId.Value); var allApps = Application.getAll(); var apps = new List(); - var dtos = ApplicationContext.Current.DatabaseContext.Database.Fetch( - "SELECT * FROM umbracoUser2app WHERE [user] = @userID", new {userID = Id}); - foreach (var dto in dtos) + var sections = _user.AllowedSections; + + foreach (var s in sections) { - var app = allApps.SingleOrDefault(x => x.alias == dto.AppAlias); + var app = allApps.SingleOrDefault(x => x.alias == s); if (app != null) apps.Add(app); } @@ -303,21 +271,15 @@ namespace umbraco.BusinessLogic { get { - if (_isInitialized == false) - setupUser(_id); - return _loginname; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.Username; } set { if (EnsureUniqueLoginName(value, this) == false) throw new Exception(String.Format("A user with the login '{0}' already exists", value)); - _loginname = value; - - ApplicationContext.Current.DatabaseContext.Database.Update( - "SET UserLogin = @login WHERE id = @id", new { login = value, id = Id }); - - FlushFromCache(); + _user.Username = value; } } @@ -382,18 +344,12 @@ namespace umbraco.BusinessLogic { get { - if (_isInitialized == false) - setupUser(_id); - return _usertype; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return new UserType(_user.UserType); } set { - _usertype = value; - - ApplicationContext.Current.DatabaseContext.Database.Update( - "SET userType = @type WHERE id = @id", new { type = value.Id, id = Id }); - - FlushFromCache(); + _user.UserType = value.UserTypeItem; } } @@ -404,17 +360,13 @@ namespace umbraco.BusinessLogic /// public static User[] getAll() { - IRecordsReader dr = SqlHelper.ExecuteReader("Select id from umbracoUser"); + int totalRecs; + var users = ApplicationContext.Current.Services.UserService.GetAllMembers( + 0, int.MaxValue, out totalRecs); - var users = new List(); - - while (dr.Read()) - { - users.Add(User.GetUser(dr.GetInt("id"))); - } - dr.Close(); - - return users.OrderBy(x => x.Name).ToArray(); + return users.Select(x => new User(x)) + .OrderBy(x => x.Name) + .ToArray(); } @@ -455,22 +407,21 @@ namespace umbraco.BusinessLogic /// public static User[] getAllByEmail(string email, bool useExactMatch) { - var retVal = new List(); - var tmpContainer = new ArrayList(); - - IRecordsReader dr = useExactMatch - ? SqlHelper.ExecuteReader("Select id from umbracoUser where userEmail = @email", - SqlHelper.CreateParameter("@email", email)) - : SqlHelper.ExecuteReader("Select id from umbracoUser where userEmail LIKE {0} @email", - SqlHelper.CreateParameter("@email", String.Format("%{0}%", email))); - - while (dr.Read()) + int totalRecs; + if (useExactMatch) { - retVal.Add(GetUser(dr.GetInt("id"))); + return ApplicationContext.Current.Services.UserService.FindMembersByEmail( + email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact) + .Select(x => new User(x)) + .ToArray(); + } + else + { + return ApplicationContext.Current.Services.UserService.FindMembersByEmail( + string.Format("%{0}%", email), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard) + .Select(x => new User(x)) + .ToArray(); } - dr.Close(); - - return retVal.ToArray(); } /// @@ -487,7 +438,7 @@ namespace umbraco.BusinessLogic /// Gets all users by login name. /// /// The login. - /// whether to use a partial match + /// whether to use a partial match /// public static User[] getAllByLoginName(string login, bool partialMatch) { @@ -496,36 +447,21 @@ namespace umbraco.BusinessLogic public static IEnumerable GetAllByLoginName(string login, bool partialMatch) { - - var users = new List(); - + int totalRecs; if (partialMatch) { - using (var dr = SqlHelper.ExecuteReader( - "Select id from umbracoUser where userLogin LIKE @login", SqlHelper.CreateParameter("@login", String.Format("%{0}%", login)))) - { - while (dr.Read()) - { - users.Add(BusinessLogic.User.GetUser(dr.GetInt("id"))); - } - } - + return ApplicationContext.Current.Services.UserService.FindMembersByUsername( + string.Format("%{0}%", login), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard) + .Select(x => new User(x)) + .ToArray(); } else { - using (var dr = SqlHelper.ExecuteReader( - "Select id from umbracoUser where userLogin=@login", SqlHelper.CreateParameter("@login", login))) - { - while (dr.Read()) - { - users.Add(BusinessLogic.User.GetUser(dr.GetInt("id"))); - } - } + return ApplicationContext.Current.Services.UserService.FindMembersByUsername( + login, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact) + .Select(x => new User(x)) + .ToArray(); } - - return users; - - } /// @@ -535,21 +471,12 @@ namespace umbraco.BusinessLogic /// The login name. /// The password. /// The user type. - [MethodImpl(MethodImplOptions.Synchronized)] public static User MakeNew(string name, string lname, string passw, UserType ut) { + var user = new Umbraco.Core.Models.Membership.User(name, "", lname, passw, ut.UserTypeItem); + ApplicationContext.Current.Services.UserService.Save(user); - SqlHelper.ExecuteNonQuery(@" - insert into umbracoUser - (UserType,startStructureId,startMediaId, UserName, userLogin, userPassword, userEmail,userLanguage) - values (@type,-1,-1,@name,@lname,@pw,'',@lang)", - SqlHelper.CreateParameter("@lang", GlobalSettings.DefaultUILanguage), - SqlHelper.CreateParameter("@name", name), - SqlHelper.CreateParameter("@lname", lname), - SqlHelper.CreateParameter("@type", ut.Id), - SqlHelper.CreateParameter("@pw", passw)); - - var u = new User(lname); + var u = new User(user); u.OnNew(EventArgs.Empty); return u; @@ -563,22 +490,13 @@ namespace umbraco.BusinessLogic /// The lname. /// The passw. /// The email. - /// The ut. - [MethodImpl(MethodImplOptions.Synchronized)] + /// The ut. public static User MakeNew(string name, string lname, string passw, string email, UserType ut) { - SqlHelper.ExecuteNonQuery(@" - insert into umbracoUser - (UserType,startStructureId,startMediaId, UserName, userLogin, userPassword, userEmail,userLanguage) - values (@type,-1,-1,@name,@lname,@pw,@email,@lang)", - SqlHelper.CreateParameter("@lang", GlobalSettings.DefaultUILanguage), - SqlHelper.CreateParameter("@name", name), - SqlHelper.CreateParameter("@lname", lname), - SqlHelper.CreateParameter("@email", email), - SqlHelper.CreateParameter("@type", ut.Id), - SqlHelper.CreateParameter("@pw", passw)); + var user = new Umbraco.Core.Models.Membership.User(name, email, lname, passw, ut.UserTypeItem); + ApplicationContext.Current.Services.UserService.Save(user); - var u = new User(lname); + var u = new User(user); u.OnNew(EventArgs.Empty); return u; @@ -595,32 +513,32 @@ namespace umbraco.BusinessLogic /// The ut. public static void Update(int id, string name, string lname, string email, UserType ut) { - if (!EnsureUniqueLoginName(lname, User.GetUser(id))) + if (EnsureUniqueLoginName(lname, GetUser(id)) == false) throw new Exception(String.Format("A user with the login '{0}' already exists", lname)); - - SqlHelper.ExecuteNonQuery(@"Update umbracoUser set userName=@name, userLogin=@lname, userEmail=@email, UserType=@type where id = @id", - SqlHelper.CreateParameter("@name", name), - SqlHelper.CreateParameter("@lname", lname), - SqlHelper.CreateParameter("@email", email), - SqlHelper.CreateParameter("@type", ut.Id), - SqlHelper.CreateParameter("@id", id)); + var found = ApplicationContext.Current.Services.UserService.GetById(id); + if (found == null) return; + found.Name = name; + found.Username = lname; + found.Email = email; + found.UserType = ut.UserTypeItem; + ApplicationContext.Current.Services.UserService.Save(found); } public static void Update(int id, string name, string lname, string email, bool disabled, bool noConsole, UserType ut) { - if (!EnsureUniqueLoginName(lname, User.GetUser(id))) + if (EnsureUniqueLoginName(lname, GetUser(id)) == false) throw new Exception(String.Format("A user with the login '{0}' already exists", lname)); - - SqlHelper.ExecuteNonQuery(@"Update umbracoUser set userName=@name, userLogin=@lname, userEmail=@email, UserType=@type, userDisabled=@disabled, userNoConsole=@noconsole where id = @id", - SqlHelper.CreateParameter("@name", name), - SqlHelper.CreateParameter("@lname", lname), - SqlHelper.CreateParameter("@email", email), - SqlHelper.CreateParameter("@type", ut.Id), - SqlHelper.CreateParameter("@disabled", disabled), - SqlHelper.CreateParameter("@noconsole", noConsole), - SqlHelper.CreateParameter("@id", id)); + var found = ApplicationContext.Current.Services.UserService.GetById(id); + if (found == null) return; + found.Name = name; + found.Username = lname; + found.Email = email; + found.UserType = ut.UserTypeItem; + found.IsApproved = disabled == false; + found.IsLockedOut = noConsole; + ApplicationContext.Current.Services.UserService.Save(found); } /// @@ -632,11 +550,13 @@ namespace umbraco.BusinessLogic /// public static void Update(int id, string email, bool disabled, bool noConsole) { - SqlHelper.ExecuteNonQuery(@"Update umbracoUser set userEmail=@email, userDisabled=@disabled, userNoConsole=@noconsole where id = @id", - SqlHelper.CreateParameter("@email", email), - SqlHelper.CreateParameter("@disabled", disabled), - SqlHelper.CreateParameter("@noconsole", noConsole), - SqlHelper.CreateParameter("@id", id)); + var found = ApplicationContext.Current.Services.UserService.GetById(id); + if (found == null) return; + + found.Email = email; + found.IsApproved = disabled == false; + found.IsLockedOut = noConsole; + ApplicationContext.Current.Services.UserService.Save(found); } /// @@ -647,9 +567,8 @@ namespace umbraco.BusinessLogic /// a user ID public static int getUserId(string lname, string passw) { - return getUserId("select id from umbracoUser where userDisabled = 0 and userNoConsole = 0 and userLogin = @login and userPassword = @pw", - SqlHelper.CreateParameter("@login", lname), - SqlHelper.CreateParameter("@pw", passw)); + var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname); + return found.Password == passw ? found.Id : -1; } /// @@ -659,16 +578,10 @@ namespace umbraco.BusinessLogic /// a user ID public static int getUserId(string lname) { - return getUserId("select id from umbracoUser where userLogin = @login", - SqlHelper.CreateParameter("@login", lname)); + var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname); + return found == null ? -1 : found.Id; } - - private static int getUserId(string query, params IParameter[] parameterValues) - { - object userId = SqlHelper.ExecuteScalar(query, parameterValues); - return (userId != null && userId != DBNull.Value) ? int.Parse(userId.ToString()) : -1; - } - + /// /// Deletes this instance. /// @@ -681,18 +594,8 @@ namespace umbraco.BusinessLogic OnDeleting(EventArgs.Empty); - //would be better in the notifications class but since we can't reference the cms project (poorly architected) we need to use raw sql - SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodeNotify where userId = @userId", SqlHelper.CreateParameter("@userId", Id)); + ApplicationContext.Current.Services.UserService.Delete(_user, true); - //would be better in the permissions class but since we can't reference the cms project (poorly architected) we need to use raw sql - SqlHelper.ExecuteNonQuery("delete from umbracoUser2NodePermission where userId = @userId", SqlHelper.CreateParameter("@userId", Id)); - - //delete the assigned applications - clearApplications(); - - SqlHelper.ExecuteNonQuery("delete from umbracoUserLogins where userID = @id", SqlHelper.CreateParameter("@id", Id)); - - SqlHelper.ExecuteNonQuery("delete from umbracoUser where id = @id", SqlHelper.CreateParameter("@id", Id)); FlushFromCache(); } @@ -702,17 +605,9 @@ namespace umbraco.BusinessLogic public void disable() { OnDisabling(EventArgs.Empty); - //change disabled and userLogin (prefix with yyyyMMdd_ ) - this.Disabled = true; - //MUST clear out the umbraco logins otherwise if they are still logged in they can still do stuff: - //http://issues.umbraco.org/issue/U4-2042 - SqlHelper.ExecuteNonQuery("delete from umbracoUserLogins where userID = @id", SqlHelper.CreateParameter("@id", Id)); - //can't rename if it's going to take up too many chars - if (this.LoginName.Length + 9 <= 125) - { - this.LoginName = DateTime.Now.ToString("yyyyMMdd") + "_" + this.LoginName; - } - this.Save(); + + //delete without the true overload will perform the disable operation + ApplicationContext.Current.Services.UserService.Delete(_user); } /// @@ -722,13 +617,15 @@ namespace umbraco.BusinessLogic /// public string GetPermissions(string Path) { - if (!_isInitialized) - setupUser(_id); + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + string defaultPermissions = UserType.DefaultPermissions; + //TODO: Wrap all this with the new services! + //get the cached permissions for the user var cachedPermissions = ApplicationContext.Current.ApplicationCache.GetCacheItem( - string.Format("{0}{1}", CacheKeys.UserPermissionsCacheKey, _id), + string.Format("{0}{1}", CacheKeys.UserPermissionsCacheKey, _user.Id), //Since this cache can be quite large (http://issues.umbraco.org/issue/U4-2161) we will make this priority below average CacheItemPriority.BelowNormal, null, @@ -785,7 +682,7 @@ namespace umbraco.BusinessLogic { string notifications = ""; - if (!_notificationsInitialized) + if (_notificationsInitialized == false) initNotifications(); foreach (string nodeId in Path.Split(',')) @@ -811,8 +708,9 @@ namespace umbraco.BusinessLogic /// public void initNotifications() { - if (!_isInitialized) - setupUser(_id); + //TODO: Wrap all this with new services! + + if (_lazyId.HasValue) SetupUser(_lazyId.Value); using (IRecordsReader dr = SqlHelper.ExecuteReader("select * from umbracoUser2NodeNotify where userId = @userId order by nodeId", SqlHelper.CreateParameter("@userId", this.Id))) { @@ -834,7 +732,7 @@ namespace umbraco.BusinessLogic /// The id. public int Id { - get { return _id; } + get { return _user.Id; } } /// @@ -842,7 +740,14 @@ namespace umbraco.BusinessLogic /// public void clearApplications() { - SqlHelper.ExecuteNonQuery("delete from umbracoUser2app where [user] = @id", SqlHelper.CreateParameter("@id", this.Id)); + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + + foreach (var s in _user.AllowedSections.ToArray()) + { + _user.RemoveAllowedSection(s); + } + + ApplicationContext.Current.Services.UserService.Save(_user); } /// @@ -851,7 +756,11 @@ namespace umbraco.BusinessLogic /// The app alias. public void addApplication(string AppAlias) { - SqlHelper.ExecuteNonQuery("insert into umbracoUser2app ([user],app) values (@id, @app)", SqlHelper.CreateParameter("@id", this.Id), SqlHelper.CreateParameter("@app", AppAlias)); + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + + _user.AddAllowedSection(AppAlias); + + ApplicationContext.Current.Services.UserService.Save(_user); } /// @@ -862,15 +771,12 @@ namespace umbraco.BusinessLogic { get { - if (!_isInitialized) - setupUser(_id); - return _userNoConsole; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.IsLockedOut; } set { - _userNoConsole = value; - SqlHelper.ExecuteNonQuery("update umbracoUser set userNoConsole = @userNoConsole where id = @id", SqlHelper.CreateParameter("@id", this.Id), SqlHelper.CreateParameter("@userNoConsole", _userNoConsole)); - FlushFromCache(); + _user.IsLockedOut = value; } } @@ -882,31 +788,26 @@ namespace umbraco.BusinessLogic { get { - if (!_isInitialized) - setupUser(_id); - return _userDisabled; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.IsApproved == false; } set { - _userDisabled = value; - SqlHelper.ExecuteNonQuery("update umbracoUser set userDisabled = @userDisabled where id = @id", SqlHelper.CreateParameter("@id", this.Id), SqlHelper.CreateParameter("@userDisabled", _userDisabled)); - FlushFromCache(); + _user.IsApproved = value == false; } } - /// - /// Gets or sets a value indicating whether a user should be redirected to liveediting by default. - /// - /// - /// true if defaults to live editing; otherwise, false. - /// + //NOTE: we cannot wrap this because it's no longer supported so we'll just go directly to the db public bool DefaultToLiveEditing { get - { - if (!_isInitialized) - setupUser(_id); - return _defaultToLiveEditing; + { + if (_defaultToLiveEditing.HasValue == false) + { + _defaultToLiveEditing = SqlHelper.ExecuteScalar("select defaultToLiveEditing from umbracoUser where id = @id", + SqlHelper.CreateParameter("@id", Id)); + } + return _defaultToLiveEditing.Value; } set { @@ -924,16 +825,12 @@ namespace umbraco.BusinessLogic { get { - if (!_isInitialized) - setupUser(_id); - return _startnodeid; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.StartContentId; } set { - - _startnodeid = value; - SqlHelper.ExecuteNonQuery("update umbracoUser set startStructureId = @start where id = @id", SqlHelper.CreateParameter("@start", value), SqlHelper.CreateParameter("@id", this.Id)); - FlushFromCache(); + _user.StartContentId = value; } } @@ -945,16 +842,12 @@ namespace umbraco.BusinessLogic { get { - if (!_isInitialized) - setupUser(_id); - return _startmediaid; + if (_lazyId.HasValue) SetupUser(_lazyId.Value); + return _user.StartMediaId; } set { - - _startmediaid = value; - SqlHelper.ExecuteNonQuery("update umbracoUser set startMediaId = @start where id = @id", SqlHelper.CreateParameter("@start", value), SqlHelper.CreateParameter("@id", this.Id)); - FlushFromCache(); + _user.StartMediaId = value; } } @@ -975,6 +868,8 @@ namespace umbraco.BusinessLogic /// public static User GetUser(int id) { + //TODO: Ref: http://issues.umbraco.org/issue/U4-4123 + return ApplicationContext.Current.ApplicationCache.GetCacheItem( string.Format("{0}{1}", CacheKeys.UserCacheKey, id.ToString()), () => { diff --git a/src/umbraco.businesslogic/UserType.cs b/src/umbraco.businesslogic/UserType.cs index 57308423b0..7bf95b74d8 100644 --- a/src/umbraco.businesslogic/UserType.cs +++ b/src/umbraco.businesslogic/UserType.cs @@ -19,19 +19,19 @@ namespace umbraco.BusinessLogic public class UserType { - private Umbraco.Core.Models.Membership.IUserType _userType; + internal Umbraco.Core.Models.Membership.IUserType UserTypeItem; /// /// Creates a new empty instance of a UserType /// public UserType() { - _userType = new Umbraco.Core.Models.Membership.UserType(); + UserTypeItem = new Umbraco.Core.Models.Membership.UserType(); } internal UserType(Umbraco.Core.Models.Membership.IUserType userType) { - _userType = userType; + UserTypeItem = userType; } /// @@ -55,8 +55,9 @@ namespace umbraco.BusinessLogic /// The name. public UserType(int id, string name) { - _userType.Id = id; - _userType.Name = name; + UserTypeItem = new Umbraco.Core.Models.Membership.UserType(); + UserTypeItem.Id = id; + UserTypeItem.Name = name; } /// @@ -68,10 +69,11 @@ namespace umbraco.BusinessLogic /// public UserType(int id, string name, string defaultPermissions, string alias) { - _userType.Id = id; - _userType.Name = name; - _userType.Alias = alias; - _userType.Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); + UserTypeItem = new Umbraco.Core.Models.Membership.UserType(); + UserTypeItem.Id = id; + UserTypeItem.Name = name; + UserTypeItem.Alias = alias; + UserTypeItem.Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); } /// @@ -93,8 +95,8 @@ namespace umbraco.BusinessLogic /// public string Alias { - get { return _userType.Alias; } - set { _userType.Alias = value; } + get { return UserTypeItem.Alias; } + set { UserTypeItem.Alias = value; } } /// @@ -102,8 +104,8 @@ namespace umbraco.BusinessLogic /// public string Name { - get { return _userType.Name; } - set { _userType.Name = value; } + get { return UserTypeItem.Name; } + set { UserTypeItem.Name = value; } } /// @@ -111,7 +113,7 @@ namespace umbraco.BusinessLogic /// public int Id { - get { return _userType.Id; } + get { return UserTypeItem.Id; } } /// @@ -119,8 +121,8 @@ namespace umbraco.BusinessLogic /// public string DefaultPermissions { - get { return string.Join("", _userType.Permissions); } - set { _userType.Permissions = value.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); } + get { return string.Join("", UserTypeItem.Permissions); } + set { UserTypeItem.Permissions = value.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); } } /// @@ -139,10 +141,10 @@ namespace umbraco.BusinessLogic public void Save() { //ensure that this object has an ID specified (it exists in the database) - if (_userType.HasIdentity == false) + if (UserTypeItem.HasIdentity == false) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); - ApplicationContext.Current.Services.UserService.SaveUserType(_userType); + ApplicationContext.Current.Services.UserService.SaveUserType(UserTypeItem); //raise event OnUpdated(this, new EventArgs()); @@ -154,10 +156,10 @@ namespace umbraco.BusinessLogic public void Delete() { //ensure that this object has an ID specified (it exists in the database) - if (_userType.HasIdentity == false) + if (UserTypeItem.HasIdentity == false) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); - ApplicationContext.Current.Services.UserService.DeleteUserType(_userType); + ApplicationContext.Current.Services.UserService.DeleteUserType(UserTypeItem); //raise event OnDeleted(this, new EventArgs()); @@ -171,8 +173,8 @@ namespace umbraco.BusinessLogic /// and the data was loaded, false if it wasn't public bool LoadByPrimaryKey(int id) { - _userType = ApplicationContext.Current.Services.UserService.GetUserTypeById(id); - return _userType != null; + UserTypeItem = ApplicationContext.Current.Services.UserService.GetUserTypeById(id); + return UserTypeItem != null; } /// From 43c426b46c2280793994c2fa23b2628a2c20d63e Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 24 Jan 2014 12:36:02 +1100 Subject: [PATCH 22/71] Update booting.aspx Throw the exception immediately if the parameter is not there or empty. If the parameter is not there it's defaulted to the current url, and this will redirect to itself and create an endless loop here. --- src/Umbraco.Web.UI/config/splashes/booting.aspx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web.UI/config/splashes/booting.aspx b/src/Umbraco.Web.UI/config/splashes/booting.aspx index 267e36b369..1bea61f89d 100644 --- a/src/Umbraco.Web.UI/config/splashes/booting.aspx +++ b/src/Umbraco.Web.UI/config/splashes/booting.aspx @@ -2,7 +2,7 @@ <% // NH: Adds this inline check to avoid a simple codebehind file in the legacy project! - if (!umbraco.cms.helpers.url.ValidateProxyUrl(Request["url"], Request.Url.AbsoluteUri)) + if (Request["url"].ToLower().Contains("booting.aspx") || !umbraco.cms.helpers.url.ValidateProxyUrl(Request["url"], Request.Url.AbsoluteUri)) { throw new ArgumentException("Can't redirect to the requested url - it's not local or an approved proxy url", "url"); From 3cdcf513ec25ebd7783a5710efb39876b0a6103b Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 28 Jan 2014 09:00:17 +1100 Subject: [PATCH 23/71] removes ancient test project --- test/umbraco.Test/AuthoringTests.txt | 30 - test/umbraco.Test/DataTypeDefinitionTest.cs | 359 ------- test/umbraco.Test/DocumentTest.cs | 999 ------------------ test/umbraco.Test/DocumentTypeTest.cs | 815 -------------- test/umbraco.Test/LanguageTest.cs | 324 ------ test/umbraco.Test/MacroPropertyTypeTest.cs | 154 --- test/umbraco.Test/MacroTest.cs | 428 -------- test/umbraco.Test/MediaTest.cs | 488 --------- test/umbraco.Test/MediaTypeTest.cs | 284 ----- test/umbraco.Test/MemberGroupTest.cs | 259 ----- test/umbraco.Test/MemberTest.cs | 626 ----------- test/umbraco.Test/MemberTypeTest.cs | 260 ----- test/umbraco.Test/NotificationTest.cs | 199 ---- test/umbraco.Test/PermissionTest.cs | 174 --- test/umbraco.Test/Properties/AssemblyInfo.cs | 19 - test/umbraco.Test/PropertyTypeTest.cs | 342 ------ test/umbraco.Test/RelationTest.cs | 310 ------ test/umbraco.Test/StyleSheetTest.cs | 302 ------ test/umbraco.Test/TagTest.cs | 368 ------- test/umbraco.Test/TaskTest.cs | 312 ------ test/umbraco.Test/TaskTypeTest.cs | 231 ---- test/umbraco.Test/TemplateTest.cs | 577 ---------- .../Test References/businesslogic.accessor | 2 - .../Test References/umbraco.accessor | 2 - test/umbraco.Test/Umbraco.LegacyTests.csproj | 233 ---- .../UmbracoMembershipProviderTest.cs | 612 ----------- test/umbraco.Test/UserTest.cs | 770 -------------- 27 files changed, 9479 deletions(-) delete mode 100644 test/umbraco.Test/AuthoringTests.txt delete mode 100644 test/umbraco.Test/DataTypeDefinitionTest.cs delete mode 100644 test/umbraco.Test/DocumentTest.cs delete mode 100644 test/umbraco.Test/DocumentTypeTest.cs delete mode 100644 test/umbraco.Test/LanguageTest.cs delete mode 100644 test/umbraco.Test/MacroPropertyTypeTest.cs delete mode 100644 test/umbraco.Test/MacroTest.cs delete mode 100644 test/umbraco.Test/MediaTest.cs delete mode 100644 test/umbraco.Test/MediaTypeTest.cs delete mode 100644 test/umbraco.Test/MemberGroupTest.cs delete mode 100644 test/umbraco.Test/MemberTest.cs delete mode 100644 test/umbraco.Test/MemberTypeTest.cs delete mode 100644 test/umbraco.Test/NotificationTest.cs delete mode 100644 test/umbraco.Test/PermissionTest.cs delete mode 100644 test/umbraco.Test/Properties/AssemblyInfo.cs delete mode 100644 test/umbraco.Test/PropertyTypeTest.cs delete mode 100644 test/umbraco.Test/RelationTest.cs delete mode 100644 test/umbraco.Test/StyleSheetTest.cs delete mode 100644 test/umbraco.Test/TagTest.cs delete mode 100644 test/umbraco.Test/TaskTest.cs delete mode 100644 test/umbraco.Test/TaskTypeTest.cs delete mode 100644 test/umbraco.Test/TemplateTest.cs delete mode 100644 test/umbraco.Test/Test References/businesslogic.accessor delete mode 100644 test/umbraco.Test/Test References/umbraco.accessor delete mode 100644 test/umbraco.Test/Umbraco.LegacyTests.csproj delete mode 100644 test/umbraco.Test/UmbracoMembershipProviderTest.cs delete mode 100644 test/umbraco.Test/UserTest.cs diff --git a/test/umbraco.Test/AuthoringTests.txt b/test/umbraco.Test/AuthoringTests.txt deleted file mode 100644 index 2fe8f08b49..0000000000 --- a/test/umbraco.Test/AuthoringTests.txt +++ /dev/null @@ -1,30 +0,0 @@ -How to run these 'old' style unit tests. They require an HTTP Context so there are a few steps to take to make sure they work. - -1. Make sure you have an umbraco instance configured, you will need some bare minimum data such as at least one content type, -media type, content node (your best bet is to install runway or CWS or something) - -3. Create a new .testrunconfig file with your machine name in the 'Solution Items' folder -** Double click on your new .testrunconfig file and go to the Hosts section, update the config: -*** 'Run in default host' -*** Host type: ASP.NET -*** URL to test: the base url that your umbraco instance runs on (i.e. http://localhost:59454 ) -*** Run tests in ASP.NET Development Server, Path to Web site: the physical folder path to the 'presentation' -folder of the 4.1 branch (the root of the umbraco site) -*** Web application root: / - -4. In the 'Test' menu item of Visual Studio, change te 'Select active test settings' to your machines configuration file - -5. Run all tests in the solution (You MUST use the VS test runner, not the resharper test runner. -You can do this from the 'Test' menu item and select run all tests in solution) -and see if it works (For some reason on my machine in VS2010, i can't have the website running while i run the -unit tests, in VS2008 this did work) -** If the tests don't work, you'll need to investigate why... could be just a config issue, a data issue or could -just be bugs and the tests only work on my machine :) - -**** DEBUGGING INFO ******* - -debugging unit tests for ASP.Net (because it runs in a context) can't be debugged directly in the same VS as your running the tests. - -Unfortunately the only way to do it is to add this line to your unit test you want to debug: - -System.Diagnostics.Debugger.Launch(); \ No newline at end of file diff --git a/test/umbraco.Test/DataTypeDefinitionTest.cs b/test/umbraco.Test/DataTypeDefinitionTest.cs deleted file mode 100644 index 7005219199..0000000000 --- a/test/umbraco.Test/DataTypeDefinitionTest.cs +++ /dev/null @@ -1,359 +0,0 @@ -using umbraco.cms.businesslogic.datatype; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using umbraco.interfaces; -using umbraco.editorControls.textfield; -using umbraco.cms.businesslogic.web; -using System.Linq; -using umbraco.cms.businesslogic.propertytype; -using umbraco.editorControls; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for DataTypeDefinitionTest and is intended - ///to contain all DataTypeDefinitionTest Unit Tests - /// - [TestClass()] - public class DataTypeDefinitionTest - { - - /// - ///A test for MakeNew - /// - [TestMethod()] - public void DataTypeDefinition_Make_New() - { - //create data tyep definition - var dtd = DataTypeDefinition.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - Assert.IsTrue(dtd.Id > 0); - Assert.IsInstanceOfType(dtd, typeof(DataTypeDefinition)); - - //now delete it - dtd.delete(); - Assert.IsFalse(DataTypeDefinition.IsNode(dtd.Id)); - } - - /// - /// Create a data type definition, add some prevalues to it then delete it - /// - [TestMethod()] - public void DataTypeDefinition_Assign_Data_Type_With_PreValues() - { - //System.Diagnostics.Debugger.Launch(); - - //create datatype definition, assign data type - var dtd = DataTypeDefinition.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - Assert.IsTrue(dtd.Id > 0); - Assert.IsInstanceOfType(dtd, typeof(DataTypeDefinition)); - IDataType dt = new TextFieldDataType(); - dt.DataTypeDefinitionId = dtd.Id; //need to set the data types data type definition id - dtd.DataType = dt; //set our data type definition's data type to the text field... i know this is all too weird. - - Assert.AreEqual(dt.Id, dtd.DataType.Id); - Assert.IsInstanceOfType(dtd.DataType, dt.GetType()); - Assert.AreEqual(dtd.Id, dt.DataTypeDefinitionId); - - //create the prevalues - ((DefaultPrevalueEditor)dt.PrevalueEditor).Prevalue = "TEST" + Guid.NewGuid().ToString("N"); - dt.PrevalueEditor.Save(); - - //verify that the prevalue is there - Assert.AreEqual(1, PreValues.GetPreValues(dtd.Id).Count); - - //now remove it - dtd.delete(); - Assert.IsFalse(DataTypeDefinition.IsNode(dtd.Id)); - } - - /// - /// Create a new definition, assign a data type to it, - /// create a doc type and assign this new data type to it, - /// then create a document from the doc type and set the value for the property. - /// - /// Once the data is all setup, we'll delete the data type definition which should: - /// 1. Remove all property type values associated with the property type of the dtd - /// 2. Remove all property types from document types associated with the dtd - /// 3. Remove the dtd - /// - /// then we'll clean up the rest of the data. - /// - [TestMethod()] - public void DataTypeDefinition_Assign_Data_Type_To_Doc_Type_Then_Create_Doc_And_Set_Value() - { - //create datatype definition, assign data type - var dtd = DataTypeDefinition.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - Assert.IsTrue(dtd.Id > 0); - Assert.IsInstanceOfType(dtd, typeof(DataTypeDefinition)); - IDataType dt = new TextFieldDataType(); - dtd.DataType = dt; - Assert.AreEqual(dt.Id, dtd.DataType.Id); - Assert.IsInstanceOfType(dtd.DataType, dt.GetType()); - - //create new doc type - var docType = DocumentType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - - //create the property with this new data type definition - var alias = "TEST" + Guid.NewGuid().ToString("N"); - docType.AddPropertyType(dtd, alias, alias); - Assert.AreEqual(1, docType.PropertyTypes.Count()); - - //create a new doc with the new doc type - var doc = Document.MakeNew("TEST" + Guid.NewGuid().ToString("N"), docType, m_User, -1); - - //set the value of the property - var prop = doc.getProperty(alias); - var propType = prop.PropertyType; - Assert.IsNotNull(prop); - var val = "TEST" + Guid.NewGuid().ToString("N"); - prop.Value = val; - Assert.AreEqual(val, prop.Value); - - //ok, now that all of the data is setup, we'll just delete the data type definition. - dtd.delete(); - - //make sure the property value is gone, check with sql - Assert.AreEqual(0, Application.SqlHelper.ExecuteScalar( - "SELECT COUNT(id) FROM cmsPropertyData WHERE propertytypeid=@propTypeId", - Application.SqlHelper.CreateParameter("@propTypeId", propType.Id))); - - //make sure the property type is gone - var hasError = false; - try - { - var confirmPropType = new PropertyType(propType.Id); - } - catch (ArgumentException) - { - hasError = true; - } - Assert.IsTrue(hasError); - - //make sure the dtd is gone - Assert.IsFalse(DataTypeDefinition.IsNode(dtd.Id)); - - //now cleanup the rest - doc.delete(true); - Assert.IsFalse(Document.IsNode(doc.Id)); - docType.delete(); - Assert.IsFalse(DocumentType.IsNode(docType.Id)); - } - - #region Private methods/members - private User m_User = new User(0); - #endregion - - #region Tests to write - ///// - /////A test for DataTypeDefinition Constructor - ///// - //[TestMethod()] - //public void DataTypeDefinitionConstructorTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition target = new DataTypeDefinition(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for DataTypeDefinition Constructor - ///// - //[TestMethod()] - //public void DataTypeDefinitionConstructorTest1() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // DataTypeDefinition target = new DataTypeDefinition(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Delete - ///// - //[TestMethod()] - //public void DeleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition target = new DataTypeDefinition(id); // TODO: Initialize to an appropriate value - // target.Delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // DataTypeDefinition[] expected = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition[] actual; - // actual = DataTypeDefinition.GetAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetByDataTypeId - ///// - //[TestMethod()] - //public void GetByDataTypeIdTest() - //{ - // Guid DataTypeId = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition expected = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition actual; - // actual = DataTypeDefinition.GetByDataTypeId(DataTypeId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetDataTypeDefinition - ///// - //[TestMethod()] - //public void GetDataTypeDefinitionTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // DataTypeDefinition expected = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition actual; - // actual = DataTypeDefinition.GetDataTypeDefinition(id); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetDataTypeDefinition - ///// - //[TestMethod()] - //public void GetDataTypeDefinitionTest1() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition expected = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition actual; - // actual = DataTypeDefinition.GetDataTypeDefinition(id); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Import - ///// - //[TestMethod()] - //public void ImportTest() - //{ - // XmlNode xmlData = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition expected = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition actual; - // actual = DataTypeDefinition.Import(xmlData); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for IsDefaultData - ///// - //[TestMethod()] - //public void IsDefaultDataTest() - //{ - // object Data = null; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = DataTypeDefinition.IsDefaultData(Data); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for MakeNew - ///// - //[TestMethod()] - //public void MakeNewTest1() - //{ - // User u = null; // TODO: Initialize to an appropriate value - // string Text = string.Empty; // TODO: Initialize to an appropriate value - // Guid UniqueId = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition expected = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition actual; - // actual = DataTypeDefinition.MakeNew(u, Text, UniqueId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition target = new DataTypeDefinition(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ToXml - ///// - //[TestMethod()] - //public void ToXmlTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition target = new DataTypeDefinition(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // XmlElement expected = null; // TODO: Initialize to an appropriate value - // XmlElement actual; - // actual = target.ToXml(xd); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DataTypeDefinition target = new DataTypeDefinition(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - - #endregion - - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/DocumentTest.cs b/test/umbraco.Test/DocumentTest.cs deleted file mode 100644 index bfc0a55ddb..0000000000 --- a/test/umbraco.Test/DocumentTest.cs +++ /dev/null @@ -1,999 +0,0 @@ -using umbraco.cms.businesslogic.web; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using umbraco.cms.businesslogic; -using System.Collections.Generic; -using System.Xml; -using System.Linq; -using System.Threading; -using umbraco.cms.businesslogic.datatype; -using umbraco.editorControls.textfield; -using umbraco.cms.businesslogic.property; -using umbraco.cms.businesslogic.language; -using umbraco.BusinessLogic.console; - -namespace Umbraco.LegacyTests -{ - - - /// - /// Test for the Document API. - /// - /// - /// All of these tests are run in the ASP.Net context and these tests will require that there is data - /// in the Umbraco instance being tested including both document types and content. - /// - /// This WILL make alot of SQL calls. - /// - /// All of these tests will also delete any data that they create - /// - [TestClass()] - public class DocumentTest - { - - /// - /// Creates a bunch of nodes in a heirarchy, then deletes the top most node (moves to the recycle bin - /// and completely deletes from system.) This should completely delete all of these nodes from the database. - /// - [TestMethod()] - public void Document_Delete_Heirarchy_Permanently() - { - var docList = new List(); - var total = 20; - var dt = new DocumentType(GetExistingDocTypeId()); - //allow the doc type to be created underneath itself - dt.AllowedChildContentTypeIDs = new int[] { dt.Id }; - dt.Save(); - - //create 20 content nodes underneath each other, this will test deleting with heirarchy as well - var lastParentId = -1; - for (var i = 0; i < total; i++) - { - var newDoc = Document.MakeNew(i.ToString() + Guid.NewGuid().ToString("N"), dt, m_User, lastParentId); - docList.Add(newDoc); - Assert.IsTrue(docList[docList.Count - 1].Id > 0); - lastParentId = newDoc.Id; - } - - //now delete all of them permanently, since they are nested, we only need to delete one - docList.First().delete(true); - - //make sure they are all gone - foreach (var d in docList) - { - Assert.IsFalse(Document.IsNode(d.Id)); - } - - } - - /// - ///A test for PublishWithResult - /// - [TestMethod()] - public void Document_Publish_With_Result() - { - var val = m_NewRootDoc.PublishWithResult(m_User); - } - - /// - /// Creates a doc type, assigns a domain to it and removes it - /// - [TestMethod()] - public void Document_Assign_Domain() - { - var d = CreateNewUnderRoot(GetExistingDocType()); - - var languages = Language.getAll.ToList(); - Assert.IsTrue(languages.Count > 0); - - //get all assigned domains - var domains = Domain.GetDomains(); - - var domainName = "www." + Guid.NewGuid().ToString("N") + ".com"; - - //add a domain name to the node with the first language found - Domain.MakeNew(domainName, d.Id, languages[0].id); - Assert.IsTrue(Domain.Exists(domainName)); - Assert.AreEqual(domains.Count + 1, Domain.GetDomains().Count); - - //delete the document, ensure that the domain is gone - RecycleAndDelete(d); - - Assert.IsFalse(Domain.Exists(domainName)); - Assert.AreEqual(domains.Count, Domain.GetDomains().Count); - } - - /// - ///A test for making a new document and deleting it which actuall first moves it to the recycle bin - ///and then deletes it. - /// - [TestMethod()] - public void Document_Make_New() - { - Assert.IsInstanceOfType(m_NewRootDoc, typeof(Document)); - } - - /// - /// A test for Copying a node, then deleting the copied node. - /// This does error checking on the case of when a node is being copied that is in the root and doesn't have a parent node, it will - /// lookup the root docs to do the test. - /// - [TestMethod()] - public void Document_Copy() - { - //System.Diagnostics.Debugger.Break(); - Document target = new Document(GetExistingNodeId()); - int parentId = target.ParentId; - bool RelateToOrignal = false; - - //get children ids for the current parent - var childrenIds = GetChildNodesOfParent(target).Select(x => x.Id); - - //copy the node - target.Copy(parentId, m_User, RelateToOrignal); - - //test that the child id count + 1 is equal to the total child count - Assert.AreEqual(childrenIds.Count() + 1, GetChildNodesOfParent(target).Count(), "Child node counts do not match"); - - //get the list of new child ids from the parent - var newChildIds = GetChildNodesOfParent(target).Select(x => x.Id); - //get the children difference which should be the new node - var diff = newChildIds.Except(childrenIds); - - Assert.AreEqual(1, diff.Count()); - - //get the node that is the difference to compare - Document newDoc = new Document(diff.First()); - Assert.AreEqual(parentId, newDoc.ParentId); - - RecycleAndDelete(newDoc); - } - - /// - /// Tests copying by relating nodes, then deleting - /// - [TestMethod()] - public void Document_Copy_And_Relate() - { - //System.Diagnostics.Debugger.Break(); - Document target = new Document(GetExistingNodeId()); - int parentId = target.ParentId; - bool RelateToOrignal = true; - - //get children ids - var childrenIds = GetChildNodesOfParent(target).Select(x => x.Id); - - target.Copy(parentId, m_User, RelateToOrignal); - - var parentChildNodes = GetChildNodesOfParent(target); - Assert.AreEqual(childrenIds.Count() + 1, parentChildNodes.Count()); - - //get the children difference which should be the new node - var diff = parentChildNodes.Select(x => x.Id).Except(childrenIds); - - Assert.AreEqual(1, diff.Count()); - - Document newDoc = new Document(diff.First()); - - RecycleAndDelete(newDoc); - } - - /// - ///Create a new document, create preview xml for it, then delete it - /// - [TestMethod()] - public void Document_To_Preview_Xml() - { - //System.Diagnostics.Debugger.Break(); - var doc = m_NewRootDoc; - var id = doc.Id; - Assert.IsTrue(doc.Id > 0); - - XmlDocument xd = new XmlDocument(); - var xmlNode = doc.ToPreviewXml(xd); - - //check the preview exists - Assert.IsTrue(doc.PreviewExists(doc.Version)); - - Assert.IsNotNull(xmlNode); - Assert.IsTrue(xmlNode.HasChildNodes); - } - - /// - /// Run test to create a node, publish it and delete it. This will test the versioning too. - /// - [TestMethod()] - public void Document_Make_New_And_Publish() - { - //System.Diagnostics.Debugger.Break(); - var doc = m_NewRootDoc; - var id = doc.Id; - Assert.IsTrue(doc.Id > 0); - - var versionCount = doc.GetVersions().Count(); - - doc.Publish(m_User); - - Assert.IsTrue(doc.Published); - Assert.AreEqual(versionCount + 1, doc.GetVersions().Count()); - } - - /// - ///A test that creates a new document, publishes it, unpublishes it and finally deletes it - /// - [TestMethod()] - public void Document_Publish_Then_UnPublish() - { - //System.Diagnostics.Debugger.Break(); - var doc = m_NewRootDoc; - var id = doc.Id; - Assert.IsTrue(doc.Id > 0); - - var versionCount = doc.GetVersions().Count(); - - doc.Publish(m_User); - - Assert.IsTrue(doc.Published); - Assert.AreEqual(versionCount + 1, doc.GetVersions().Count()); - - doc.UnPublish(); - - Assert.IsFalse(doc.Published); - } - - /// - ///A test that makes a new document, updates some properties, saves and publishes the document, then rolls the document back and finally deletes it. - /// - [TestMethod()] - public void Document_Save_And_Publish_Then_Roll_Back() - { - //System.Diagnostics.Debugger.Break(); - - //create new document in the root - var doc = m_NewRootDoc; - var id = doc.Id; - Assert.IsTrue(doc.Id > 0); - - //get a text property - var prop = GetTextFieldProperty(m_ExistingDocType, doc); - var originalPropVal = prop.Value; - var versionCount = doc.GetVersions().Count(); - - //save - //wait a sec so that there's a time delay between the update time and version time - Thread.Sleep(1000); - doc.Save(); - Assert.IsTrue(doc.HasPendingChanges()); - - //publish and create new version - doc.Publish(m_User); - Assert.IsTrue(doc.Published); - var versions = doc.GetVersions().ToList(); - Assert.AreEqual(versionCount + 1, versions.Count()); - - string propertyTypeAlias = prop.PropertyType.Alias; - prop.Value = "updated!"; //udpate the prop - Assert.AreNotEqual(originalPropVal, prop.Value); - - //rollback to first version - doc.RollBack(versions.OrderBy(x => x.Date).Last().Version, m_User); - - var rolledBack = new Document(id); - Assert.AreEqual(originalPropVal, rolledBack.GenericProperties.ToList().Where(x => x.PropertyType.Alias == propertyTypeAlias).First().Value); - } - - /// - ///Tests creating a new document type, then creating a new node with that document type, adding some data to it, then deleting the - ///document type which should delete all documents associated with that. - ///This will create a document type that has it's own id allowed as children. When we create the content nodes, we'll create - ///them as children of each other to ensure the deletion occurs correctly. - /// - [TestMethod()] - public void Document_Delete_All_Docs_By_Document_Type() - { - //System.Diagnostics.Debugger.Break(); - - //create a new doc type - string name = "TEST-" + Guid.NewGuid().ToString("N"); - var dt = DocumentType.MakeNew(m_User, name); - - //test the doc type - Assert.AreEqual(DateTime.Now.Date, dt.CreateDateTime.Date); - Assert.IsTrue(dt.Id > 0); - - //allow itself to be created under itself - dt.AllowedChildContentTypeIDs = new int[] { dt.Id }; - //create a tab - dt.AddVirtualTab("TEST"); - - //test the tab - var tabs = dt.getVirtualTabs.ToList(); - Assert.AreEqual(1, tabs.Count); - - //create a property - var allDataTypes = DataTypeDefinition.GetAll().ToList(); //get all definitions - dt.AddPropertyType(allDataTypes[0], "testProperty", "Test Property"); //add a property type of the first type found in the list - - //test the prop - var prop = dt.getPropertyType("testProperty"); - Assert.AreEqual("Test Property", prop.Name); - - //create 1st node - var node1 = Document.MakeNew("TEST-" + Guid.NewGuid().ToString("N"), dt, m_User, -1); - Assert.IsTrue(node1.Id > 0); - - //create 2nd node underneath node 1 - var node2 = Document.MakeNew("TEST-" + Guid.NewGuid().ToString("N"), dt, m_User, node1.Id); - Assert.IsTrue(node2.Id > 0); - Assert.AreEqual(node1.Id, node2.Parent.Id); - - //create 3rd node underneath node 2 - var node3 = Document.MakeNew("TEST-" + Guid.NewGuid().ToString("N"), dt, m_User, node2.Id); - Assert.IsTrue(node3.Id > 0); - Assert.AreEqual(node2.Id, node3.Parent.Id); - - Document.DeleteFromType(dt); - - Assert.IsFalse(Document.IsNode(node1.Id)); - Assert.IsFalse(Document.IsNode(node2.Id)); - Assert.IsFalse(Document.IsNode(node3.Id)); - - //now remove the document type created - dt.delete(); - - Assert.IsFalse(DocumentType.IsNode(dt.Id)); - } - - /// - /// This will find a document type that supports a heirarchy, create 2 root nodes, then create a child node under the first one, - /// then move it to the second one and finally delete everything that was created. - /// - [TestMethod] - public void Document_Move() - { - //first need to document type that allows other types of document types to exist underneath it - DocumentType parent = null; - DocumentType child = null; - var ids = DocumentType.getAllUniqueNodeIdsFromObjectType(DocumentType._objectType); - foreach (var id in ids) - { - var dt = new DocumentType(id); - var allowed = dt.AllowedChildContentTypeIDs.ToList(); - if (allowed.Count() > 0) - { - parent = dt; - child = new DocumentType(allowed[0]); - break; - } - } - if (parent == null || child == null) - { - throw new NotImplementedException("The umbraco install doesn't have document types that support a heirarchy"); - } - - //now that we have a parent and a child, we need to create some documents - var node1 = Document.MakeNew("FromCopy" + Guid.NewGuid().ToString("N"), parent, m_User, -1); - Assert.IsTrue(node1.Id > 0); - - var node2 = Document.MakeNew("ToCopy" + Guid.NewGuid().ToString("N"), parent, m_User, -1); - Assert.IsTrue(node2.Id > 0); - - //we now have 2 nodes in the root of the same type, we'll create a child node under node1 and move it to node2 - var childNode = Document.MakeNew("ChildCopy" + Guid.NewGuid().ToString("N"), child, m_User, node2.Id); - Assert.IsTrue(childNode.Id > 0); - - childNode.Move(node2.Id); - Assert.AreEqual(node2.Id, childNode.Parent.Id); - - RecycleAndDelete(childNode); - RecycleAndDelete(node2); - RecycleAndDelete(node1); - } - - /// - /// This will find an existing node, copy it to the same parent, delete the copied node and restore it, then finally completley remove it. - /// - [TestMethod] - public void Document_Undelete() - { - //find existing content - var doc = new Document(GetExistingNodeId()); - //create new content based on the existing content in the same heirarchy - var dt = new DocumentType(doc.ContentType.Id); - var parentId = doc.ParentId; - var newDoc = Document.MakeNew("NewDoc" + Guid.NewGuid().ToString("N"), dt, m_User, parentId); - Assert.IsTrue(newDoc.Id > 0); - - //this will recycle the node - newDoc.delete(); - Assert.IsTrue(newDoc.IsTrashed); - Assert.IsTrue(newDoc.Path.Contains("," + (int)RecycleBin.RecycleBinType.Content + ",")); - - //undelete the node (move it) - newDoc.Move(parentId); - Assert.IsFalse(newDoc.IsTrashed); - Assert.IsFalse(newDoc.Path.Contains("," + (int)RecycleBin.RecycleBinType.Content + ",")); - - //remove it completely - RecycleAndDelete(newDoc); - } - - /// - /// This method will create 20 content nodes, send them to the recycle bin and then empty the recycle bin - /// - [TestMethod] - public void Document_Empty_Recycle_Bin() - { - var docList = new List(); - var total = 20; - var dt = m_ExistingDocType; - //allow the doc type to be created underneath itself - dt.AllowedChildContentTypeIDs = new int[] { dt.Id }; - dt.Save(); - - //create 20 content nodes underneath each other, this will test deleting with heirarchy as well - var lastParentId = -1; - for (var i = 0; i < total; i++) - { - var newDoc = Document.MakeNew("R-" + i.ToString() + Guid.NewGuid().ToString("N"), dt, m_User, lastParentId); - docList.Add(newDoc); - Assert.IsTrue(docList[docList.Count - 1].Id > 0); - Assert.AreEqual(lastParentId, newDoc.ParentId); - lastParentId = newDoc.Id; - } - - //now delete all of them, since they are nested, we only need to delete one - docList.First().delete(); - - //a callback action for each item removed from the recycle bin - var totalDeleted = 0; - - var bin = new RecycleBin(RecycleBin.RecycleBinType.Content); - var totalTrashedItems = bin.GetDescendants().Cast().Count(); - bin.CallTheGarbageMan(x => - { - Assert.AreEqual(totalTrashedItems - (++totalDeleted), x); - }); - - Assert.AreEqual(0, RecycleBin.Count(RecycleBin.RecycleBinType.Content)); - } - - - /// - ///A test for RePublishAll - /// - [TestMethod()] - public void Document_RePublish_All() - { - //publish the node - m_NewRootDoc.Publish(m_User); - - Document.RePublishAll(); - - //now ensure that the xml has been generated - Assert.AreEqual(1, Application.SqlHelper.ExecuteScalar("SELECT COUNT(nodeId) FROM cmsContentXml WHERE nodeId=@nodeId", - Application.SqlHelper.CreateParameter("@nodeId", m_NewRootDoc.Id))); - - } - - /// - ///A test for RegeneratePreviews - /// - [TestMethod()] - public void Document_Regenerate_Previews() - { - //there won't be a preview yet... - Document.RegeneratePreviews(); - - Assert.IsTrue(m_NewRootDoc.PreviewExists(m_NewRootDoc.Version)); - } - - /// - ///A test for PublishWithSubs - /// - [TestMethod()] - public void Document_Publish_With_Subs() - { - var docList = new List(); - var total = 20; - var dt = new DocumentType(GetExistingDocTypeId()); - //allow the doc type to be created underneath itself - dt.AllowedChildContentTypeIDs = new int[] { dt.Id }; - dt.Save(); - - Document firstNode = null; - - - - //create 20 content nodes underneath each other, this will test deleting with heirarchy as well - var lastParentId = -1; - for (var i = 0; i < total; i++) - { - var newDoc = Document.MakeNew(i.ToString() + Guid.NewGuid().ToString("N"), dt, m_User, lastParentId); - docList.Add(newDoc); - if (firstNode == null) firstNode = newDoc; //assign the first node - Assert.IsTrue(docList[docList.Count - 1].Id > 0); - lastParentId = newDoc.Id; - } - - - //now publish the main one with subs - firstNode.PublishWithSubs(m_User); - - //now make sure all children are published, but we need to look them up again as the data layer isn't persistent - var nodes = new Document(firstNode.Id).Children.ToList(); - Assert.IsTrue(firstNode.Published); - foreach (var d in nodes) - { - Assert.IsTrue(d.Published); - } - - //now delete them all - firstNode.delete(true); - - //make sure they are all gone - foreach (var d in docList) - { - Assert.IsFalse(Document.IsNode(d.Id)); - } - - - } - - #region TEST TO BE WRITTEN - - ///// - /////A test for XmlPopulate - ///// - //[TestMethod()] - //public void XmlPopulateTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // XmlNode x = null; // TODO: Initialize to an appropriate value - // XmlNode xExpected = null; // TODO: Initialize to an appropriate value - // bool Deep = false; // TODO: Initialize to an appropriate value - // target.XmlPopulate(xd, ref x, Deep); - // Assert.AreEqual(xExpected, x); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for XmlNodeRefresh - ///// - //[TestMethod()] - //public void XmlNodeRefreshTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // XmlNode x = null; // TODO: Initialize to an appropriate value - // XmlNode xExpected = null; // TODO: Initialize to an appropriate value - // target.XmlNodeRefresh(xd, ref x); - // Assert.AreEqual(xExpected, x); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for XmlGenerate - ///// - //[TestMethod()] - //public void XmlGenerateTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // target.XmlGenerate(xd); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ToXml - ///// - //[TestMethod()] - //public void ToXmlTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // bool Deep = false; // TODO: Initialize to an appropriate value - // XmlNode expected = null; // TODO: Initialize to an appropriate value - // XmlNode actual; - // actual = target.ToXml(xd, Deep); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - ///// - /////A test for SendToPublication - ///// - //[TestMethod()] - //public void SendToPublicationTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // User u = null; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = target.SendToPublication(u); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - - - ///// - /////A test for refreshXmlSortOrder - ///// - //[TestMethod()] - //public void refreshXmlSortOrderTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // target.refreshXmlSortOrder(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - - - - - ///// - /////A test for PublishWithChildrenWithResult - ///// - //[TestMethod()] - //public void PublishWithChildrenWithResultTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // User u = null; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = target.PublishWithChildrenWithResult(u); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Publish - ///// - //[TestMethod()] - //public void PublishTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // User u = null; // TODO: Initialize to an appropriate value - // target.Publish(u); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Import - ///// - //[TestMethod()] - //public void ImportTest() - //{ - // int ParentId = 0; // TODO: Initialize to an appropriate value - // User Creator = null; // TODO: Initialize to an appropriate value - // XmlElement Source = null; // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // actual = Document.Import(ParentId, Creator, Source); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetTextPath - ///// - //[TestMethod()] - //public void GetTextPathTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // actual = target.GetTextPath(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetRootDocuments - ///// - //[TestMethod()] - //public void GetRootDocumentsTest() - //{ - // Document[] expected = null; // TODO: Initialize to an appropriate value - // Document[] actual; - // actual = Document.GetRootDocuments(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetNodesForPreview - ///// - //[TestMethod()] - //public void GetNodesForPreviewTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // bool childrenOnly = false; // TODO: Initialize to an appropriate value - // List expected = null; // TODO: Initialize to an appropriate value - // List actual; - // actual = target.GetNodesForPreview(childrenOnly); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetDocumentsForRelease - ///// - //[TestMethod()] - //public void GetDocumentsForReleaseTest() - //{ - // Document[] expected = null; // TODO: Initialize to an appropriate value - // Document[] actual; - // actual = Document.GetDocumentsForRelease(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetDocumentsForExpiration - ///// - //[TestMethod()] - //public void GetDocumentsForExpirationTest() - //{ - // Document[] expected = null; // TODO: Initialize to an appropriate value - // Document[] actual; - // actual = Document.GetDocumentsForExpiration(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetChildrenForTree - ///// - //[TestMethod()] - //public void GetChildrenForTreeTest() - //{ - // int NodeId = 0; // TODO: Initialize to an appropriate value - // Document[] expected = null; // TODO: Initialize to an appropriate value - // Document[] actual; - // actual = Document.GetChildrenForTree(NodeId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for CountSubs - ///// - //[TestMethod()] - //public void CountSubsTest() - //{ - // int parentId = 0; // TODO: Initialize to an appropriate value - // bool publishedOnly = false; // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // actual = Document.CountSubs(parentId, publishedOnly); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Copy - ///// - //[TestMethod()] - //public void CopyTest1() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Document target = new Document(id); // TODO: Initialize to an appropriate value - // int CopyTo = 0; // TODO: Initialize to an appropriate value - // User u = null; // TODO: Initialize to an appropriate value - // target.Copy(CopyTo, u); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - #endregion - - #region Private properties and methods - - /// - /// The user to be used to create stuff - /// - private static User m_User = new User(0); - - /// - /// Used for each test initialization. Before each test is run a new root doc is created. - /// - private Document m_NewRootDoc; - - /// - /// Gets initialized for each test and is set to an existing document type - /// - private DocumentType m_ExistingDocType; - - /// - /// Completely remove the document, this will first recycle it and then delete it (the api doesn't directly support deleting completey in one step) - /// - /// - internal static void RecycleAndDelete(Document d) - { - if (d == null) - { - return; - } - - var id = d.Id; - - //check if it is already trashed - var alreadyTrashed = d.IsTrashed; - - if (!alreadyTrashed) - { - //now recycle it - d.delete(); - - Assert.IsTrue(d.IsTrashed); - } - - //now permanently delete - d.delete(true); - Assert.IsFalse(Document.IsNode(id)); - - //check with sql that it is gone - var count = Application.SqlHelper.ExecuteScalar("SELECT COUNT(*) FROM umbracoNode WHERE id=@id", - Application.SqlHelper.CreateParameter("@id", id)); - - Assert.AreEqual(0, count); - } - - /// - /// Returns a random docuemnt type that supports a text property - /// - /// - internal static int GetExistingDocTypeId() - { - System.Diagnostics.Debugger.Launch(); - - var types = DocumentType.GetAllAsList(); - DocumentType found = null; - var txtField = new TextFieldDataType(); - foreach (var d in types) - { - var prop = d.PropertyTypes.FirstOrDefault(x => x.DataTypeDefinition.DataType.Id == txtField.Id); - if (prop != null) - { - found = d; - break; - } - } - if (found == null) - { - throw new MissingMemberException("No document type was found that contains a text field property"); - } - return found.Id; - } - - /// - /// Returns a text field property of the document type specified. This will throw an exception if one is not found. - /// - /// - /// - internal static Property GetTextFieldProperty(DocumentType dt, Document d) - { - TextFieldDataType txtField = new TextFieldDataType(); - var prop = dt.PropertyTypes - .Where(x => x.DataTypeDefinition.DataType.Id == txtField.Id).First(); - return d.GenericProperties.Where(x => x.PropertyType.Id == prop.Id).First(); - } - - /// - /// Returns a content node - /// - /// - internal static int GetExistingNodeId() - { - var ids = Document.getAllUniqueNodeIdsFromObjectType(Document._objectType).ToList(); - var r = new Random(); - var index = r.Next(0, ids.Count() - 1); - return ids[index]; - } - - /// - /// A helper method to get the parent node. - /// The reason we need this is because the API currently throws an exception if we access the Parent property - /// of a node and the node is on level 1. This also causes issues if the node is in level 1 in the recycle bin. - /// - /// - /// - internal static IEnumerable GetChildNodesOfParent(Document d) - { - if (d.ParentId == (int)RecycleBin.RecycleBinType.Content) - { - return new RecycleBin(RecycleBin.RecycleBinType.Content).Children.ToList(); - } - else - { - if (d.Level == 1) - { - return Document.GetRootDocuments(); - } - else - { - return d.Parent.Children; - } - } - } - - internal static DocumentType GetExistingDocType() - { - DocumentType dct = new DocumentType(GetExistingDocTypeId()); - Assert.IsTrue(dct.Id > 0); - return dct; - } - - /// - /// Creates a new node based on an existing doc type - /// - /// - internal static Document CreateNewUnderRoot(DocumentType dt) - { - string Name = "TEST-" + Guid.NewGuid().ToString("N"); - int ParentId = -1; - Document actual = Document.MakeNew(Name, dt, m_User, ParentId); - var id = actual.Id; - Assert.IsTrue(actual.Id > 0); - return actual; - } - - #endregion - - - #region Initialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - - - /// - /// Creates a new root document to use for each test if required - /// - [TestInitialize()] - public void MyTestInitialize() - { - m_ExistingDocType = GetExistingDocType(); - m_NewRootDoc = CreateNewUnderRoot(m_ExistingDocType); - } - - /// - /// Makes sure the root doc is deleted - /// - [TestCleanup()] - public void MyTestCleanup() - { - RecycleAndDelete(m_NewRootDoc); - } - - #endregion - } -} diff --git a/test/umbraco.Test/DocumentTypeTest.cs b/test/umbraco.Test/DocumentTypeTest.cs deleted file mode 100644 index b01fdc54c0..0000000000 --- a/test/umbraco.Test/DocumentTypeTest.cs +++ /dev/null @@ -1,815 +0,0 @@ -using umbraco.cms.businesslogic.web; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Collections.Generic; -using umbraco.BusinessLogic; -using System.Linq; -using umbraco.cms.businesslogic.datatype; - -namespace Umbraco.LegacyTests -{ - - - /// - /// Tests DocumentType apis. - /// - /// - /// After each test is run, any document type created is removed - /// - [TestClass()] - public class DocumentTypeTest - { - [TestMethod()] - public void DocumentType_Delete_Doc_Type_With_Content() - { - var dt = CreateNewDocType(); - var doc = Document.MakeNew("TEST" + Guid.NewGuid().ToString("N"), dt, m_User, -1); - Assert.IsInstanceOfType(doc, typeof(Document)); - Assert.IsTrue(doc.Id > 0); - - DeleteDocType(dt); - - Assert.IsFalse(Document.IsNode(doc.Id)); - } - - /// - /// This will create 3 document types, and create nodes in the following structure: - /// - root - /// -- node1 (of doc type #1) - /// --- node 2 (of doc type #2) - /// ---- node 3 (of doc type #1) - /// ----- node 4 (of doc type #3) - /// - /// Then we'll delete doc type #1. The result should be that node1 and node3 are completely deleted from the database and node2 and node4 are - /// moved to the recycle bin. - /// - [TestMethod()] - public void DocumentType_Delete_Doc_Type_With_Content_And_Children_Of_Different_Doc_Types() - { - //System.Diagnostics.Debugger.Break(); - - //create the doc types - var dt1 = CreateNewDocType(); - var dt2 = CreateNewDocType(); - var dt3 = CreateNewDocType(); - - //create the heirarchy - dt1.AllowedChildContentTypeIDs = new int[] { dt2.Id, dt3.Id }; - dt1.Save(); - dt2.AllowedChildContentTypeIDs = new int[] { dt1.Id }; - dt2.Save(); - - //create the content tree - var node1 = Document.MakeNew("TEST" + Guid.NewGuid().ToString("N"), dt1, m_User, -1); - var node2 = Document.MakeNew("TEST" + Guid.NewGuid().ToString("N"), dt2, m_User, node1.Id); - var node3 = Document.MakeNew("TEST" + Guid.NewGuid().ToString("N"), dt1, m_User, node2.Id); - var node4 = Document.MakeNew("TEST" + Guid.NewGuid().ToString("N"), dt3, m_User, node3.Id); - - //do the deletion of doc type #1 - DeleteDocType(dt1); - - //do our checks - Assert.IsFalse(Document.IsNode(node1.Id), "node1 is not deleted"); //this was of doc type 1, should be gone - Assert.IsFalse(Document.IsNode(node3.Id), "node3 is not deleted"); //this was of doc type 1, should be gone - - Assert.IsTrue(Document.IsNode(node2.Id), "node2 is deleted"); - Assert.IsTrue(Document.IsNode(node4.Id), "node4 is deleted"); - - node2 = new Document(node2.Id);//need to re-query the node - Assert.IsTrue(node2.IsTrashed, "node2 is not in the trash"); - node4 = new Document(node4.Id); //need to re-query the node - Assert.IsTrue(node4.IsTrashed, "node 4 is not in the trash"); - - //remove the old data - DeleteDocType(dt2); - DeleteDocType(dt3); - - } - - /// - ///A test for creating a new document type - /// - [TestMethod()] - public void DocumentType_Make_New() - { - Assert.IsInstanceOfType(m_NewDocType, typeof(DocumentType)); - } - - /// - /// Tests adding every type of property to a new document type on a new tab, then delete the tab, then the document type - /// - [TestMethod()] - public void DocumentType_Add_Properties_To_Tab_Then_Delete_It() - { - //System.Diagnostics.Debugger.Break(); - - //allow itself to be created under itself - m_NewDocType.AllowedChildContentTypeIDs = new int[] { m_NewDocType.Id }; - //create a tab - m_NewDocType.AddVirtualTab("TEST"); - - //test the tab - var tabs = m_NewDocType.getVirtualTabs.ToList(); - Assert.AreEqual(1, tabs.Count); - - //create a property - var allDataTypes = DataTypeDefinition.GetAll().ToList(); //get all definitions - var i = 0; - foreach (var dataType in allDataTypes) - { - //add a property type of the first type found in the list - m_NewDocType.AddPropertyType(dataType, "testProperty" + (++i).ToString(), "Test Property" + i.ToString()); - //test the prop - var prop = m_NewDocType.getPropertyType("testProperty" + i.ToString()); - Assert.IsTrue(prop.Id > 0); - Assert.AreEqual("Test Property" + i.ToString(), prop.Name); - //put the properties to the tab - m_NewDocType.SetTabOnPropertyType(prop, tabs[0].Id); - //re-get the property since data is cached in the object - prop = m_NewDocType.getPropertyType("testProperty" + i.ToString()); - Assert.AreEqual(tabs[0].Id, prop.TabId); - } - - //now we need to delete the tab - m_NewDocType.DeleteVirtualTab(tabs[0].Id); - } - - /// - ///A test for GetAll - /// - [TestMethod()] - public void DocumentType_Get_All() - { - //check with sql that it's the correct number of children - var ids = new List(); - using (var reader = Application.SqlHelper.ExecuteReader(DocumentType.m_SQLOptimizedGetAll.Trim(), - Application.SqlHelper.CreateParameter("@nodeObjectType", DocumentType._objectType))) - { - while (reader.Read()) - { - ids.Add(reader.Get("id")); - } - } - - var all = DocumentType.GetAllAsList(); - - Assert.AreEqual(ids.Distinct().Count(), all.Count); - } - - /// - ///A test for HasChildren - /// - [TestMethod()] - public void DocumentType_Has_Children() - { - //System.Diagnostics.Debugger.Break(); - - var dt1 = DocumentType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - - Assert.IsTrue(dt1.Id > 0); - Assert.AreEqual(DateTime.Now.Date, dt1.CreateDateTime.Date); - Assert.IsFalse(dt1.HasChildren); - - var dt2 = DocumentType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - - Assert.IsTrue(dt2.Id > 0); - Assert.AreEqual(DateTime.Now.Date, dt2.CreateDateTime.Date); - Assert.IsFalse(dt2.HasChildren); - - dt2.MasterContentType = dt1.Id; - dt2.Save(); - - //unfortunately this won't work! because the HasChildren property is cached - //Assert.IsTrue(dt1.HasChildren); - var reloaded = new DocumentType(dt1.Id); - Assert.IsTrue(reloaded.HasChildren); - - var hasError = false; - try - { - DeleteDocType(dt1); - } - catch (ArgumentException) - { - hasError = true; - } - Assert.IsTrue(hasError); - - DeleteDocType(dt2); - DeleteDocType(dt1); - } - - #region Tests to write - ///// - /////A test for allowedTemplates - ///// - //[TestMethod()] - //public void allowedTemplatesTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // Template[] expected = null; // TODO: Initialize to an appropriate value - // Template[] actual; - // target.allowedTemplates = expected; - // actual = target.allowedTemplates; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for DefaultTemplate - ///// - //[TestMethod()] - //public void DefaultTemplateTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.DefaultTemplate = expected; - // actual = target.DefaultTemplate; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - ///// - /////A test for ToXml - ///// - //[TestMethod()] - //public void ToXmlTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // XmlElement expected = null; // TODO: Initialize to an appropriate value - // XmlElement actual; - // actual = target.ToXml(xd); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for RemoveDefaultTemplate - ///// - //[TestMethod()] - //public void RemoveDefaultTemplateTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // target.RemoveDefaultTemplate(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - - - ///// - /////A test for HasTemplate - ///// - //[TestMethod()] - //public void HasTemplateTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = target.HasTemplate(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetByAlias - ///// - //[TestMethod()] - //public void GetByAliasTest() - //{ - // string Alias = string.Empty; // TODO: Initialize to an appropriate value - // DocumentType expected = null; // TODO: Initialize to an appropriate value - // DocumentType actual; - // actual = DocumentType.GetByAlias(Alias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetAllAsList - ///// - //[TestMethod()] - //public void GetAllAsListTest() - //{ - // List expected = null; // TODO: Initialize to an appropriate value - // List actual; - // actual = DocumentType.GetAllAsList(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GenerateDtd - ///// - //[TestMethod()] - //public void GenerateDtdTest() - //{ - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // actual = DocumentType.GenerateDtd(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for clearTemplates - ///// - //[TestMethod()] - //public void clearTemplatesTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // DocumentType target = new DocumentType(id); // TODO: Initialize to an appropriate value - // target.clearTemplates(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Thumbnail - ///// - //[TestMethod()] - //public void ThumbnailTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Thumbnail = expected; - // actual = target.Thumbnail; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Text - ///// - //[TestMethod()] - //public void TextTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Text = expected; - // actual = target.Text; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for PropertyTypes - ///// - //[TestMethod()] - //public void PropertyTypesTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // List actual; - // actual = target.PropertyTypes; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for MasterContentType - ///// - //[TestMethod()] - //public void MasterContentTypeTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.MasterContentType = expected; - // actual = target.MasterContentType; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for IconUrl - ///// - //[TestMethod()] - //public void IconUrlTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.IconUrl = expected; - // actual = target.IconUrl; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for getVirtualTabs - ///// - //[TestMethod()] - //public void getVirtualTabsTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // ContentType.TabI[] actual; - // actual = target.getVirtualTabs; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Description - ///// - //[TestMethod()] - //public void DescriptionTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Description = expected; - // actual = target.Description; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for AllowedChildContentTypeIDs - ///// - //[TestMethod()] - //public void AllowedChildContentTypeIDsTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // int[] expected = null; // TODO: Initialize to an appropriate value - // int[] actual; - // target.AllowedChildContentTypeIDs = expected; - // actual = target.AllowedChildContentTypeIDs; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Alias - ///// - //[TestMethod()] - //public void AliasTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Alias = expected; - // actual = target.Alias; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for SetTabSortOrder - ///// - //[TestMethod()] - //public void SetTabSortOrderTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // int tabId = 0; // TODO: Initialize to an appropriate value - // int sortOrder = 0; // TODO: Initialize to an appropriate value - // target.SetTabSortOrder(tabId, sortOrder); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for SetTabOnPropertyType - ///// - //[TestMethod()] - //public void SetTabOnPropertyTypeTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // PropertyType pt = null; // TODO: Initialize to an appropriate value - // int TabId = 0; // TODO: Initialize to an appropriate value - // target.SetTabOnPropertyType(pt, TabId); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for SetTabName - ///// - //[TestMethod()] - //public void SetTabNameTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // int tabId = 0; // TODO: Initialize to an appropriate value - // string Caption = string.Empty; // TODO: Initialize to an appropriate value - // target.SetTabName(tabId, Caption); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for removePropertyTypeFromTab - ///// - //[TestMethod()] - //public void removePropertyTypeFromTabTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // PropertyType pt = null; // TODO: Initialize to an appropriate value - // target.removePropertyTypeFromTab(pt); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for getTabIdFromPropertyType - ///// - //[TestMethod()] - //public void getTabIdFromPropertyTypeTest() - //{ - // PropertyType pt = null; // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // actual = ContentType.getTabIdFromPropertyType(pt); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetRawText - ///// - //[TestMethod()] - //public void GetRawTextTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // actual = target.GetRawText(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for getPropertyType - ///// - //[TestMethod()] - //public void getPropertyTypeTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string alias = string.Empty; // TODO: Initialize to an appropriate value - // PropertyType expected = null; // TODO: Initialize to an appropriate value - // PropertyType actual; - // actual = target.getPropertyType(alias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetContentType - ///// - //[TestMethod()] - //public void GetContentTypeTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // ContentType expected = null; // TODO: Initialize to an appropriate value - // ContentType actual; - // actual = ContentType.GetContentType(id); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetByAlias - ///// - //[TestMethod()] - //public void GetByAliasTest() - //{ - // string Alias = string.Empty; // TODO: Initialize to an appropriate value - // ContentType expected = null; // TODO: Initialize to an appropriate value - // ContentType actual; - // actual = ContentType.GetByAlias(Alias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // ContentType[] expected = null; // TODO: Initialize to an appropriate value - // ContentType[] actual; - // actual = target.GetAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for FlushTabCache - ///// - //[TestMethod()] - //public void FlushTabCacheTest() - //{ - // int TabId = 0; // TODO: Initialize to an appropriate value - // int ContentTypeId = 0; // TODO: Initialize to an appropriate value - // ContentType.FlushTabCache(TabId, ContentTypeId); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for AddVirtualTab - ///// - //[TestMethod()] - //public void AddVirtualTabTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // string Caption = string.Empty; // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // actual = target.AddVirtualTab(Caption); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for AddPropertyType - ///// - //[TestMethod()] - //public void AddPropertyTypeTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); // TODO: Initialize to an appropriate value - // DataTypeDefinition dt = null; // TODO: Initialize to an appropriate value - // string Alias = string.Empty; // TODO: Initialize to an appropriate value - // string Name = string.Empty; // TODO: Initialize to an appropriate value - // target.AddPropertyType(dt, Alias, Name); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ContentType Constructor - ///// - //[TestMethod()] - //public void ContentTypeConstructorTest2() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for ContentType Constructor - ///// - //[TestMethod()] - //public void ContentTypeConstructorTest1() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for ContentType Constructor - ///// - //[TestMethod()] - //public void ContentTypeConstructorTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // bool noSetup = false; // TODO: Initialize to an appropriate value - // ContentType target = new ContentType(id, noSetup); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - #endregion - - #region Private properties and methods - - private User m_User = new User(0); - - /// - /// before each test starts, this object is created so it can be used for testing. - /// - private DocumentType m_NewDocType; - - /// - /// Create a brand new document type - /// - /// - private DocumentType CreateNewDocType() - { - var dt = DocumentType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - Assert.IsTrue(dt.Id > 0); - Assert.AreEqual(DateTime.Now.Date, dt.CreateDateTime.Date); - return dt; - } - - private void DeleteDocType(DocumentType dt) - { - var id = dt.Id; - - dt.delete(); - - //check with sql that it is gone - var count = Application.SqlHelper.ExecuteScalar("SELECT COUNT(*) FROM umbracoNode WHERE id=@id", - Application.SqlHelper.CreateParameter("@id", id)); - - Assert.AreEqual(0, count); - } - - #endregion - - - #region Initialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - - /// - /// Create a new document type for use in tests - /// - [TestInitialize()] - public void MyTestInitialize() - { - m_NewDocType = CreateNewDocType(); - } - - /// - /// Remove the created document type - /// - [TestCleanup()] - public void MyTestCleanup() - { - DeleteDocType(m_NewDocType); - } - - #endregion - - } -} diff --git a/test/umbraco.Test/LanguageTest.cs b/test/umbraco.Test/LanguageTest.cs deleted file mode 100644 index 78d56d8498..0000000000 --- a/test/umbraco.Test/LanguageTest.cs +++ /dev/null @@ -1,324 +0,0 @@ -using umbraco.cms.businesslogic.language; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System.Xml; -using System.Collections.Generic; -using umbraco.BusinessLogic; -using System.Linq; -using System; -using System.Globalization; -using umbraco.DataLayer; -using umbraco.cms.businesslogic.web; -using System.Data; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for LanguageTest and is intended - ///to contain all LanguageTest Unit Tests - /// - [TestClass()] - public class LanguageTest - { - - /// - /// A test to ensure you cannot delete the default language: en-US - /// - [ExpectedException(typeof(InvalidOperationException))] - [TestMethod()] - public void Language_Delete_Default_Language() - { - var lang = Language.GetByCultureCode("en-US"); - lang.Delete(); - } - - /// - ///A test for getAll - /// - [TestMethod()] - public void Language_GetAll() - { - //check with sql that it's the correct number of children - var ids = new List(); - using (var reader = Application.SqlHelper.ExecuteReader(Language.m_SQLOptimizedGetAll)) - { - while (reader.Read()) - { - ids.Add(Convert.ToInt32(reader.GetShort("id"))); - } - } - - var all = Language.GetAllAsList(); - - Assert.AreEqual(ids.Distinct().Count(), all.Count()); - } - - /// - ///A test for ToXml - /// - [TestMethod()] - public void Language_To_Xml() - { - var all = Language.GetAllAsList(); - - XmlDocument xd = new XmlDocument(); - var x = all.First().ToXml(xd); - - Assert.IsNotNull(x.Attributes["Id"].Value); - Assert.IsNotNull(x.Attributes["CultureAlias"].Value); - Assert.IsNotNull(x.Attributes["FriendlyName"].Value); - } - - /// - ///A test for GetByCultureCode - /// - [TestMethod()] - public void Language_Get_By_Culture_Code() - { - var all = Language.GetAllAsList(); - var lang = Language.GetByCultureCode(all.First().CultureAlias); - Assert.AreEqual(all.First().CultureAlias, lang.CultureAlias); - } - - /// - ///A test for MakeNew - /// - [TestMethod()] - public void Language_Make_New() - { - var newLang = MakeNew(); - DeleteLanguage(newLang); - } - - /// - /// try to make a duplicate, this should fail with an sql exception - /// - [TestMethod()] - [ExpectedException(typeof(SqlHelperException))] - public void Language_Make_Duplicate() - { - var all = Language.GetAllAsList(); - Language.MakeNew(all.First().CultureAlias); - } - - [TestMethod()] - public void Language_Delete_With_Assigned_Domain() - { - var newLang = MakeNew(); - - var newDoc = DocumentTest.CreateNewUnderRoot(DocumentTest.GetExistingDocType()); - - Domain.MakeNew("www.test" + Guid.NewGuid().ToString("N") + ".com", newDoc.Id, newLang.id); - - //this shouldn't delete it - bool hasErr = false; - try - { - newLang.Delete(); - } - catch (DataException) - { - hasErr = true; - } - Assert.IsTrue(hasErr); - - //we will need to delete the domain first, then the language - var d = Domain.GetDomainsById(newDoc.Id).First(); - d.Delete(); - - DeleteLanguage(newLang); - } - - /// - /// Ensure that a language that has dictionary items assigned to it with values - /// is able to be deleted propery. Ensure that all translations for the language are - /// removed as well. - /// - [TestMethod()] - public void Language_Delete_With_Assigned_Dictionary_Items() - { - var newLang = MakeNew(); - - - - DeleteLanguage(newLang); - } - - #region Tests to write - ///// - /////A test for id - ///// - //[TestMethod()] - //public void idTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Language target = new Language(id); // TODO: Initialize to an appropriate value - // int actual; - // actual = target.id; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for FriendlyName - ///// - //[TestMethod()] - //public void FriendlyNameTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Language target = new Language(id); // TODO: Initialize to an appropriate value - // string actual; - // actual = target.FriendlyName; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for CultureAlias - ///// - //[TestMethod()] - //public void CultureAliasTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Language target = new Language(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.CultureAlias = expected; - // actual = target.CultureAlias; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Language target = new Language(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - - - ///// - /////A test for Import - ///// - //[TestMethod()] - //public void ImportTest() - //{ - // XmlNode xmlData = null; // TODO: Initialize to an appropriate value - // Language expected = null; // TODO: Initialize to an appropriate value - // Language actual; - // actual = Language.Import(xmlData); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for Delete - ///// - //[TestMethod()] - //public void DeleteTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Language target = new Language(id); // TODO: Initialize to an appropriate value - // target.Delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Language Constructor - ///// - //[TestMethod()] - //public void LanguageConstructorTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Language target = new Language(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - #endregion - - #region Private methods - - /// - /// a helper class to create a new language and validate everything. This does NOT delete it when the test is done. - /// - /// - private Language MakeNew() - { - var all = Language.GetAllAsList(); - - //get all cultures not installed - var nonInstalled = CultureInfo.GetCultures(CultureTypes.AllCultures) - .Select(x => x.Name) - .Except(all.Select(x => x.CultureAlias)) - .ToList(); - - Language.MakeNew(nonInstalled.First()); - - //now get all installed again to make sure it's there - var newAll = Language.GetAllAsList(); - - //the new counts should be different - Assert.AreNotEqual(all.Count(), newAll.Count()); - //the differnce should be 1 - Assert.AreEqual(1, newAll.Except(all).Count()); - - //now we need to delete - var newLang = newAll.Except(all).Single(); - return newLang; - } - - private void DeleteLanguage(Language lang) - { - var id = lang.id; - - lang.Delete(); - - //check with sql that it is gone - var count = Application.SqlHelper.ExecuteScalar("SELECT COUNT(*) FROM umbracoLanguage WHERE id=@id", - Application.SqlHelper.CreateParameter("@id", id)); - - Assert.AreEqual(0, count); - } - #endregion - - #region Intitialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/MacroPropertyTypeTest.cs b/test/umbraco.Test/MacroPropertyTypeTest.cs deleted file mode 100644 index 8349b797df..0000000000 --- a/test/umbraco.Test/MacroPropertyTypeTest.cs +++ /dev/null @@ -1,154 +0,0 @@ -using umbraco.cms.businesslogic.macro; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for MacroPropertyTypeTest and is intended - ///to contain all MacroPropertyTypeTest Unit Tests - /// - [TestClass()] - public class MacroPropertyTypeTest - { - - /// - /// Test the constructor to throw an exception when the object is not found by id - /// - [TestMethod()] - [ExpectedException(typeof(ArgumentException))] - public void MacroProperty_Not_Found_Constructor() - { - MacroProperty u = new MacroProperty(-1111); - } - - - #region Tests to write - - - ///// - /////A test for MacroPropertyType Constructor - ///// - //[TestMethod()] - //public void MacroPropertyTypeConstructorTest1() - //{ - // MacroPropertyType target = new MacroPropertyType(); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for MacroPropertyType Constructor - ///// - //[TestMethod()] - //public void MacroPropertyTypeConstructorTest2() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // MacroPropertyType target = new MacroPropertyType(Id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Alias - ///// - //[TestMethod()] - //public void AliasTest() - //{ - // MacroPropertyType target = new MacroPropertyType(); // TODO: Initialize to an appropriate value - // string actual; - // actual = target.Alias; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Assembly - ///// - //[TestMethod()] - //public void AssemblyTest() - //{ - // MacroPropertyType target = new MacroPropertyType(); // TODO: Initialize to an appropriate value - // string actual; - // actual = target.Assembly; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for BaseType - ///// - //[TestMethod()] - //public void BaseTypeTest() - //{ - // MacroPropertyType target = new MacroPropertyType(); // TODO: Initialize to an appropriate value - // string actual; - // actual = target.BaseType; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // List actual; - // actual = MacroPropertyType.GetAll; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Id - ///// - //[TestMethod()] - //public void IdTest() - //{ - // MacroPropertyType target = new MacroPropertyType(); // TODO: Initialize to an appropriate value - // int actual; - // actual = target.Id; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Type - ///// - //[TestMethod()] - //public void TypeTest() - //{ - // MacroPropertyType target = new MacroPropertyType(); // TODO: Initialize to an appropriate value - // string actual; - // actual = target.Type; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/MacroTest.cs b/test/umbraco.Test/MacroTest.cs deleted file mode 100644 index 44eec2531d..0000000000 --- a/test/umbraco.Test/MacroTest.cs +++ /dev/null @@ -1,428 +0,0 @@ -using umbraco.cms.businesslogic.macro; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Linq; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for MacroTest and is intended - ///to contain all MacroTest Unit Tests - /// - [TestClass()] - public class MacroTest - { - - /// - /// Test the constructor to throw an exception when the object is not found by id - /// - [TestMethod()] - [ExpectedException(typeof(ArgumentException))] - public void Macro_Not_Found_Constructor() - { - Macro target = new Macro(-1111); - } - - /// - ///A test for MakeNew - /// - [TestMethod()] - public void Macro_Make_New() - { - var m = Macro.MakeNew(Guid.NewGuid().ToString("N")); - Assert.IsTrue(m.Id > 0); - Assert.IsInstanceOfType(m, typeof(Macro)); - - m.Delete(); - var isfound = false; - try - { - var asdf = new Macro(m.Id); - isfound = true; - } - catch (ArgumentException) - { - isfound = false; - } - - Assert.IsFalse(isfound); - } - - /// - /// Creates a new macro, add a property to it and delete the macro ensuring the properties are all gone. - /// - [TestMethod()] - public void Macro_Make_New_Add_Property() - { - var m = Macro.MakeNew(Guid.NewGuid().ToString("N")); - Assert.IsTrue(m.Id > 0); - Assert.IsInstanceOfType(m, typeof(Macro)); - - //now, add a property... - - //get the first macro property type we can find - var mpt = MacroPropertyType.GetAll.First(); - var mp = MacroProperty.MakeNew(m, false, Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"), mpt); - Assert.IsTrue(mp.Id > 0); - Assert.IsInstanceOfType(mp, typeof(MacroProperty)); - - m.Delete(); - - //make sure the property is gone - var props = MacroProperty.GetProperties(m.Id); - Assert.IsFalse(props.Select(x => x.Id).Contains(mp.Id)); - - var isfound = false; - try - { - var asdf = new Macro(m.Id); - isfound = true; - } - catch (ArgumentException) - { - isfound = false; - } - - Assert.IsFalse(isfound); - - } - - - #region Tests to write - - - ///// - /////A test for Macro Constructor - ///// - //[TestMethod()] - //public void MacroConstructorTest1() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Macro target = new Macro(Id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Macro Constructor - ///// - //[TestMethod()] - //public void MacroConstructorTest2() - //{ - // Macro target = new Macro(); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Delete - ///// - //[TestMethod()] - //public void DeleteTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // target.Delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // Macro[] expected = null; // TODO: Initialize to an appropriate value - // Macro[] actual; - // actual = Macro.GetAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetByAlias - ///// - //[TestMethod()] - //public void GetByAliasTest() - //{ - // string Alias = string.Empty; // TODO: Initialize to an appropriate value - // Macro expected = null; // TODO: Initialize to an appropriate value - // Macro actual; - // actual = Macro.GetByAlias(Alias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Import - ///// - //[TestMethod()] - //public void ImportTest() - //{ - // XmlNode n = null; // TODO: Initialize to an appropriate value - // Macro expected = null; // TODO: Initialize to an appropriate value - // Macro actual; - // actual = Macro.Import(n); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for RefreshProperties - ///// - //[TestMethod()] - //public void RefreshPropertiesTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // target.RefreshProperties(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ToXml - ///// - //[TestMethod()] - //public void ToXmlTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // XmlNode expected = null; // TODO: Initialize to an appropriate value - // XmlNode actual; - // actual = target.ToXml(xd); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Alias - ///// - //[TestMethod()] - //public void AliasTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Alias = expected; - // actual = target.Alias; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Assembly - ///// - //[TestMethod()] - //public void AssemblyTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Assembly = expected; - // actual = target.Assembly; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for CacheByPage - ///// - //[TestMethod()] - //public void CacheByPageTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.CacheByPage = expected; - // actual = target.CacheByPage; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for CachePersonalized - ///// - //[TestMethod()] - //public void CachePersonalizedTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.CachePersonalized = expected; - // actual = target.CachePersonalized; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Id - ///// - //[TestMethod()] - //public void IdTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // int actual; - // actual = target.Id; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Name - ///// - //[TestMethod()] - //public void NameTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Name = expected; - // actual = target.Name; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Properties - ///// - //[TestMethod()] - //public void PropertiesTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // MacroProperty[] actual; - // actual = target.Properties; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for RefreshRate - ///// - //[TestMethod()] - //public void RefreshRateTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.RefreshRate = expected; - // actual = target.RefreshRate; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for RenderContent - ///// - //[TestMethod()] - //public void RenderContentTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.RenderContent = expected; - // actual = target.RenderContent; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for ScriptingFile - ///// - //[TestMethod()] - //public void ScriptingFileTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.ScriptingFile = expected; - // actual = target.ScriptingFile; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Type - ///// - //[TestMethod()] - //public void TypeTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Type = expected; - // actual = target.Type; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for UseInEditor - ///// - //[TestMethod()] - //public void UseInEditorTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.UseInEditor = expected; - // actual = target.UseInEditor; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Xslt - ///// - //[TestMethod()] - //public void XsltTest() - //{ - // Macro target = new Macro(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Xslt = expected; - // actual = target.Xslt; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/MediaTest.cs b/test/umbraco.Test/MediaTest.cs deleted file mode 100644 index d53d9eeb0e..0000000000 --- a/test/umbraco.Test/MediaTest.cs +++ /dev/null @@ -1,488 +0,0 @@ -using umbraco.cms.businesslogic.media; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Collections.Generic; -using umbraco.BusinessLogic; -using System.Linq; -using umbraco.editorControls.label; -using umbraco.cms.businesslogic.datatype; -using umbraco.cms.businesslogic; -using umbraco.cms.businesslogic.property; - -namespace Umbraco.LegacyTests -{ - - - /// - /// This will test the Media data layer. - /// These test assume the following criteria, if this criteria is not met, these tests will fail: - /// - There is a Label data type assigned to one of your Media types. - /// - [TestClass()] - public class MediaTest - { - /// - ///A test for making a new media and deleting it which actuall first moves it to the recycle bin - ///and then deletes it. - /// - [TestMethod()] - public void Media_Make_New() - { - //System.Diagnostics.Debugger.Break(); - Assert.IsInstanceOfType(m_NewRootMedia, typeof(Media)); - } - - [TestMethod()] - public void Media_Update_Data() - { - //System.Diagnostics.Debugger.Break(); - - //set the value of a text property - var m = CreateNewUnderRoot(m_ExistingMediaType); - var p = GetLabelProperty(m_ExistingMediaType, m); - p.Value = "HELLO!"; - - Assert.AreEqual("HELLO!", m.getProperty(p.PropertyType).Value); - - //completely delete - m.delete(true); - - Assert.IsFalse(Media.IsNode(m.Id)); - } - - [TestMethod()] - public void Media_Delete_Heirarchy_Permanently() - { - var mediaList = new List(); - var total = 20; - var mt = new MediaType(GetExistingMediaTypeId()); - //allow the doc type to be created underneath itself - mt.AllowedChildContentTypeIDs = new int[] { mt.Id }; - mt.Save(); - - //create 20 content nodes underneath each other, this will test deleting with heirarchy as well - var lastParentId = -1; - for (var i = 0; i < total; i++) - { - var newDoc = Media.MakeNew(i.ToString() + Guid.NewGuid().ToString("N"), mt, m_User, lastParentId); - mediaList.Add(newDoc); - Assert.IsTrue(mediaList[mediaList.Count - 1].Id > 0); - lastParentId = newDoc.Id; - } - - //now delete all of them permanently, since they are nested, we only need to delete one - mediaList.First().delete(true); - - //make sure they are all gone - foreach (var d in mediaList) - { - Assert.IsFalse(Media.IsNode(d.Id)); - } - - } - - [TestMethod] - public void Media_Move() - { - //first need to document type that allows other types of document types to exist underneath it - MediaType parent = null; - MediaType child = null; - var ids = MediaType.getAllUniqueNodeIdsFromObjectType(MediaType._objectType); - foreach (var id in ids) - { - var dt = new MediaType(id); - var allowed = dt.AllowedChildContentTypeIDs.ToList(); - if (allowed.Count() > 0) - { - parent = dt; - child = new MediaType(allowed[0]); - break; - } - } - if (parent == null || child == null) - { - throw new NotImplementedException("The umbraco install doesn't have document types that support a heirarchy"); - } - - //now that we have a parent and a child, we need to create some documents - var node1 = Media.MakeNew("FromCopy" + Guid.NewGuid().ToString("N"), parent, m_User, -1); - Assert.IsTrue(node1.Id > 0); - - var node2 = Media.MakeNew("ToCopy" + Guid.NewGuid().ToString("N"), parent, m_User, -1); - Assert.IsTrue(node2.Id > 0); - - //we now have 2 nodes in the root of the same type, we'll create a child node under node1 and move it to node2 - var childNode = Media.MakeNew("ChildCopy" + Guid.NewGuid().ToString("N"), child, m_User, node2.Id); - Assert.IsTrue(childNode.Id > 0); - - childNode.Move(node2.Id); - Assert.AreEqual(node2.Id, childNode.Parent.Id); - - RecycleAndDelete(childNode); - RecycleAndDelete(node2); - RecycleAndDelete(node1); - } - - [TestMethod()] - public void Media_Delete_All_Docs_By_Document_Type() - { - //System.Diagnostics.Debugger.Break(); - - //create a new media type - string name = "TEST-" + Guid.NewGuid().ToString("N"); - var mt = MediaType.MakeNew(m_User, name); - - //test the media type - Assert.AreEqual(DateTime.Now.Date, mt.CreateDateTime.Date); - Assert.IsTrue(mt.Id > 0); - - //allow itself to be created under itself - mt.AllowedChildContentTypeIDs = new int[] { mt.Id }; - //create a tab - mt.AddVirtualTab("TEST"); - - //test the tab - var tabs = mt.getVirtualTabs.ToList(); - Assert.AreEqual(1, tabs.Count); - - //create a property - var allDataTypes = DataTypeDefinition.GetAll().ToList(); //get all definitions - mt.AddPropertyType(allDataTypes[0], "testProperty", "Test Property"); //add a property type of the first type found in the list - - //test the prop - var prop = mt.getPropertyType("testProperty"); - Assert.AreEqual("Test Property", prop.Name); - - //create 1st node - var node1 = Media.MakeNew("TEST-" + Guid.NewGuid().ToString("N"), mt, m_User, -1); - Assert.IsTrue(node1.Id > 0); - - //create 2nd node underneath node 1 - var node2 = Media.MakeNew("TEST-" + Guid.NewGuid().ToString("N"), mt, m_User, node1.Id); - Assert.IsTrue(node2.Id > 0); - Assert.AreEqual(node1.Id, node2.Parent.Id); - - //create 3rd node underneath node 2 - var node3 = Media.MakeNew("TEST-" + Guid.NewGuid().ToString("N"), mt, m_User, node2.Id); - Assert.IsTrue(node3.Id > 0); - Assert.AreEqual(node2.Id, node3.Parent.Id); - - Media.DeleteFromType(mt); - - Assert.IsFalse(Media.IsNode(node1.Id)); - Assert.IsFalse(Media.IsNode(node2.Id)); - Assert.IsFalse(Media.IsNode(node3.Id)); - - //now remove the document type created - mt.delete(); - - Assert.IsFalse(MediaType.IsNode(mt.Id)); - } - - [TestMethod] - public void Media_Empty_Recycle_Bin() - { - //System.Diagnostics.Debugger.Break(); - - var mediaList = new List(); - var total = 20; - var mt = m_ExistingMediaType; - //allow the doc type to be created underneath itself - mt.AllowedChildContentTypeIDs = new int[] { mt.Id }; - mt.Save(); - - //create 20 media nodes underneath each other, this will test deleting with heirarchy as well - var lastParentId = -1; - for (var i = 0; i < total; i++) - { - var newMedia = Media.MakeNew("R-" + i.ToString() + Guid.NewGuid().ToString("N"), mt, m_User, lastParentId); - mediaList.Add(newMedia); - Assert.IsTrue(mediaList[mediaList.Count - 1].Id > 0); - Assert.AreEqual(lastParentId, newMedia.ParentId); - lastParentId = newMedia.Id; - } - - //now delete all of them, since they are nested, we only need to delete one - mediaList.First().delete(); - - //a callback action for each item removed from the recycle bin - var totalDeleted = 0; - - var bin = new RecycleBin(RecycleBin.RecycleBinType.Media); - var totalTrashedItems = bin.GetDescendants().Cast().Count(); - bin.CallTheGarbageMan(x => - { - Assert.AreEqual(totalTrashedItems - (++totalDeleted), x); - }); - - Assert.AreEqual(0, RecycleBin.Count(RecycleBin.RecycleBinType.Media)); - } - - [TestMethod] - public void Media_Undelete() - { - //find existing content - var media = new Media(GetExistingNodeId()); - //create new content based on the existing content in the same heirarchy - var mt = new MediaType(media.ContentType.Id); - var parentId = media.ParentId; - var newMedia = Media.MakeNew("NewMedia" + Guid.NewGuid().ToString("N"), mt, m_User, parentId); - Assert.IsTrue(newMedia.Id > 0); - - //this will recycle the node - newMedia.delete(); - Assert.IsTrue(newMedia.IsTrashed); - Assert.IsTrue(newMedia.Path.Contains("," + (int)RecycleBin.RecycleBinType.Media + ",")); - - //undelete the node (move it) - newMedia.Move(parentId); - Assert.IsFalse(newMedia.IsTrashed); - Assert.IsFalse(newMedia.Path.Contains("," + (int)RecycleBin.RecycleBinType.Media + ",")); - - //remove it completely - RecycleAndDelete(newMedia); - } - - #region Tests to write - - ///// - /////A test for Children - ///// - //[TestMethod()] - //public void ChildrenTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Media target = new Media(id); // TODO: Initialize to an appropriate value - // Media[] actual; - // actual = target.Children; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Media target = new Media(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetRootMedias - ///// - //[TestMethod()] - //public void GetRootMediasTest() - //{ - // Media[] expected = null; // TODO: Initialize to an appropriate value - // Media[] actual; - // actual = Media.GetRootMedias(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetChildrenForTree - ///// - //[TestMethod()] - //public void GetChildrenForTreeTest() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // List expected = null; // TODO: Initialize to an appropriate value - // List actual; - // actual = Media.GetChildrenForTree(nodeId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for DeleteFromType - ///// - //[TestMethod()] - //public void DeleteFromTypeTest() - //{ - // MediaType dt = null; // TODO: Initialize to an appropriate value - // Media.DeleteFromType(dt); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Media target = new Media(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - #endregion - - #region Private properties and methods - - /// - /// The user to be used to create stuff - /// - private User m_User = new User(0); - - /// - /// Used for each test initialization. Before each test is run a new root media is created. - /// - private Media m_NewRootMedia; - - /// - /// Returns a label property of the document type specified. This will throw an exception if one is not found. - /// - /// - /// - private Property GetLabelProperty(MediaType mt, Media m) - { - DataTypeNoEdit lblField = new DataTypeNoEdit(); - var prop = mt.PropertyTypes - .Where(x => x.DataTypeDefinition.DataType.Id == lblField.Id).First(); - return m.GenericProperties.Where(x => x.PropertyType.Id == prop.Id).First(); - } - - private Property GetUploadProperty(MediaType mt, Media m) - { - DataTypeNoEdit lblField = new DataTypeNoEdit(); - var prop = mt.PropertyTypes - .Where(x => x.DataTypeDefinition.DataType.Id == lblField.Id).First(); - return m.GenericProperties.Where(x => x.PropertyType.Id == prop.Id).First(); - } - - /// - /// Gets initialized for each test and is set to an existing document type - /// - private MediaType m_ExistingMediaType; - - private void RecycleAndDelete(Media m) - { - if (m == null) - { - return; - } - - var id = m.Id; - - //check if it is already trashed - var alreadyTrashed = m.IsTrashed; - - if (!alreadyTrashed) - { - //now recycle it - m.delete(); - - Assert.IsTrue(m.IsTrashed); - } - - //now permanently delete - m.delete(true); - Assert.IsFalse(Media.IsNode(id)); - - //check with sql that it is gone - var count = Application.SqlHelper.ExecuteScalar("SELECT COUNT(*) FROM umbracoNode WHERE id=@id", - Application.SqlHelper.CreateParameter("@id", id)); - - Assert.AreEqual(0, count); - } - - private int GetExistingNodeId() - { - var ids = Media.getAllUniqueNodeIdsFromObjectType(Media._objectType).ToList(); - var r = new Random(); - var index = r.Next(0, ids.Count() - 1); - return ids[index]; - } - - private Media CreateNewUnderRoot(MediaType mt) - { - string Name = "TEST-" + Guid.NewGuid().ToString("N"); - int ParentId = -1; - Media actual = Media.MakeNew(Name, mt, m_User, ParentId); - var id = actual.Id; - Assert.IsTrue(actual.Id > 0); - return actual; - } - - private MediaType GetExistingDocType() - { - MediaType dct = new MediaType(GetExistingMediaTypeId()); - Assert.IsTrue(dct.Id > 0); - return dct; - } - - private MediaType GetExistingMediaType() - { - MediaType dct = new MediaType(GetExistingMediaTypeId()); - Assert.IsTrue(dct.Id > 0); - return dct; - } - - private int GetExistingMediaTypeId() - { - var types = MediaType.GetAll.ToList(); - MediaType found = null; - DataTypeNoEdit lblField = new DataTypeNoEdit(); - foreach (var d in types) - { - var prop = d.PropertyTypes - .Where(x => x.DataTypeDefinition.DataType.Id == lblField.Id).FirstOrDefault(); - if (prop != null) - { - found = d; - break; - } - } - if (found == null) - { - throw new MissingMemberException("No media type was found that contains a label property"); - } - return found.Id; - } - - #endregion - - #region Initialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - - /// - /// Creates a new root document to use for each test if required - /// - [TestInitialize()] - public void MyTestInitialize() - { - m_ExistingMediaType = GetExistingMediaType(); - m_NewRootMedia = CreateNewUnderRoot(m_ExistingMediaType); - } - - /// - /// Makes sure the root doc is deleted - /// - [TestCleanup()] - public void MyTestCleanup() - { - RecycleAndDelete(m_NewRootMedia); - } - #endregion - - - } -} diff --git a/test/umbraco.Test/MediaTypeTest.cs b/test/umbraco.Test/MediaTypeTest.cs deleted file mode 100644 index 08141a12d6..0000000000 --- a/test/umbraco.Test/MediaTypeTest.cs +++ /dev/null @@ -1,284 +0,0 @@ -using umbraco.cms.businesslogic.media; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using System.Collections.Generic; -using System.Linq; -using umbraco.cms.businesslogic.datatype; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for MediaTypeTest and is intended - ///to contain all MediaTypeTest Unit Tests - /// - [TestClass()] - public class MediaTypeTest - { - /// - ///A test for GetAll - /// - [TestMethod()] - public void MediaType_Get_All() - { - //check with sql that it's the correct number of children - var ids = new List(); - using (var reader = Application.SqlHelper.ExecuteReader(MediaType.m_SQLOptimizedGetAll.Trim(), - Application.SqlHelper.CreateParameter("@nodeObjectType", MediaType._objectType))) - { - while (reader.Read()) - { - ids.Add(reader.Get("id")); - } - } - - var all = MediaType.GetAllAsList(); - - Assert.AreEqual(ids.Distinct().Count(), all.Count()); - } - - /// - /// This will create 3 media types, and create nodes in the following structure: - /// - root - /// -- node1 (of media type #1) - /// --- node 2 (of media type #2) - /// ---- node 3 (of media type #1) - /// ----- node 4 (of media type #3) - /// - /// Then we'll delete media type #1. The result should be that node1 and node3 are completely deleted from the database and node2 and node4 are - /// moved to the recycle bin. - /// - [TestMethod()] - public void MediaType_Delete_Media_Type_With_Media_And_Children_Of_Diff_Media_Types() - { - //System.Diagnostics.Debugger.Break(); - - //create the doc types - var mt1 = CreateNewMediaType(); - var mt2 = CreateNewMediaType(); - var mt3 = CreateNewMediaType(); - - //create the heirarchy - mt1.AllowedChildContentTypeIDs = new int[] { mt2.Id, mt3.Id }; - mt1.Save(); - mt2.AllowedChildContentTypeIDs = new int[] { mt1.Id }; - mt2.Save(); - - //create the content tree - var node1 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt1, m_User, -1); - var node2 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt2, m_User, node1.Id); - var node3 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt1, m_User, node2.Id); - var node4 = Media.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt3, m_User, node3.Id); - - //do the deletion of doc type #1 - DeleteMediaType(mt1); - - //do our checks - Assert.IsFalse(Media.IsNode(node1.Id), "node1 is not deleted"); //this was of doc type 1, should be gone - Assert.IsFalse(Media.IsNode(node3.Id), "node3 is not deleted"); //this was of doc type 1, should be gone - - Assert.IsTrue(Media.IsNode(node2.Id), "node2 is deleted"); - Assert.IsTrue(Media.IsNode(node4.Id), "node4 is deleted"); - - node2 = new Media(node2.Id);//need to re-query the node - Assert.IsTrue(node2.IsTrashed, "node2 is not in the trash"); - node4 = new Media(node4.Id); //need to re-query the node - Assert.IsTrue(node4.IsTrashed, "node 4 is not in the trash"); - - //remove the old data - DeleteMediaType(mt2); - DeleteMediaType(mt3); - - } - - /// - /// Tests adding every type of property to a new media type on a new tab, then delete the tab, then the media type - /// - [TestMethod()] - public void MediaType_Add_Properties_To_Tab_Then_Delete_It() - { - //System.Diagnostics.Debugger.Break(); - - //allow itself to be created under itself - m_NewMediaType.AllowedChildContentTypeIDs = new int[] { m_NewMediaType.Id }; - //create a tab - m_NewMediaType.AddVirtualTab("TEST"); - - //test the tab - var tabs = m_NewMediaType.getVirtualTabs.ToList(); - Assert.AreEqual(1, tabs.Count); - - //create a property - var allDataTypes = DataTypeDefinition.GetAll().ToList(); //get all definitions - var i = 0; - foreach (var dataType in allDataTypes) - { - //add a property type of the first type found in the list - m_NewMediaType.AddPropertyType(dataType, "testProperty" + (++i).ToString(), "Test Property" + i.ToString()); - //test the prop - var prop = m_NewMediaType.getPropertyType("testProperty" + i.ToString()); - Assert.IsTrue(prop.Id > 0); - Assert.AreEqual("Test Property" + i.ToString(), prop.Name); - //put the properties to the tab - m_NewMediaType.SetTabOnPropertyType(prop, tabs[0].Id); - //re-get the property since data is cached in the object - prop = m_NewMediaType.getPropertyType("testProperty" + i.ToString()); - Assert.AreEqual(tabs[0].Id, prop.TabId); - } - - //now we need to delete the tab - m_NewMediaType.DeleteVirtualTab(tabs[0].Id); - } - - #region Test to write - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MediaType target = new MediaType(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for MakeNew - ///// - //[TestMethod()] - //public void MakeNewTest() - //{ - // User u = null; // TODO: Initialize to an appropriate value - // string Text = string.Empty; // TODO: Initialize to an appropriate value - // MediaType expected = null; // TODO: Initialize to an appropriate value - // MediaType actual; - // actual = MediaType.MakeNew(u, Text); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetByAlias - ///// - //[TestMethod()] - //public void GetByAliasTest() - //{ - // string Alias = string.Empty; // TODO: Initialize to an appropriate value - // MediaType expected = null; // TODO: Initialize to an appropriate value - // MediaType actual; - // actual = MediaType.GetByAlias(Alias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MediaType target = new MediaType(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for MediaType Constructor - ///// - //[TestMethod()] - //public void MediaTypeConstructorTest1() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // MediaType target = new MediaType(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for MediaType Constructor - ///// - //[TestMethod()] - //public void MediaTypeConstructorTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MediaType target = new MediaType(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - #endregion - - #region Private properties and methods - - private User m_User = new User(0); - - /// - /// before each test starts, this object is created so it can be used for testing. - /// - private MediaType m_NewMediaType; - - /// - /// Create a brand new media type - /// - /// - private MediaType CreateNewMediaType() - { - var mt = MediaType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - Assert.IsTrue(mt.Id > 0); - Assert.AreEqual(DateTime.Now.Date, mt.CreateDateTime.Date); - return mt; - } - - private void DeleteMediaType(MediaType mt) - { - var id = mt.Id; - - mt.delete(); - - //check with sql that it is gone - var count = Application.SqlHelper.ExecuteScalar("SELECT COUNT(*) FROM umbracoNode WHERE id=@id", - Application.SqlHelper.CreateParameter("@id", id)); - - Assert.AreEqual(0, count); - } - - #endregion - - #region Initialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - /// - /// Create a new document type for use in tests - /// - [TestInitialize()] - public void MyTestInitialize() - { - m_NewMediaType = CreateNewMediaType(); - } - - /// - /// Remove the created document type - /// - [TestCleanup()] - public void MyTestCleanup() - { - DeleteMediaType(m_NewMediaType); - } - #endregion - - } -} diff --git a/test/umbraco.Test/MemberGroupTest.cs b/test/umbraco.Test/MemberGroupTest.cs deleted file mode 100644 index c3c60b56de..0000000000 --- a/test/umbraco.Test/MemberGroupTest.cs +++ /dev/null @@ -1,259 +0,0 @@ -using umbraco.cms.businesslogic.member; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using System.Collections; -using System.Linq; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for MemberGroupTest and is intended - ///to contain all MemberGroupTest Unit Tests - /// - [TestClass()] - public class MemberGroupTest - { - - /// - /// Make a new member group and delete it - /// - [TestMethod()] - public void MemberGroup_Make_New() - { - var m = MemberGroup.MakeNew(Guid.NewGuid().ToString("N"), m_User); - Assert.IsTrue(m.Id > 0); - Assert.IsInstanceOfType(m, typeof(MemberGroup)); - - m.delete(); - //make sure its gone - Assert.IsFalse(MemberGroup.IsNode(m.Id)); - - } - - /// - /// Create a new member group, put a member in it, then delete the group and ensure the member is gone - /// - [TestMethod()] - public void MemberGroup_Add_Member_To_Group_And_Delete_Group() - { - var mt = MemberType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - var m = Member.MakeNew("TEST" + Guid.NewGuid().ToString("N"), - "TEST" + Guid.NewGuid().ToString("N") + "@test.com", mt, m_User); - - var mg = MemberGroup.MakeNew("TEST" + Guid.NewGuid().ToString("N"), m_User); - Assert.IsInstanceOfType(mg, typeof(MemberGroup)); - Assert.IsTrue(mg.Id > 0); - - //add the member to the group - m.AddGroup(mg.Id); - - //ensure they are added - Assert.AreEqual(1, m.Groups.Count); - Assert.AreEqual(mg.Id, ((MemberGroup)m.Groups.Cast().First().Value).Id); - - //delete the group - mg.delete(); - - //make sure the member is no longer associated - m = new Member(m.Id); //need to re-get the member - Assert.AreEqual(0, m.Groups.Count); - - //now cleanup... - - m.delete(); - Assert.IsFalse(Member.IsNode(m.Id)); - - mt.delete(); - Assert.IsFalse(MemberType.IsNode(mt.Id)); - } - - private User m_User = new User(0); - - #region Tests to write - - ///// - /////A test for MemberGroup Constructor - ///// - //[TestMethod()] - //public void MemberGroupConstructorTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for MemberGroup Constructor - ///// - //[TestMethod()] - //public void MemberGroupConstructorTest1() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for GetByName - ///// - //[TestMethod()] - //public void GetByNameTest() - //{ - // string Name = string.Empty; // TODO: Initialize to an appropriate value - // MemberGroup expected = null; // TODO: Initialize to an appropriate value - // MemberGroup actual; - // actual = MemberGroup.GetByName(Name); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMembers - ///// - //[TestMethod()] - //public void GetMembersTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); // TODO: Initialize to an appropriate value - // Member[] expected = null; // TODO: Initialize to an appropriate value - // Member[] actual; - // actual = target.GetMembers(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMembers - ///// - //[TestMethod()] - //public void GetMembersTest1() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); // TODO: Initialize to an appropriate value - // string usernameToMatch = string.Empty; // TODO: Initialize to an appropriate value - // Member[] expected = null; // TODO: Initialize to an appropriate value - // Member[] actual; - // actual = target.GetMembers(usernameToMatch); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMembersAsIds - ///// - //[TestMethod()] - //public void GetMembersAsIdsTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); // TODO: Initialize to an appropriate value - // int[] expected = null; // TODO: Initialize to an appropriate value - // int[] actual; - // actual = target.GetMembersAsIds(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for HasMember - ///// - //[TestMethod()] - //public void HasMemberTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); // TODO: Initialize to an appropriate value - // int memberId = 0; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = target.HasMember(memberId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // MemberGroup[] actual; - // actual = MemberGroup.GetAll; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Text - ///// - //[TestMethod()] - //public void TextTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberGroup target = new MemberGroup(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Text = expected; - // actual = target.Text; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/MemberTest.cs b/test/umbraco.Test/MemberTest.cs deleted file mode 100644 index 8e06dc7a5e..0000000000 --- a/test/umbraco.Test/MemberTest.cs +++ /dev/null @@ -1,626 +0,0 @@ -using umbraco.cms.businesslogic.member; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Collections; -using umbraco.BusinessLogic; -using System.Linq; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for MemberTest and is intended - ///to contain all MemberTest Unit Tests - /// - [TestClass()] - public class MemberTest - { - - /// - /// Creates a new member type and member, then deletes it - /// - [TestMethod()] - public void Member_Make_New() - { - - var mt = MemberType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - var m = Member.MakeNew("TEST" + Guid.NewGuid().ToString("N"), - "TEST" + Guid.NewGuid().ToString("N") + "@test.com", mt, m_User); - - Assert.IsInstanceOfType(m, typeof(Member)); - Assert.IsTrue(m.Id > 0); - - m.delete(); - Assert.IsFalse(Member.IsNode(m.Id)); - - mt.delete(); - Assert.IsFalse(MemberType.IsNode(mt.Id)); - } - - /// - ///Creates a new member type, member group and a member, then adds the member to the group. - ///then deletes the data in order for cleanup - /// - [TestMethod()] - public void Member_Add_To_Group() - { - var mt = MemberType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - var m = Member.MakeNew("TEST" + Guid.NewGuid().ToString("N"), - "TEST" + Guid.NewGuid().ToString("N") + "@test.com", mt, m_User); - - var mg = MemberGroup.MakeNew("TEST" + Guid.NewGuid().ToString("N"), m_User); - Assert.IsInstanceOfType(mg, typeof(MemberGroup)); - Assert.IsTrue(mg.Id > 0); - - //add the member to the group - m.AddGroup(mg.Id); - - //ensure they are added - Assert.AreEqual(1, m.Groups.Count); - Assert.AreEqual(mg.Id, ((MemberGroup)m.Groups.Cast().First().Value).Id); - - //remove the grup association - m.RemoveGroup(mg.Id); - - //ensure they are removed - Assert.AreEqual(0, m.Groups.Count); - - mg.delete(); - Assert.IsFalse(Member.IsNode(mg.Id)); - - m.delete(); - Assert.IsFalse(Member.IsNode(m.Id)); - - mt.delete(); - Assert.IsFalse(MemberType.IsNode(mt.Id)); - } - - #region Private members - private User m_User = new User(0); - #endregion - - #region Test to write - ///// - /////A test for Member Constructor - ///// - //[TestMethod()] - //public void MemberConstructorTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // bool noSetup = false; // TODO: Initialize to an appropriate value - // Member target = new Member(id, noSetup); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Member Constructor - ///// - //[TestMethod()] - //public void MemberConstructorTest1() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // bool noSetup = false; // TODO: Initialize to an appropriate value - // Member target = new Member(id, noSetup); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Member Constructor - ///// - //[TestMethod()] - //public void MemberConstructorTest2() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Member target = new Member(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Member Constructor - ///// - //[TestMethod()] - //public void MemberConstructorTest3() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - - - ///// - /////A test for AddMemberToCache - ///// - //[TestMethod()] - //public void AddMemberToCacheTest() - //{ - // Member m = null; // TODO: Initialize to an appropriate value - // Member.AddMemberToCache(m); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for AddMemberToCache - ///// - //[TestMethod()] - //public void AddMemberToCacheTest1() - //{ - // Member m = null; // TODO: Initialize to an appropriate value - // bool UseSession = false; // TODO: Initialize to an appropriate value - // TimeSpan TimespanForCookie = new TimeSpan(); // TODO: Initialize to an appropriate value - // Member.AddMemberToCache(m, UseSession, TimespanForCookie); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for CachedMembers - ///// - //[TestMethod()] - //public void CachedMembersTest() - //{ - // Hashtable expected = null; // TODO: Initialize to an appropriate value - // Hashtable actual; - // actual = Member.CachedMembers(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for ChangePassword - ///// - //[TestMethod()] - //public void ChangePasswordTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // string newPassword = string.Empty; // TODO: Initialize to an appropriate value - // target.ChangePassword(newPassword); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ClearMemberFromClient - ///// - //[TestMethod()] - //public void ClearMemberFromClientTest() - //{ - // int NodeId = 0; // TODO: Initialize to an appropriate value - // Member.ClearMemberFromClient(NodeId); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ClearMemberFromClient - ///// - //[TestMethod()] - //public void ClearMemberFromClientTest1() - //{ - // Member m = null; // TODO: Initialize to an appropriate value - // Member.ClearMemberFromClient(m); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for CurrentMemberId - ///// - //[TestMethod()] - //public void CurrentMemberIdTest() - //{ - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // actual = Member.CurrentMemberId(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for DeleteFromType - ///// - //[TestMethod()] - //public void DeleteFromTypeTest() - //{ - // MemberType dt = null; // TODO: Initialize to an appropriate value - // Member.DeleteFromType(dt); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetCurrentMember - ///// - //[TestMethod()] - //public void GetCurrentMemberTest() - //{ - // Member expected = null; // TODO: Initialize to an appropriate value - // Member actual; - // actual = Member.GetCurrentMember(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMemberByName - ///// - //[TestMethod()] - //public void GetMemberByNameTest() - //{ - // string usernameToMatch = string.Empty; // TODO: Initialize to an appropriate value - // bool matchByNameInsteadOfLogin = false; // TODO: Initialize to an appropriate value - // Member[] expected = null; // TODO: Initialize to an appropriate value - // Member[] actual; - // actual = Member.GetMemberByName(usernameToMatch, matchByNameInsteadOfLogin); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMemberFromCache - ///// - //[TestMethod()] - //public void GetMemberFromCacheTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Member expected = null; // TODO: Initialize to an appropriate value - // Member actual; - // actual = Member.GetMemberFromCache(id); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMemberFromEmail - ///// - //[TestMethod()] - //public void GetMemberFromEmailTest() - //{ - // string email = string.Empty; // TODO: Initialize to an appropriate value - // Member expected = null; // TODO: Initialize to an appropriate value - // Member actual; - // actual = Member.GetMemberFromEmail(email); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMemberFromLoginAndEncodedPassword - ///// - //[TestMethod()] - //public void GetMemberFromLoginAndEncodedPasswordTest() - //{ - // string loginName = string.Empty; // TODO: Initialize to an appropriate value - // string password = string.Empty; // TODO: Initialize to an appropriate value - // Member expected = null; // TODO: Initialize to an appropriate value - // Member actual; - // actual = Member.GetMemberFromLoginAndEncodedPassword(loginName, password); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMemberFromLoginName - ///// - //[TestMethod()] - //public void GetMemberFromLoginNameTest() - //{ - // string loginName = string.Empty; // TODO: Initialize to an appropriate value - // Member expected = null; // TODO: Initialize to an appropriate value - // Member actual; - // actual = Member.GetMemberFromLoginName(loginName); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetMemberFromLoginNameAndPassword - ///// - //[TestMethod()] - //public void GetMemberFromLoginNameAndPasswordTest() - //{ - // string loginName = string.Empty; // TODO: Initialize to an appropriate value - // string password = string.Empty; // TODO: Initialize to an appropriate value - // Member expected = null; // TODO: Initialize to an appropriate value - // Member actual; - // actual = Member.GetMemberFromLoginNameAndPassword(loginName, password); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for InUmbracoMemberMode - ///// - //[TestMethod()] - //public void InUmbracoMemberModeTest() - //{ - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = Member.InUmbracoMemberMode(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for IsLoggedOn - ///// - //[TestMethod()] - //public void IsLoggedOnTest() - //{ - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = Member.IsLoggedOn(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for IsMember - ///// - //[TestMethod()] - //public void IsMemberTest() - //{ - // string loginName = string.Empty; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = Member.IsMember(loginName); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for IsUsingUmbracoRoles - ///// - //[TestMethod()] - //public void IsUsingUmbracoRolesTest() - //{ - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = Member.IsUsingUmbracoRoles(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for MakeNew - ///// - //[TestMethod()] - //public void MakeNewTest1() - //{ - // string Name = string.Empty; // TODO: Initialize to an appropriate value - // MemberType mbt = null; // TODO: Initialize to an appropriate value - // User u = null; // TODO: Initialize to an appropriate value - // Member expected = null; // TODO: Initialize to an appropriate value - // Member actual; - // actual = Member.MakeNew(Name, mbt, u); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for RemoveGroup - ///// - //[TestMethod()] - //public void RemoveGroupTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // int GroupId = 0; // TODO: Initialize to an appropriate value - // target.RemoveGroup(GroupId); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for RemoveMemberFromCache - ///// - //[TestMethod()] - //public void RemoveMemberFromCacheTest() - //{ - // Member m = null; // TODO: Initialize to an appropriate value - // Member.RemoveMemberFromCache(m); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for RemoveMemberFromCache - ///// - //[TestMethod()] - //public void RemoveMemberFromCacheTest1() - //{ - // int NodeId = 0; // TODO: Initialize to an appropriate value - // Member.RemoveMemberFromCache(NodeId); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ToXml - ///// - //[TestMethod()] - //public void ToXmlTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // bool Deep = false; // TODO: Initialize to an appropriate value - // XmlNode expected = null; // TODO: Initialize to an appropriate value - // XmlNode actual; - // actual = target.ToXml(xd, Deep); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for XmlGenerate - ///// - //[TestMethod()] - //public void XmlGenerateTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // target.XmlGenerate(xd); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - - - ///// - /////A test for getAllOtherMembers - ///// - //[TestMethod()] - //public void getAllOtherMembersTest() - //{ - // Member[] expected = null; // TODO: Initialize to an appropriate value - // Member[] actual; - // actual = Member.getAllOtherMembers(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for getMemberFromFirstLetter - ///// - //[TestMethod()] - //public void getMemberFromFirstLetterTest() - //{ - // char letter = '\0'; // TODO: Initialize to an appropriate value - // Member[] expected = null; // TODO: Initialize to an appropriate value - // Member[] actual; - // actual = Member.getMemberFromFirstLetter(letter); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Email - ///// - //[TestMethod()] - //public void EmailTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Email = expected; - // actual = target.Email; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // Member[] actual; - // actual = Member.GetAll; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Groups - ///// - //[TestMethod()] - //public void GroupsTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // Hashtable actual; - // actual = target.Groups; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for LoginName - ///// - //[TestMethod()] - //public void LoginNameTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.LoginName = expected; - // actual = target.LoginName; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Password - ///// - //[TestMethod()] - //public void PasswordTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Password = expected; - // actual = target.Password; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Text - ///// - //[TestMethod()] - //public void TextTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Member target = new Member(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Text = expected; - // actual = target.Text; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - - #region Initialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - - } -} diff --git a/test/umbraco.Test/MemberTypeTest.cs b/test/umbraco.Test/MemberTypeTest.cs deleted file mode 100644 index d7c4e8eddc..0000000000 --- a/test/umbraco.Test/MemberTypeTest.cs +++ /dev/null @@ -1,260 +0,0 @@ -using umbraco.cms.businesslogic.member; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using umbraco.cms.businesslogic.propertytype; -using umbraco.cms.businesslogic.datatype; -using System.Linq; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for MemberTypeTest and is intended - ///to contain all MemberTypeTest Unit Tests - /// - [TestClass()] - public class MemberTypeTest - { - - [TestMethod()] - public void MemberType_Make_New_Add_Remove_Properties() - { - var m = MemberType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - - Assert.IsInstanceOfType(m, typeof(MemberType)); - Assert.IsTrue(m.Id > 0); - - //System.Diagnostics.Debugger.Launch(); - - AddMemberTypeProperty(ref m); - AddMemberTypeProperty(ref m); - AddMemberTypeProperty(ref m); - AddMemberTypeProperty(ref m); - - //remove it - m.delete(); - Assert.IsFalse(MemberType.IsNode(m.Id)); - } - - private void AddMemberTypeProperty(ref MemberType m) - { - var ddt = DataTypeDefinition.GetAll().First(); - //needs to start with a letter - var alias = "m" + Guid.NewGuid().ToString("N"); - m.AddPropertyType(ddt, alias, alias); - //make sure it's there - var prop = m.getPropertyType(alias); - Assert.IsInstanceOfType(prop, typeof(PropertyType)); - } - - /// - ///A test for MakeNew - /// - [TestMethod()] - public void MemberType_Make_New() - { - var m = MemberType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - - Assert.IsInstanceOfType(m, typeof(MemberType)); - Assert.IsTrue(m.Id > 0); - - //remove it - m.delete(); - Assert.IsFalse(MemberType.IsNode(m.Id)); - } - - /// - /// Create a member type, create some members of the member type and then delete the member type. - /// This should also delete all of the members. - /// - [TestMethod()] - public void MemberType_Delete_With_Assigned_Members() - { - - var mt1 = MemberType.MakeNew(m_User, "TEST" + Guid.NewGuid().ToString("N")); - - //create the members - var node1 = Member.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt1, m_User); - var node2 = Member.MakeNew("TEST" + Guid.NewGuid().ToString("N"), mt1, m_User); - - //do the deletion of doc type #1 - mt1.delete(); - Assert.IsFalse(MemberType.IsNode(mt1.Id)); - - //do our checks - Assert.IsFalse(Member.IsNode(node1.Id), "node1 is not deleted"); - Assert.IsFalse(Member.IsNode(node2.Id), "node2 is not deleted"); - } - - #region Tests to write - ///// - /////A test for MemberType Constructor - ///// - //[TestMethod()] - //public void MemberTypeConstructorTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for MemberType Constructor - ///// - //[TestMethod()] - //public void MemberTypeConstructorTest1() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for GetByAlias - ///// - //[TestMethod()] - //public void GetByAliasTest() - //{ - // string Alias = string.Empty; // TODO: Initialize to an appropriate value - // MemberType expected = null; // TODO: Initialize to an appropriate value - // MemberType actual; - // actual = MemberType.GetByAlias(Alias); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for MemberCanEdit - ///// - //[TestMethod()] - //public void MemberCanEditTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); // TODO: Initialize to an appropriate value - // PropertyType pt = null; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = target.MemberCanEdit(pt); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ViewOnProfile - ///// - //[TestMethod()] - //public void ViewOnProfileTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); // TODO: Initialize to an appropriate value - // PropertyType pt = null; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = target.ViewOnProfile(pt); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for setMemberCanEdit - ///// - //[TestMethod()] - //public void setMemberCanEditTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); // TODO: Initialize to an appropriate value - // PropertyType pt = null; // TODO: Initialize to an appropriate value - // bool value = false; // TODO: Initialize to an appropriate value - // target.setMemberCanEdit(pt, value); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for setMemberViewOnProfile - ///// - //[TestMethod()] - //public void setMemberViewOnProfileTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // MemberType target = new MemberType(id); // TODO: Initialize to an appropriate value - // PropertyType pt = null; // TODO: Initialize to an appropriate value - // bool value = false; // TODO: Initialize to an appropriate value - // target.setMemberViewOnProfile(pt, value); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // MemberType[] actual; - // actual = MemberType.GetAll; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Private methods - - private User m_User = new User(0); - - #endregion - - #region Initialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/NotificationTest.cs b/test/umbraco.Test/NotificationTest.cs deleted file mode 100644 index 16653fbb19..0000000000 --- a/test/umbraco.Test/NotificationTest.cs +++ /dev/null @@ -1,199 +0,0 @@ -using umbraco.cms.businesslogic.workflow; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using umbraco.cms.businesslogic.web; -using System.Linq; -using umbraco.BusinessLogic.Actions; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for NotificationTest and is intended - ///to contain all NotificationTest Unit Tests - /// - [TestClass()] - public class NotificationTest - { - /// - /// Create a new notification for the admin user for the first node found in the tree and delete it. - /// - [TestMethod()] - public void Notification_Make_New() - { - //create a new notification - var doc = Document.GetRootDocuments().First(); - Notification.MakeNew(m_User, doc, ActionNew.Instance.Letter); - - //get the notifications - var n = Notification.GetUserNotifications(m_User); - Assert.IsTrue(n.Count() > 0); - Assert.AreEqual(1, n.Where(x => x.NodeId == doc.Id && x.UserId == m_User.Id && x.ActionId == ActionNew.Instance.Letter).Count()); - - //delete the notification - Notification.DeleteNotifications(doc); - - //make sure they're gone - Assert.AreEqual(0, Notification.GetNodeNotifications(doc).Count()); - - } - - /// - /// Creates a new document, assigns some notifications to it, then deletes the document. - /// Need to ensure that the notifications are removed. - /// - [TestMethod()] - public void Notification_Assign_To_New_Node_Then_Delete_Node() - { - //create anew document - var dt = DocumentType.GetAllAsList().First(); - var doc = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - - //assign a notification to it - Notification.MakeNew(m_User, doc, ActionNew.Instance.Letter); - - //delete the document permanently - doc.delete(true); - - //make sure they're gone - Assert.AreEqual(0, Notification.GetNodeNotifications(doc).Count()); - Assert.IsFalse(Document.IsNode(doc.Id)); - - } - - /// - /// Create a new user, assign a notification to it, remove the user and ensure the notifications are gone as well. - /// - [TestMethod()] - public void Notification_Assign_To_New_User_Then_Delete_User() - { - //create anew document - var ut = UserType.GetAllUserTypes().First(); - var u = User.MakeNew(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"), ut); - //get a doc - var doc = Document.GetRootDocuments().First(); - - //assign a notification to the user - Notification.MakeNew(u, doc, ActionNew.Instance.Letter); - - //delete the document permanently - u.delete(); - - //make sure they're gone - Assert.AreEqual(0, Notification.GetUserNotifications(u).Count()); - Assert.IsNull(User.GetUser(u.Id)); - - } - - private User m_User = new User(0); - - #region Tests to write - - - ///// - /////A test for DeleteNotifications - ///// - //[TestMethod()] - //public void DeleteNotificationsTest() - //{ - // User user = null; // TODO: Initialize to an appropriate value - // CMSNode node = null; // TODO: Initialize to an appropriate value - // Notification.DeleteNotifications(user, node); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for DeleteNotifications - ///// - //[TestMethod()] - //public void DeleteNotificationsTest1() - //{ - // User user = null; // TODO: Initialize to an appropriate value - // Notification.DeleteNotifications(user); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for DeleteNotifications - ///// - //[TestMethod()] - //public void DeleteNotificationsTest2() - //{ - // CMSNode node = null; // TODO: Initialize to an appropriate value - // Notification.DeleteNotifications(node); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetNotifications - ///// - //[TestMethod()] - //public void GetNotificationsTest() - //{ - // CMSNode Node = null; // TODO: Initialize to an appropriate value - // User user = null; // TODO: Initialize to an appropriate value - // IAction Action = null; // TODO: Initialize to an appropriate value - // Notification.GetNotifications(Node, user, Action); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for MakeNew - ///// - //[TestMethod()] - //public void MakeNewTest() - //{ - // User User = null; // TODO: Initialize to an appropriate value - // CMSNode Node = null; // TODO: Initialize to an appropriate value - // char ActionLetter = '\0'; // TODO: Initialize to an appropriate value - // Notification.MakeNew(User, Node, ActionLetter); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for UpdateNotifications - ///// - //[TestMethod()] - //public void UpdateNotificationsTest() - //{ - // User User = null; // TODO: Initialize to an appropriate value - // CMSNode Node = null; // TODO: Initialize to an appropriate value - // string Notifications = string.Empty; // TODO: Initialize to an appropriate value - // Notification.UpdateNotifications(User, Node, Notifications); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/PermissionTest.cs b/test/umbraco.Test/PermissionTest.cs deleted file mode 100644 index 6d8fc1896e..0000000000 --- a/test/umbraco.Test/PermissionTest.cs +++ /dev/null @@ -1,174 +0,0 @@ -using umbraco.BusinessLogic; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic.Actions; -using umbraco.cms.businesslogic.web; -using System.Linq; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for PermissionTest and is intended - ///to contain all PermissionTest Unit Tests - /// - [TestClass()] - public class PermissionTest - { - - /// - /// Create a new permission and delete it - /// - [TestMethod()] - public void Permission_Make_New() - { - var doc = Document.GetRootDocuments().First(); - Permission.MakeNew(m_User, doc, ActionNew.Instance.Letter); - - //get the notifications - var n = Permission.GetUserPermissions(m_User); - Assert.IsTrue(n.Count() > 0); - Assert.AreEqual(1, n.Where(x => x.NodeId == doc.Id && x.UserId == m_User.Id && x.PermissionId == ActionNew.Instance.Letter).Count()); - - //delete the notification - Permission.DeletePermissions(doc); - - //make sure they're gone - Assert.AreEqual(0, Permission.GetNodePermissions(doc).Count()); - - - } - - /// - /// Creates a new document, assigns some Permissions to it, then deletes the document. - /// Need to ensure that the Permissions are removed. - /// - [TestMethod()] - public void Permission_Assign_To_New_Node_Then_Delete_Node() - { - //create anew document - var dt = DocumentType.GetAllAsList().First(); - var doc = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - - //assign a Permission to it - Permission.MakeNew(m_User, doc, ActionNew.Instance.Letter); - - //delete the document permanently - doc.delete(true); - - //make sure they're gone - Assert.AreEqual(0, Permission.GetNodePermissions(doc).Count()); - Assert.IsFalse(Document.IsNode(doc.Id)); - - } - - /// - /// Create a new user, assign a Permission to it, remove the user and ensure the Permission are gone as well. - /// - [TestMethod()] - public void Permission_Assign_To_New_User_Then_Delete_User() - { - //create anew document - var ut = UserType.GetAllUserTypes().First(); - var u = User.MakeNew(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"), ut); - //get a doc - var doc = Document.GetRootDocuments().First(); - - //assign a notification to the user - Permission.MakeNew(u, doc, ActionNew.Instance.Letter); - - //delete the document permanently - u.delete(); - - //make sure they're gone - Assert.AreEqual(0, Permission.GetUserPermissions(u).Count()); - Assert.IsNull(User.GetUser(u.Id)); - - } - - private User m_User = new User(0); - - #region Tests to write - - ///// - /////A test for DeletePermissions - ///// - //[TestMethod()] - //public void DeletePermissionsTest() - //{ - // CMSNode node = null; // TODO: Initialize to an appropriate value - // Permission.DeletePermissions(node); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for DeletePermissions - ///// - //[TestMethod()] - //public void DeletePermissionsTest1() - //{ - // User user = null; // TODO: Initialize to an appropriate value - // CMSNode node = null; // TODO: Initialize to an appropriate value - // Permission.DeletePermissions(user, node); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for DeletePermissions - ///// - //[TestMethod()] - //public void DeletePermissionsTest2() - //{ - // User user = null; // TODO: Initialize to an appropriate value - // Permission.DeletePermissions(user); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - - - ///// - /////A test for UpdateCruds - ///// - //[TestMethod()] - //public void UpdateCrudsTest() - //{ - // User user = null; // TODO: Initialize to an appropriate value - // CMSNode node = null; // TODO: Initialize to an appropriate value - // string permissions = string.Empty; // TODO: Initialize to an appropriate value - // Permission.UpdateCruds(user, node, permissions); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/Properties/AssemblyInfo.cs b/test/umbraco.Test/Properties/AssemblyInfo.cs deleted file mode 100644 index b1c866b616..0000000000 --- a/test/umbraco.Test/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("umbraco.Test")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("umbraco.Test")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM componenets. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("662e3518-c5af-49ea-a195-dee4b94a522d")] \ No newline at end of file diff --git a/test/umbraco.Test/PropertyTypeTest.cs b/test/umbraco.Test/PropertyTypeTest.cs deleted file mode 100644 index 0ba0b28623..0000000000 --- a/test/umbraco.Test/PropertyTypeTest.cs +++ /dev/null @@ -1,342 +0,0 @@ -using umbraco.cms.businesslogic.propertytype; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.cms.businesslogic.datatype; -using System.Linq; -using umbraco.cms.businesslogic.web; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for PropertyTypeTest and is intended - ///to contain all PropertyTypeTest Unit Tests - /// - [TestClass()] - public class PropertyTypeTest - { - - /// - ///A test for MakeNew - /// - [TestMethod()] - public void PropertyType_Make_New() - { - - var allDataTypes = DataTypeDefinition.GetAll().ToList(); //get all definitions - var contentTypes = DocumentType.GetAllAsList(); - - var name = "TEST" + Guid.NewGuid().ToString("N"); - var pt = PropertyType.MakeNew(allDataTypes.First(), contentTypes.First(), name, name); - - Assert.IsTrue(pt.Id > 0); - Assert.IsInstanceOfType(pt, typeof(PropertyType)); - - pt.delete(); - - //make sure it's gone - Assert.IsFalse(PropertyType.GetAll().Select(x => x.Id).Contains(pt.Id)); - - } - - - #region Tests to write - ///// - /////A test for PropertyType Constructor - ///// - //[TestMethod()] - //public void PropertyTypeConstructorTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // PropertyType[] expected = null; // TODO: Initialize to an appropriate value - // PropertyType[] actual; - // actual = PropertyType.GetAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetEditControl - ///// - //[TestMethod()] - //public void GetEditControlTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // object Value = null; // TODO: Initialize to an appropriate value - // bool IsPostBack = false; // TODO: Initialize to an appropriate value - // IDataType expected = null; // TODO: Initialize to an appropriate value - // IDataType actual; - // actual = target.GetEditControl(Value, IsPostBack); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetPropertyType - ///// - //[TestMethod()] - //public void GetPropertyTypeTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType expected = null; // TODO: Initialize to an appropriate value - // PropertyType actual; - // actual = PropertyType.GetPropertyType(id); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetRawDescription - ///// - //[TestMethod()] - //public void GetRawDescriptionTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // actual = target.GetRawDescription(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetRawName - ///// - //[TestMethod()] - //public void GetRawNameTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // actual = target.GetRawName(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Alias - ///// - //[TestMethod()] - //public void AliasTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Alias = expected; - // actual = target.Alias; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for ContentTypeId - ///// - //[TestMethod()] - //public void ContentTypeIdTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // int actual; - // actual = target.ContentTypeId; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for DataTypeDefinition - ///// - //[TestMethod()] - //public void DataTypeDefinitionTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // DataTypeDefinition expected = null; // TODO: Initialize to an appropriate value - // DataTypeDefinition actual; - // target.DataTypeDefinition = expected; - // actual = target.DataTypeDefinition; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Description - ///// - //[TestMethod()] - //public void DescriptionTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Description = expected; - // actual = target.Description; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Id - ///// - //[TestMethod()] - //public void IdTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // int actual; - // actual = target.Id; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Mandatory - ///// - //[TestMethod()] - //public void MandatoryTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.Mandatory = expected; - // actual = target.Mandatory; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Name - ///// - //[TestMethod()] - //public void NameTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Name = expected; - // actual = target.Name; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for SortOrder - ///// - //[TestMethod()] - //public void SortOrderTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.SortOrder = expected; - // actual = target.SortOrder; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for TabId - ///// - //[TestMethod()] - //public void TabIdTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.TabId = expected; - // actual = target.TabId; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for ValidationRegExp - ///// - //[TestMethod()] - //public void ValidationRegExpTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // PropertyType target = new PropertyType(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.ValidationRegExp = expected; - // actual = target.ValidationRegExp; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - - #region Initialize and cleanup - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/RelationTest.cs b/test/umbraco.Test/RelationTest.cs deleted file mode 100644 index 8935da5a3d..0000000000 --- a/test/umbraco.Test/RelationTest.cs +++ /dev/null @@ -1,310 +0,0 @@ -using umbraco.cms.businesslogic.relation; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.cms.businesslogic.web; -using System.Linq; -using umbraco.BusinessLogic; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for RelationTest and is intended - ///to contain all RelationTest Unit Tests - /// - [TestClass()] - public class RelationTest - { - - /// - /// Creates 2 documents and relates them, then deletes the relation - /// - [TestMethod()] - public void Relation_Make_New() - { - var dt = DocumentType.GetAllAsList().First(); - var parent = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - var child = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - var rt = RelationType.GetAll().First(); - - //make the relation - var r = Relation.MakeNew(parent.Id, child.Id, rt, Guid.NewGuid().ToString("N")); - Assert.IsTrue(r.Id > 0); - Assert.IsInstanceOfType(r, typeof(Relation)); - - //delete the relation - r.Delete(); - //make sure it's gone by looking up both parent & children - Assert.AreEqual(0, Relation.GetRelations(parent.Id).Count()); - Assert.AreEqual(0, Relation.GetRelations(child.Id).Count()); - - //now remove the documents - child.delete(true); - parent.delete(true); - } - - /// - /// Creates 2 documents, relates them, then deletes the parent doc and ensure that the relation is gone - /// - [TestMethod()] - public void Relation_Relate_Docs_And_Delete_Parent() - { - var dt = DocumentType.GetAllAsList().First(); - var parent = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - var child = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - var rt = RelationType.GetAll().First(); - - //make the relation - var r = Relation.MakeNew(parent.Id, child.Id, rt, Guid.NewGuid().ToString("N")); - Assert.IsTrue(r.Id > 0); - Assert.IsInstanceOfType(r, typeof(Relation)); - - //deletes the parent - parent.delete(true); - - //make sure it's gone by looking up both parent & children - Assert.AreEqual(0, Relation.GetRelations(parent.Id).Count()); - Assert.AreEqual(0, Relation.GetRelations(child.Id).Count()); - - //now remove the documents - child.delete(true); - } - - private User m_User = new User(0); - - #region Tests to write - - ///// - /////A test for Relation Constructor - ///// - //[TestMethod()] - //public void RelationConstructorTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Delete - ///// - //[TestMethod()] - //public void DeleteTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // target.Delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetRelations - ///// - //[TestMethod()] - //public void GetRelationsTest() - //{ - // int NodeId = 0; // TODO: Initialize to an appropriate value - // RelationType Filter = null; // TODO: Initialize to an appropriate value - // Relation[] expected = null; // TODO: Initialize to an appropriate value - // Relation[] actual; - // actual = Relation.GetRelations(NodeId, Filter); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetRelations - ///// - //[TestMethod()] - //public void GetRelationsTest1() - //{ - // int NodeId = 0; // TODO: Initialize to an appropriate value - // Relation[] expected = null; // TODO: Initialize to an appropriate value - // Relation[] actual; - // actual = Relation.GetRelations(NodeId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetRelationsAsList - ///// - //[TestMethod()] - //public void GetRelationsAsListTest() - //{ - // int NodeId = 0; // TODO: Initialize to an appropriate value - // List expected = null; // TODO: Initialize to an appropriate value - // List actual; - // actual = Relation.GetRelationsAsList(NodeId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for IsRelated - ///// - //[TestMethod()] - //public void IsRelatedTest() - //{ - // int ParentID = 0; // TODO: Initialize to an appropriate value - // int ChildId = 0; // TODO: Initialize to an appropriate value - // RelationType Filter = null; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = Relation.IsRelated(ParentID, ChildId, Filter); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for IsRelated - ///// - //[TestMethod()] - //public void IsRelatedTest1() - //{ - // int ParentID = 0; // TODO: Initialize to an appropriate value - // int ChildId = 0; // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // actual = Relation.IsRelated(ParentID, ChildId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Child - ///// - //[TestMethod()] - //public void ChildTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // CMSNode expected = null; // TODO: Initialize to an appropriate value - // CMSNode actual; - // target.Child = expected; - // actual = target.Child; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Comment - ///// - //[TestMethod()] - //public void CommentTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Comment = expected; - // actual = target.Comment; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for CreateDate - ///// - //[TestMethod()] - //public void CreateDateTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // DateTime actual; - // actual = target.CreateDate; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Id - ///// - //[TestMethod()] - //public void IdTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // int actual; - // actual = target.Id; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Parent - ///// - //[TestMethod()] - //public void ParentTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // CMSNode expected = null; // TODO: Initialize to an appropriate value - // CMSNode actual; - // target.Parent = expected; - // actual = target.Parent; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for RelType - ///// - //[TestMethod()] - //public void RelTypeTest() - //{ - // int Id = 0; // TODO: Initialize to an appropriate value - // Relation target = new Relation(Id); // TODO: Initialize to an appropriate value - // RelationType expected = null; // TODO: Initialize to an appropriate value - // RelationType actual; - // target.RelType = expected; - // actual = target.RelType; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/StyleSheetTest.cs b/test/umbraco.Test/StyleSheetTest.cs deleted file mode 100644 index 1978b7799b..0000000000 --- a/test/umbraco.Test/StyleSheetTest.cs +++ /dev/null @@ -1,302 +0,0 @@ -using umbraco.cms.businesslogic.web; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for StyleSheetTest and is intended - ///to contain all StyleSheetTest Unit Tests - /// - [TestClass()] - public class StyleSheetTest - { - - /// - ///A test for MakeNew - /// - [TestMethod()] - public void StyleSheet_Make_New() - { - - var s = StyleSheet.MakeNew(m_User, Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N") + ".css", Guid.NewGuid().ToString("N")); - Assert.IsTrue(s.Id > 0); - Assert.IsInstanceOfType(s, typeof(StyleSheet)); - - //now remove it - s.delete(); - Assert.IsFalse(StyleSheet.IsNode(s.Id)); - - } - - [TestMethod()] - public void StyleSheet_Make_New_AddProperty() - { - - var s = StyleSheet.MakeNew(m_User, Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N") + ".css", Guid.NewGuid().ToString("N")); - Assert.IsTrue(s.Id > 0); - Assert.IsInstanceOfType(s, typeof(StyleSheet)); - - //add property - var p = s.AddProperty(Guid.NewGuid().ToString("N"), m_User); - Assert.IsTrue(p.Id > 0); - Assert.IsInstanceOfType(p, typeof(StylesheetProperty)); - - //now remove it - s.delete(); - Assert.IsFalse(StyleSheet.IsNode(s.Id)); - - //make sure the property is gone too - Assert.IsFalse(StylesheetProperty.IsNode(p.Id)); - - } - - private User m_User = new User(0); - - #region Tests to write - ///// - /////A test for StyleSheet Constructor - ///// - //[TestMethod()] - //public void StyleSheetConstructorTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // bool setupStyleProperties = false; // TODO: Initialize to an appropriate value - // bool loadContentFromFile = false; // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id, setupStyleProperties, loadContentFromFile); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for StyleSheet Constructor - ///// - //[TestMethod()] - //public void StyleSheetConstructorTest1() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for StyleSheet Constructor - ///// - //[TestMethod()] - //public void StyleSheetConstructorTest2() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for AddProperty - ///// - //[TestMethod()] - //public void AddPropertyTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // string Alias = string.Empty; // TODO: Initialize to an appropriate value - // User u = null; // TODO: Initialize to an appropriate value - // StylesheetProperty expected = null; // TODO: Initialize to an appropriate value - // StylesheetProperty actual; - // actual = target.AddProperty(Alias, u); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // StyleSheet[] expected = null; // TODO: Initialize to an appropriate value - // StyleSheet[] actual; - // actual = StyleSheet.GetAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetByName - ///// - //[TestMethod()] - //public void GetByNameTest() - //{ - // string name = string.Empty; // TODO: Initialize to an appropriate value - // StyleSheet expected = null; // TODO: Initialize to an appropriate value - // StyleSheet actual; - // actual = StyleSheet.GetByName(name); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetStyleSheet - ///// - //[TestMethod()] - //public void GetStyleSheetTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // bool setupStyleProperties = false; // TODO: Initialize to an appropriate value - // bool loadContentFromFile = false; // TODO: Initialize to an appropriate value - // StyleSheet expected = null; // TODO: Initialize to an appropriate value - // StyleSheet actual; - // actual = StyleSheet.GetStyleSheet(id, setupStyleProperties, loadContentFromFile); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Import - ///// - //[TestMethod()] - //public void ImportTest() - //{ - // XmlNode n = null; // TODO: Initialize to an appropriate value - // User u = null; // TODO: Initialize to an appropriate value - // StyleSheet expected = null; // TODO: Initialize to an appropriate value - // StyleSheet actual; - // actual = StyleSheet.Import(n, u); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for ToXml - ///// - //[TestMethod()] - //public void ToXmlTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // XmlDocument xd = null; // TODO: Initialize to an appropriate value - // XmlNode expected = null; // TODO: Initialize to an appropriate value - // XmlNode actual; - // actual = target.ToXml(xd); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for delete - ///// - //[TestMethod()] - //public void deleteTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // target.delete(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for saveCssToFile - ///// - //[TestMethod()] - //public void saveCssToFileTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // target.saveCssToFile(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Content - ///// - //[TestMethod()] - //public void ContentTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Content = expected; - // actual = target.Content; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Filename - ///// - //[TestMethod()] - //public void FilenameTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Filename = expected; - // actual = target.Filename; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Properties - ///// - //[TestMethod()] - //public void PropertiesTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // StyleSheet target = new StyleSheet(id); // TODO: Initialize to an appropriate value - // StylesheetProperty[] actual; - // actual = target.Properties; - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/TagTest.cs b/test/umbraco.Test/TagTest.cs deleted file mode 100644 index af9d85dd1c..0000000000 --- a/test/umbraco.Test/TagTest.cs +++ /dev/null @@ -1,368 +0,0 @@ -using umbraco.cms.businesslogic.Tags; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.cms.businesslogic.web; -using System.Linq; -using umbraco.BusinessLogic; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for TagTest and is intended - ///to contain all TagTest Unit Tests - /// - [TestClass()] - public class TagTest - { - - /// - /// Create a new tag and delete it - /// - [TestMethod()] - public void Tag_Make_New() - { - var t = Tag.AddTag(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N")); - Assert.IsTrue(t > 0); //id should be greater than zero - Assert.AreEqual(1, Tag.GetTags().Where(x => x.Id == t).Count()); - - Tag.RemoveTag(t); - //make sure it's gone - Assert.AreEqual(0, Tag.GetTags().Where(x => x.Id == t).Count()); - - } - - - /// - /// Creates a new tag and a new document, assigns the tag to the document and deletes the document - /// - [TestMethod()] - public void Tag_Make_New_Assign_Node_Delete_Node() - { - - var t = Tag.AddTag(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N")); - Assert.IsTrue(t > 0); //id should be greater than zero - Assert.AreEqual(1, Tag.GetTags().Where(x => x.Id == t).Count()); - - var dt = DocumentType.GetAllAsList().First(); - var doc = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - - Tag.AssociateTagToNode(doc.Id, t); - //make sure it's associated - Assert.AreEqual(1, Tag.GetTags(doc.Id).Count()); - - //delete the doc - doc.delete(true); - - //make sure it's not related any more - Assert.AreEqual(0, Tag.GetTags(doc.Id).Count()); - - Tag.RemoveTag(t); - //make sure it's gone - Assert.AreEqual(0, Tag.GetTags().Where(x => x.Id == t).Count()); - - } - - /// - /// Test the AddTagsToNode method and deletes it - /// - [TestMethod()] - public void Tag_Add_Tags_To_Node() - { - var dt = DocumentType.GetAllAsList().First(); - var doc = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - - var grp = Guid.NewGuid().ToString("N"); - Tag.AddTagsToNode(doc.Id, string.Format("{0},{1}", Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N")), grp); - - var tags = Tag.GetTags(doc.Id); - //make sure they are there by document - Assert.AreEqual(2, tags.Count()); - - //make sure they are there by group - Assert.AreEqual(2, Tag.GetTags(grp).Count()); - - //make sure they are there by both group and node - Assert.AreEqual(2, Tag.GetTags(doc.Id, grp).Count()); - - doc.delete(true); - - //make sure associations are gone - Assert.AreEqual(0, Tag.GetTags(doc.Id).Count()); - - //delete the tags - foreach (var t in tags) - { - Tag.RemoveTag(t.Id); - Assert.AreEqual(0, Tag.GetTags().Where(x => x.Id == t.Id).Count()); - } - } - - private User m_User = new User(0); - - #region Tests to write - - ///// - /////A test for Tag Constructor - ///// - //[TestMethod()] - //public void TagConstructorTest() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // string tag = string.Empty; // TODO: Initialize to an appropriate value - // string group = string.Empty; // TODO: Initialize to an appropriate value - // int nodeCount = 0; // TODO: Initialize to an appropriate value - // Tag target = new Tag(id, tag, group, nodeCount); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Tag Constructor - ///// - //[TestMethod()] - //public void TagConstructorTest1() - //{ - // Tag target = new Tag(); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - - - ///// - /////A test for AddTagsToNode - ///// - //[TestMethod()] - //public void AddTagsToNodeTest() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // string tags = string.Empty; // TODO: Initialize to an appropriate value - // string group = string.Empty; // TODO: Initialize to an appropriate value - // Tag.AddTagsToNode(nodeId, tags, group); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for AssociateTagToNode - ///// - //[TestMethod()] - //public void AssociateTagToNodeTest() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // int tagId = 0; // TODO: Initialize to an appropriate value - // Tag.AssociateTagToNode(nodeId, tagId); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for GetDocumentsWithTags - ///// - //[TestMethod()] - //public void GetDocumentsWithTagsTest() - //{ - // string tags = string.Empty; // TODO: Initialize to an appropriate value - // IEnumerable expected = null; // TODO: Initialize to an appropriate value - // IEnumerable actual; - // actual = Tag.GetDocumentsWithTags(tags); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetNodesWithTags - ///// - //[TestMethod()] - //public void GetNodesWithTagsTest() - //{ - // string tags = string.Empty; // TODO: Initialize to an appropriate value - // IEnumerable expected = null; // TODO: Initialize to an appropriate value - // IEnumerable actual; - // actual = Tag.GetNodesWithTags(tags); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetTagId - ///// - //[TestMethod()] - //public void GetTagIdTest() - //{ - // string tag = string.Empty; // TODO: Initialize to an appropriate value - // string group = string.Empty; // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // actual = Tag.GetTagId(tag, group); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetTags - ///// - //[TestMethod()] - //public void GetTagsTest() - //{ - // string group = string.Empty; // TODO: Initialize to an appropriate value - // IEnumerable expected = null; // TODO: Initialize to an appropriate value - // IEnumerable actual; - // actual = Tag.GetTags(group); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetTags - ///// - //[TestMethod()] - //public void GetTagsTest1() - //{ - // IEnumerable expected = null; // TODO: Initialize to an appropriate value - // IEnumerable actual; - // actual = Tag.GetTags(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetTags - ///// - //[TestMethod()] - //public void GetTagsTest2() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // IEnumerable expected = null; // TODO: Initialize to an appropriate value - // IEnumerable actual; - // actual = Tag.GetTags(nodeId); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetTags - ///// - //[TestMethod()] - //public void GetTagsTest3() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // string group = string.Empty; // TODO: Initialize to an appropriate value - // IEnumerable expected = null; // TODO: Initialize to an appropriate value - // IEnumerable actual; - // actual = Tag.GetTags(nodeId, group); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for RemoveTagFromNode - ///// - //[TestMethod()] - //public void RemoveTagFromNodeTest() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // string tag = string.Empty; // TODO: Initialize to an appropriate value - // string group = string.Empty; // TODO: Initialize to an appropriate value - // Tag.RemoveTagFromNode(nodeId, tag, group); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for RemoveTagsFromNode - ///// - //[TestMethod()] - //public void RemoveTagsFromNodeTest() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // string group = string.Empty; // TODO: Initialize to an appropriate value - // Tag.RemoveTagsFromNode(nodeId, group); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for RemoveTagsFromNode - ///// - //[TestMethod()] - //public void RemoveTagsFromNodeTest1() - //{ - // int nodeId = 0; // TODO: Initialize to an appropriate value - // Tag.RemoveTagsFromNode(nodeId); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Group - ///// - //[TestMethod()] - //public void GroupTest() - //{ - // Tag target = new Tag(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Group = expected; - // actual = target.Group; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Id - ///// - //[TestMethod()] - //public void IdTest() - //{ - // Tag target = new Tag(); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.Id = expected; - // actual = target.Id; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for TagCaption - ///// - //[TestMethod()] - //public void TagCaptionTest() - //{ - // Tag target = new Tag(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.TagCaption = expected; - // actual = target.TagCaption; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/TaskTest.cs b/test/umbraco.Test/TaskTest.cs deleted file mode 100644 index aff0c46fa3..0000000000 --- a/test/umbraco.Test/TaskTest.cs +++ /dev/null @@ -1,312 +0,0 @@ -using umbraco.cms.businesslogic.task; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using System.Linq; -using umbraco.cms.businesslogic.web; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for TaskTest and is intended - ///to contain all TaskTest Unit Tests - /// - [TestClass()] - public class TaskTest - { - - - /// - /// Test the constructor to throw an exception when the object is not found by id - /// - [TestMethod()] - [ExpectedException(typeof(ArgumentException))] - public void Task_Not_Found_Constructor() - { - Task u = new Task(-1111); - } - - /// - /// Create a new task and then close it (then deletes it) - /// - [TestMethod()] - public void Task_Make_New_And_Close() - { - //create the task - Task t = new Task(); - t.Comment = Guid.NewGuid().ToString("N"); - t.Node = Document.GetRootDocuments().First(); - t.ParentUser = m_User; - t.User = m_User; - t.Type = TaskType.GetAll().First(); - t.Save(); - - Assert.IsTrue(t.Id > 0); - - t.Closed = true; - t.Save(); - Assert.IsTrue(t.Closed); - - //re-get the task and make sure the props have been persisted to the db - var reGet = new Task(t.Id); - Assert.IsTrue(reGet.Closed); - - reGet.Delete(); - //re-get the task and make sure it is gone - var isFound = true; - try - { - var gone = new Task(t.Id); - } - catch (ArgumentException) - { - isFound = false; - } - Assert.IsFalse(isFound); - - } - - [TestMethod()] - public void Task_Assign_To_New_Node_Delete_Node_And_Ensure_Tasks_Removed() - { - //create a new document in the root - var dt = DocumentType.GetAllAsList().First(); - Document d = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - - //create a new task assigned to the new document - Task t = new Task(); - t.Comment = Guid.NewGuid().ToString("N"); - t.Node = d; - t.ParentUser = m_User; - t.User = m_User; - t.Type = TaskType.GetAll().First(); - t.Save(); - - //delete the document permanently - d.delete(true); - - //ensure the task is gone - var isFound = true; - try - { - var gone = new Task(t.Id); - } - catch (ArgumentException) - { - isFound = false; - } - Assert.IsFalse(isFound); - - //ensure it's gone - Assert.IsFalse(Document.IsNode(d.Id)); - } - - private User m_User = new User(0); - - #region Tests to write - - ///// - /////A test for Task Constructor - ///// - //[TestMethod()] - //public void TaskConstructorTest1() - //{ - // Task target = new Task(); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for GetOwnedTasks - ///// - //[TestMethod()] - //public void GetOwnedTasksTest() - //{ - // User User = null; // TODO: Initialize to an appropriate value - // bool IncludeClosed = false; // TODO: Initialize to an appropriate value - // Tasks expected = null; // TODO: Initialize to an appropriate value - // Tasks actual; - // actual = Task.GetOwnedTasks(User, IncludeClosed); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetTasks - ///// - //[TestMethod()] - //public void GetTasksTest() - //{ - // User User = null; // TODO: Initialize to an appropriate value - // bool IncludeClosed = false; // TODO: Initialize to an appropriate value - // Tasks expected = null; // TODO: Initialize to an appropriate value - // Tasks actual; - // actual = Task.GetTasks(User, IncludeClosed); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Closed - ///// - //[TestMethod()] - //public void ClosedTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // bool expected = false; // TODO: Initialize to an appropriate value - // bool actual; - // target.Closed = expected; - // actual = target.Closed; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Comment - ///// - //[TestMethod()] - //public void CommentTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Comment = expected; - // actual = target.Comment; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Date - ///// - //[TestMethod()] - //public void DateTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // DateTime expected = new DateTime(); // TODO: Initialize to an appropriate value - // DateTime actual; - // target.Date = expected; - // actual = target.Date; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Id - ///// - //[TestMethod()] - //public void IdTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.Id = expected; - // actual = target.Id; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Node - ///// - //[TestMethod()] - //public void NodeTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // CMSNode expected = null; // TODO: Initialize to an appropriate value - // CMSNode actual; - // target.Node = expected; - // actual = target.Node; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for ParentUser - ///// - //[TestMethod()] - //public void ParentUserTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // User expected = null; // TODO: Initialize to an appropriate value - // User actual; - // target.ParentUser = expected; - // actual = target.ParentUser; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Type - ///// - //[TestMethod()] - //public void TypeTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // TaskType expected = null; // TODO: Initialize to an appropriate value - // TaskType actual; - // target.Type = expected; - // actual = target.Type; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for User - ///// - //[TestMethod()] - //public void UserTest() - //{ - // Task target = new Task(); // TODO: Initialize to an appropriate value - // User expected = null; // TODO: Initialize to an appropriate value - // User actual; - // target.User = expected; - // actual = target.User; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/TaskTypeTest.cs b/test/umbraco.Test/TaskTypeTest.cs deleted file mode 100644 index 645d4f20fe..0000000000 --- a/test/umbraco.Test/TaskTypeTest.cs +++ /dev/null @@ -1,231 +0,0 @@ -using umbraco.cms.businesslogic.task; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using umbraco.cms.businesslogic.web; -using System.Linq; -using umbraco.DataLayer; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for TaskTypeTest and is intended - ///to contain all TaskTypeTest Unit Tests - /// - [TestClass()] - public class TaskTypeTest - { - - /// - /// Test the constructor to throw an exception when the object is not found by id - /// - [TestMethod()] - [ExpectedException(typeof(ArgumentException))] - public void TaskType_Not_Found_Constructor1() - { - TaskType u = new TaskType(-1111); - } - - /// - /// Test the constructor to throw an exception when the object is not found by id - /// - [TestMethod()] - [ExpectedException(typeof(ArgumentException))] - public void TaskType_Not_Found_Constructor2() - { - TaskType u = new TaskType(Guid.NewGuid().ToString("N")); - } - - /// - /// Creates a new task type, creates some tasks with it, then deletes the type. ensure that all tasks associated are removed. - /// - [TestMethod()] - public void TaskType_Make_New_Assign_Tasks_And_Remove() - { - TaskType tt = new TaskType(); - tt.Alias = Guid.NewGuid().ToString("N"); - tt.Save(); - Assert.IsTrue(tt.Id > 0); - - Task t = new Task(); - t.Comment = Guid.NewGuid().ToString("N"); - t.Node = Document.GetRootDocuments().First(); - t.ParentUser = m_User; - t.User = m_User; - t.Type = TaskType.GetAll().First(); - t.Save(); - - //delete the task type - tt.Delete(); - - //ensure they're gone - Assert.AreEqual(0, Task.GetTasksByType(tt.Id).Count); - - //ensure the type is gone - Assert.AreEqual(0, TaskType.GetAll().Where(x => x.Id == tt.Id).Count()); - - } - - /// - /// Ensures that duplicate task type names are not allowed either by an update or an insert - /// - [TestMethod()] - public void TaskType_Make_Duplicate() - { - var alias = Guid.NewGuid().ToString("N"); - - var tt = new TaskType(); - tt.Alias = alias; - tt.Save(); - - //try to insert a duplicate - var tt2 = new TaskType(); - tt2.Alias = alias; - var hasException = false; - try - { - tt2.Save(); - } - catch (SqlHelperException) - { - hasException = true; - } - Assert.IsTrue(hasException); - - //try to update to a duplicate - var tt3 = new TaskType(); - tt3.Alias = Guid.NewGuid().ToString("N"); - tt3.Save(); - tt3.Alias = alias; - hasException = false; - try - { - tt3.Save(); - } - catch (SqlHelperException) - { - hasException = true; - } - Assert.IsTrue(hasException); - - //now remove the ones we've created - tt.Delete(); - tt3.Delete(); - - } - - private User m_User = new User(0); - - #region Tests to write - - - - ///// - /////A test for TaskType Constructor - ///// - //[TestMethod()] - //public void TaskTypeConstructorTest1() - //{ - // string TypeAlias = string.Empty; // TODO: Initialize to an appropriate value - // TaskType target = new TaskType(TypeAlias); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for TaskType Constructor - ///// - //[TestMethod()] - //public void TaskTypeConstructorTest2() - //{ - // TaskType target = new TaskType(); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for GetAll - ///// - //[TestMethod()] - //public void GetAllTest() - //{ - // IEnumerable expected = null; // TODO: Initialize to an appropriate value - // IEnumerable actual; - // actual = TaskType.GetAll(); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Save - ///// - //[TestMethod()] - //public void SaveTest() - //{ - // TaskType target = new TaskType(); // TODO: Initialize to an appropriate value - // target.Save(); - // Assert.Inconclusive("A method that does not return a value cannot be verified."); - //} - - ///// - /////A test for Alias - ///// - //[TestMethod()] - //public void AliasTest() - //{ - // TaskType target = new TaskType(); // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // target.Alias = expected; - // actual = target.Alias; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for Id - ///// - //[TestMethod()] - //public void IdTest() - //{ - // TaskType target = new TaskType(); // TODO: Initialize to an appropriate value - // int expected = 0; // TODO: Initialize to an appropriate value - // int actual; - // target.Id = expected; - // actual = target.Id; - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - #endregion - - #region Additional test attributes - // - //You can use the following additional attributes as you write your tests: - // - //Use ClassInitialize to run code before running the first test in the class - //[ClassInitialize()] - //public static void MyClassInitialize(TestContext testContext) - //{ - //} - // - //Use ClassCleanup to run code after all tests in a class have run - //[ClassCleanup()] - //public static void MyClassCleanup() - //{ - //} - // - //Use TestInitialize to run code before running each test - //[TestInitialize()] - //public void MyTestInitialize() - //{ - //} - // - //Use TestCleanup to run code after each test has run - //[TestCleanup()] - //public void MyTestCleanup() - //{ - //} - // - #endregion - } -} diff --git a/test/umbraco.Test/TemplateTest.cs b/test/umbraco.Test/TemplateTest.cs deleted file mode 100644 index f43ff39baf..0000000000 --- a/test/umbraco.Test/TemplateTest.cs +++ /dev/null @@ -1,577 +0,0 @@ -using umbraco.cms.businesslogic.template; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using umbraco.BusinessLogic; -using umbraco.cms.businesslogic.web; - -namespace Umbraco.LegacyTests -{ - - - /// - ///This is a test class for TemplateTest and is intended - ///to contain all TemplateTest Unit Tests - /// - [TestClass()] - public class TemplateTest - { - - /// - /// create a new template - /// - [TestMethod()] - public void Template_Make_New() - { - - var t = Template.MakeNew(Guid.NewGuid().ToString("N"), m_User); - Assert.IsTrue(t.Id > 0); - Assert.IsInstanceOfType(t, typeof(Template)); - - t.delete(); - Assert.IsFalse(Template.IsNode(t.Id)); - - } - - /// - /// Make a new template as a master and a child template. Then try to delete the master template and ensure that it can't be deleted - /// without first changning the child template to have a null parent. - /// - [TestMethod()] - public void Template_Make_New_With_Master_And_Remove_Heirarchy_And_Delete() - { - var t = Template.MakeNew(Guid.NewGuid().ToString("N"), m_User); - var child = Template.MakeNew(Guid.NewGuid().ToString("N"), m_User, t); - Assert.IsTrue(t.Id > 0); - Assert.IsInstanceOfType(t, typeof(Template)); - - //verify heirarchy - Assert.IsTrue(child.HasMasterTemplate); - Assert.IsTrue(t.HasChildren); - - //make sure we can't delete it - var hasException = false; - try - { - t.delete(); - } - catch (InvalidOperationException) - { - hasException = true; - } - Assert.IsTrue(hasException); - - //System.Diagnostics.Debugger.Launch(); - - //now we need to update the heirarchy... - - //though, this call will make changes in the database, it won't change our child object as our data layer doesn't have object - //persistenece. - t.RemoveAllReferences(); - //so we'll manually update our master page reference as well (0 = null) - child.MasterTemplate = 0; - - //verify heirarchy - Assert.IsFalse(child.HasMasterTemplate); - Assert.IsFalse(t.HasChildren); - - //now delete it, should work now - t.delete(); - Assert.IsFalse(Template.IsNode(t.Id)); - - //remove the child - child.delete(); - Assert.IsFalse(Template.IsNode(child.Id)); - - } - - /// - /// Creates a new document type, new template, asssign the template to the document type, create a new document using the new template - /// then delete the template. This should throw an exception. We will not allow deleting a template that is currently in use - /// - [TestMethod()] - public void Template_Assign_To_Document_And_Delete() - { - //create the doc type, template and document - var dt = DocumentType.MakeNew(m_User, Guid.NewGuid().ToString("N")); - var t = Template.MakeNew(Guid.NewGuid().ToString("N"), m_User); - - //set the allowed templates - dt.allowedTemplates = new Template[] { t }; - //now set the default - dt.DefaultTemplate = t.Id; - - //create the document (this should have the default template set) - var doc = Document.MakeNew(Guid.NewGuid().ToString("N"), dt, m_User, -1); - - Assert.AreEqual(t.Id, doc.Template); - - //now delete, this should throw the exception - // changed by NH as the API will cleanup instead! -/* var hasException = false; - try - { - t.delete(); - } - catch (InvalidOperationException) - { - hasException = true; - } - Assert.IsTrue(hasException); - */ - //ok, now that we've proved it can't be removed, we'll remove the data in order - doc.delete(true); - Assert.IsFalse(Document.IsNode(doc.Id)); - - dt.delete(); - Assert.IsFalse(DocumentType.IsNode(dt.Id)); - - t.delete(); - Assert.IsFalse(Template.IsNode(t.Id)); - } - - private User m_User = new User(0); - - #region Tests to write - ///// - /////A test for Template Constructor - ///// - //[TestMethod()] - //public void TemplateConstructorTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Template target = new Template(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for Template Constructor - ///// - //[TestMethod()] - //public void TemplateConstructorTest1() - //{ - // int id = 0; // TODO: Initialize to an appropriate value - // Template target = new Template(id); - // Assert.Inconclusive("TODO: Implement code to verify target"); - //} - - ///// - /////A test for ConvertToMasterPageSyntax - ///// - //[TestMethod()] - //public void ConvertToMasterPageSyntaxTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Template target = new Template(id); // TODO: Initialize to an appropriate value - // string templateDesign = string.Empty; // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // actual = target.ConvertToMasterPageSyntax(templateDesign); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for EnsureMasterPageSyntax - ///// - //[TestMethod()] - //public void EnsureMasterPageSyntaxTest() - //{ - // Guid id = new Guid(); // TODO: Initialize to an appropriate value - // Template target = new Template(id); // TODO: Initialize to an appropriate value - // string masterPageContent = string.Empty; // TODO: Initialize to an appropriate value - // string expected = string.Empty; // TODO: Initialize to an appropriate value - // string actual; - // actual = target.EnsureMasterPageSyntax(masterPageContent); - // Assert.AreEqual(expected, actual); - // Assert.Inconclusive("Verify the correctness of this test method."); - //} - - ///// - /////A test for GetAllAsList - ///// - //[TestMethod()] - //public void GetAllAsListTest() - //{ - // List