diff --git a/umbraco.Test/Dictionary_DictionaryItemTest.cs b/umbraco.Test/DictionaryTest.cs similarity index 91% rename from umbraco.Test/Dictionary_DictionaryItemTest.cs rename to umbraco.Test/DictionaryTest.cs index 0e813fde22..615a8fd2cd 100644 --- a/umbraco.Test/Dictionary_DictionaryItemTest.cs +++ b/umbraco.Test/DictionaryTest.cs @@ -17,6 +17,18 @@ namespace umbraco.Test [TestClass()] public class DictionaryTest { + [TestMethod()] + public void Dictionary_Get_Top_Level_Items() + { + var items = Dictionary.getTopMostItems; + + var d = CreateNew(); + + Assert.AreEqual(items.Count() + 1, Dictionary.getTopMostItems.Count()); + + DeleteItem(d); + } + /// /// Creates a new dictionary entry, adds values for all languages assigned, then deletes the /// entry and ensure that all other data is gone too. @@ -232,6 +244,34 @@ namespace umbraco.Test DeleteItem(d); } + /// + /// Tries to create a duplicate key and ensures it's not possible. + /// + [TestMethod()] + public void Dictionary_Attempt_Duplicate_Key() + { + var key = "Test" + Guid.NewGuid().ToString("N"); + var d1Id = Dictionary.DictionaryItem.addKey(key, ""); + Assert.IsTrue(d1Id > 0); + var d1 = new Dictionary.DictionaryItem(d1Id); + Assert.IsInstanceOfType(d1, typeof(Dictionary.DictionaryItem)); + + var alreadyExists = false; + try + { + var d2Id = Dictionary.DictionaryItem.addKey(key, ""); + Assert.IsTrue(d2Id > 0); + var d2 = new Dictionary.DictionaryItem(d2Id); + } + catch (ArgumentException) + { + alreadyExists = true; + } + Assert.IsTrue(alreadyExists); + + DeleteItem(d1); + } + #region Private methods private Dictionary.DictionaryItem CreateNew() { diff --git a/umbraco.Test/DocumentTest.cs b/umbraco.Test/DocumentTest.cs index 62eeefdbb0..e922c85355 100644 --- a/umbraco.Test/DocumentTest.cs +++ b/umbraco.Test/DocumentTest.cs @@ -168,11 +168,11 @@ namespace umbraco.Test target.Copy(parentId, m_User, RelateToOrignal); - Assert.AreEqual(childrenIds.Count() + 1, GetChildNodesOfParent(target).Count()); - - Document parent = new Document(parentId); + var parentChildNodes = GetChildNodesOfParent(target); + Assert.AreEqual(childrenIds.Count() + 1, parentChildNodes.Count()); + //get the children difference which should be the new node - var diff = parent.Children.ToList().Select(x => x.Id).Except(childrenIds); + var diff = parentChildNodes.Select(x => x.Id).Except(childrenIds); Assert.AreEqual(1, diff.Count()); diff --git a/umbraco.Test/MediaTypeTest.cs b/umbraco.Test/MediaTypeTest.cs index b1cd590b32..0c70936e1e 100644 --- a/umbraco.Test/MediaTypeTest.cs +++ b/umbraco.Test/MediaTypeTest.cs @@ -21,7 +21,7 @@ namespace umbraco.Test ///A test for GetAll /// [TestMethod()] - public void MediaType_GetAllTest() + public void MediaType_Get_All() { //check with sql that it's the correct number of children var ids = new List(); @@ -51,7 +51,7 @@ namespace umbraco.Test /// moved to the recycle bin. /// [TestMethod()] - public void MediaType_DeleteDocTypeWithContentAndChildrenOfDifferentDocTypes() + public void MediaType_Delete_Media_Type_With_Media_And_Children_Of_Diff_Media_Types() { //System.Diagnostics.Debugger.Break(); @@ -97,7 +97,7 @@ namespace umbraco.Test /// 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_AddPropertiesToTabThenDeleteItTest() + public void MediaType_Add_Properties_To_Tab_Then_Delete_It_Test() { //System.Diagnostics.Debugger.Break(); diff --git a/umbraco.Test/MemberTest.cs b/umbraco.Test/MemberTest.cs new file mode 100644 index 0000000000..e315f7a0e0 --- /dev/null +++ b/umbraco.Test/MemberTest.cs @@ -0,0 +1,627 @@ +using umbraco.cms.businesslogic.member; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections; +using umbraco.BusinessLogic; +using System.Xml; +using System.Linq; + +namespace umbraco.Test +{ + + + /// + ///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 + 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/umbraco.Test/MemberTypeTest.cs b/umbraco.Test/MemberTypeTest.cs new file mode 100644 index 0000000000..48dea9261b --- /dev/null +++ b/umbraco.Test/MemberTypeTest.cs @@ -0,0 +1,228 @@ +using umbraco.cms.businesslogic.member; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using umbraco.BusinessLogic; +using umbraco.cms.businesslogic.propertytype; +using System.Xml; + +namespace umbraco.Test +{ + + + /// + ///This is a test class for MemberTypeTest and is intended + ///to contain all MemberTypeTest Unit Tests + /// + [TestClass()] + public class MemberTypeTest + { + + /// + ///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/umbraco.Test/umbraco.Test.csproj b/umbraco.Test/umbraco.Test.csproj index e6ae688619..f08044fe08 100644 --- a/umbraco.Test/umbraco.Test.csproj +++ b/umbraco.Test/umbraco.Test.csproj @@ -136,12 +136,14 @@ - + + + diff --git a/umbraco/cms/businesslogic/CMSNode.cs b/umbraco/cms/businesslogic/CMSNode.cs index 8b856244f4..3b76bac19f 100644 --- a/umbraco/cms/businesslogic/CMSNode.cs +++ b/umbraco/cms/businesslogic/CMSNode.cs @@ -295,6 +295,11 @@ namespace umbraco.cms.businesslogic #endregion #region Constructors + + /// + /// Empty constructor that is not suported + /// ...why is it here? + /// public CMSNode() { throw new NotSupportedException(); @@ -310,7 +315,6 @@ namespace umbraco.cms.businesslogic setupNode(); } - /// /// Initializes a new instance of the class. /// @@ -320,10 +324,8 @@ namespace umbraco.cms.businesslogic { _id = id; - //TODO: add the following as noSetup currenlty doesn't actuall do anything!?? This can't happen until - //inheriting classes can override setupNode instead of using their own implementation (i.e. Document: setupDocument) - //if (!noSetup) - //setupNode(); + if (!noSetup) + setupNode(); } /// @@ -336,11 +338,20 @@ namespace umbraco.cms.businesslogic setupNode(); } - public CMSNode(IRecordsReader reader) + public CMSNode(Guid uniqueID, bool noSetup) + { + _id = SqlHelper.ExecuteScalar("SELECT id FROM umbracoNode WHERE uniqueID = @uniqueId", SqlHelper.CreateParameter("@uniqueId", uniqueID)); + + if (!noSetup) + setupNode(); + } + + protected internal CMSNode(IRecordsReader reader) { _id = reader.GetInt("id"); PopulateCMSNodeFromReader(reader); } + #endregion #region Public Methods diff --git a/umbraco/cms/businesslogic/Content.cs b/umbraco/cms/businesslogic/Content.cs index dbbe468360..3f5198472d 100644 --- a/umbraco/cms/businesslogic/Content.cs +++ b/umbraco/cms/businesslogic/Content.cs @@ -41,25 +41,16 @@ namespace umbraco.cms.businesslogic #endregion - #region Constructors - /// - /// - /// - /// + #region Constructors + public Content(int id) : base(id) { } - /// - /// - /// - /// - /// protected Content(int id, bool noSetup) : base(id, noSetup) { } - - /// - /// - /// - /// + protected Content(Guid id) : base(id) { } + + protected Content(Guid id, bool noSetup) : base(id, noSetup) { } + #endregion #region Static Methods @@ -505,6 +496,8 @@ namespace umbraco.cms.businesslogic createNewVersion(); } + + /// /// Method for creating a new version of the data associated to the Content. /// diff --git a/umbraco/cms/businesslogic/ContentType.cs b/umbraco/cms/businesslogic/ContentType.cs index 0dd19abcd1..7f054e5527 100644 --- a/umbraco/cms/businesslogic/ContentType.cs +++ b/umbraco/cms/businesslogic/ContentType.cs @@ -44,6 +44,8 @@ namespace umbraco.cms.businesslogic public ContentType(int id, bool noSetup) : base(id, noSetup) { } + public ContentType(Guid id, bool noSetup) : base(id, noSetup) { } + ///// ///// Initializes a new instance of the class. ///// diff --git a/umbraco/cms/businesslogic/cache/Cache.cs b/umbraco/cms/businesslogic/cache/Cache.cs index 886830cc12..66782ee783 100644 --- a/umbraco/cms/businesslogic/cache/Cache.cs +++ b/umbraco/cms/businesslogic/cache/Cache.cs @@ -1,16 +1,15 @@ using System; using System.Web.Caching; +using System.Web; namespace umbraco.cms.businesslogic.cache { /// - /// Summary description for Cache. + /// Used to easily store and retreive items from the cache. /// public class Cache { - public static readonly object m_Locker = new object(); - /// /// Clears everything in umbraco's runtime cache, which means that not only /// umbraco content is removed, but also other cache items from pages running in @@ -36,16 +35,9 @@ namespace umbraco.cms.businesslogic.cache public static void ClearCacheItem(string Key) { if (System.Web.HttpRuntime.Cache[Key] != null) - { - lock (m_Locker) - { - //check again - if (System.Web.HttpRuntime.Cache[Key] != null) - { - System.Web.HttpRuntime.Cache.Remove(Key); - System.Web.HttpContext.Current.Trace.Warn("Cache", "Item " + Key + " removed from cache"); - } - } + { + HttpRuntime.Cache.Remove(Key); + HttpContext.Current.Trace.Warn("Cache", "Item " + Key + " removed from cache"); } } @@ -67,14 +59,7 @@ namespace umbraco.cms.businesslogic.cache { if (cacheEnumerator.Key != null && c[cacheEnumerator.Key.ToString()] != null && c[cacheEnumerator.Key.ToString()].GetType() != null && c[cacheEnumerator.Key.ToString()].GetType().ToString() == TypeName) { - lock (m_Locker) - { - //check again - if (cacheEnumerator.Key != null && c[cacheEnumerator.Key.ToString()] != null && c[cacheEnumerator.Key.ToString()].GetType() != null && c[cacheEnumerator.Key.ToString()].GetType().ToString() == TypeName) - { - c.Remove(cacheEnumerator.Key.ToString()); - } - } + c.Remove(cacheEnumerator.Key.ToString()); } } } diff --git a/umbraco/cms/businesslogic/media/Media.cs b/umbraco/cms/businesslogic/media/Media.cs index 7fe9b1b846..3268790bf7 100644 --- a/umbraco/cms/businesslogic/media/Media.cs +++ b/umbraco/cms/businesslogic/media/Media.cs @@ -35,6 +35,7 @@ namespace umbraco.cms.businesslogic.media #endregion #region Constructors + /// /// Contructs a media object given the Id /// @@ -49,7 +50,8 @@ namespace umbraco.cms.businesslogic.media public Media(int id, bool noSetup) : base(id, noSetup) { } - public Media(bool optimizedMode, int id) : base(id, optimizedMode) { } + public Media(Guid id, bool noSetup) : base(id, noSetup) { } + #endregion #region Static Methods diff --git a/umbraco/cms/businesslogic/member/Member.cs b/umbraco/cms/businesslogic/member/Member.cs index 956fc28163..085b82620a 100644 --- a/umbraco/cms/businesslogic/member/Member.cs +++ b/umbraco/cms/businesslogic/member/Member.cs @@ -5,17 +5,14 @@ using System.Data; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Web; -using System.Web.Caching; using System.Xml; - using umbraco.cms.businesslogic.cache; - using umbraco.BusinessLogic; using umbraco.DataLayer; - using System.Web.Security; using System.Text; using System.Security.Cryptography; +using System.Linq; namespace umbraco.cms.businesslogic.member { @@ -29,70 +26,52 @@ namespace umbraco.cms.businesslogic.member /// public class Member : Content { + #region Constants and static members public static readonly string UmbracoMemberProviderName = "UmbracoMembershipProvider"; public static readonly string UmbracoRoleProviderName = "UmbracoRoleProvider"; public static readonly Guid _objectType = new Guid("39eb0f98-b348-42a1-8662-e7eb18487560"); - private static readonly System.Web.Caching.Cache _memberCache = HttpRuntime.Cache; - private static object memberCacheSyncLock = new object(); - private static readonly string memberLookupCacheKey = "memberLookupId_"; + + private static readonly object m_Locker = new object(); private static readonly string UmbracoMemberIdCookieKey = "umbracoMemberId"; private static readonly string UmbracoMemberGuidCookieKey = "umbracoMemberGuid"; - private static readonly string UmbracoMemberLoginCookieKey = "umbracoMemberLogin"; - private string _text; + private static readonly string UmbracoMemberLoginCookieKey = "umbracoMemberLogin"; + #endregion - private Hashtable _groups = null; + #region Private members + private string m_Text; + private string m_Email; + private string m_Password; + private string m_LoginName; + private Hashtable m_Groups = null; + #endregion + + #region Constructors /// /// Initializes a new instance of the Member class. /// /// Identifier - public Member(int id) - : base(id) - { - } + public Member(int id) : base(id) { } /// /// Initializes a new instance of the Member class. /// /// Identifier - public Member(Guid id) - : base(id) - { - } + public Member(Guid id) : base(id) { } /// /// Initializes a new instance of the Member class, with an option to only initialize /// the data used by the tree in the umbraco console. - /// - /// Performace /// /// Identifier /// - public Member(int id, bool noSetup) - : base(id, noSetup) - { - } + public Member(int id, bool noSetup) : base(id, noSetup) { } - /// - /// The name of the member - /// - 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; - } - set - { - _text = value; - base.Text = value; - } - } + public Member(Guid id, bool noSetup) : base(id, noSetup) { } + #endregion + + #region Static methods /// /// A list of all members in the current umbraco install /// @@ -109,105 +88,6 @@ namespace umbraco.cms.businesslogic.member } } - /// - /// The members password, used when logging in on the public website - /// - public string Password - { - get - { - return SqlHelper.ExecuteScalar( - "select Password from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); - } - set - { - // We need to use the provider for this in order for hashing, etc. support - // 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) - MemberShipHelper helper = new MemberShipHelper(); - ChangePassword(helper.EncodePassword(value, Membership.Provider.PasswordFormat)); - } - } - - /// - /// The loginname of the member, used when logging in - /// - public string LoginName - { - get - { - return SqlHelper.ExecuteScalar( - "select LoginName from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); - } - set - { - SqlHelper.ExecuteNonQuery( - "update cmsMember set LoginName = @loginName where nodeId = @id", - SqlHelper.CreateParameter("@loginName", value), - SqlHelper.CreateParameter("@id", Id)); - } - } - - /// - /// A list of groups the member are member of - /// - [Obsolete("Use System.Web.Security.Roles.GetRolesForUser()")] - public Hashtable Groups - { - get - { - if (_groups == null) - populateGroups(); - return _groups; - } - } - - /// - /// The members email - /// - public string Email - { - get - { - return SqlHelper.ExecuteScalar( - "select Email from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); - } - set - { - SqlHelper.ExecuteNonQuery( - "update cmsMember set Email = @email where nodeId = @id", - SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@email", value)); - } - } - - /// - /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility - /// - public override void Save() - { - SaveEventArgs e = new SaveEventArgs(); - FireBeforeSave(e); - - if (!e.Cancel) - { - // re-generate xml - 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! - savePreviewXml(generateXmlWithoutSaving(xd), Guid.NewGuid()); - } - - FireAfterSave(e); - } - } - /// /// Retrieves a list of members thats not start with a-z /// @@ -223,7 +103,7 @@ namespace umbraco.cms.businesslogic.member while (dr.Read()) { Member newMember = new Member(dr.GetInt("id"), true); - newMember._text = dr.GetString("text"); + newMember.m_Text = dr.GetString("text"); m.Add(new Member(newMember.Id)); } } @@ -259,7 +139,7 @@ namespace umbraco.cms.businesslogic.member while (dr.Read()) { Member newMember = new Member(dr.GetInt("id"), true); - newMember._text = dr.GetString("text"); + newMember.m_Text = dr.GetString("text"); m.Add(new Member(newMember.Id)); } } @@ -277,24 +157,7 @@ namespace umbraco.cms.businesslogic.member [Obsolete("Use System.Web.Security.Membership.CreateUser")] public static Member MakeNew(string Name, MemberType mbt, User u) { - return MakeNew(Name, "", mbt, u); - /* - Guid newId = Guid.NewGuid(); - MakeNew(-1, _objectType, u.Id, 1, Name, newId); - - Member tmp = new Member(newId); - - tmp.CreateContent(mbt); - // Create member specific data .. - SqlHelper.ExecuteNonQuery( - "insert into cmsMember (nodeId,Email,LoginName,Password) values (@id,'',@text,'')", - SqlHelper.CreateParameter("@id", tmp.Id), - SqlHelper.CreateParameter("@text", tmp.Text)); - - NewEventArgs e = new NewEventArgs(); - tmp.OnNew(e); - - return tmp;*/ + return MakeNew(Name, "", mbt, u); } /// @@ -315,11 +178,17 @@ namespace umbraco.cms.businesslogic.member throw new Exception(String.Format("Duplicate User name! A member with the user name {0} already exists", Name)); Guid newId = Guid.NewGuid(); - MakeNew(-1, _objectType, u.Id, 1, Name, newId); - Member tmp = new Member(newId); + //create the cms node first + CMSNode newNode = MakeNew(-1, _objectType, u.Id, 1, Name, newId); + //we need to create an empty member and set the underlying text property + Member 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,@text,'')", @@ -327,169 +196,15 @@ namespace umbraco.cms.businesslogic.member SqlHelper.CreateParameter("@text", tmp.Text), SqlHelper.CreateParameter("@email", Email)); + //read the whole object from the db + Member m = new Member(newId); + NewEventArgs e = new NewEventArgs(); - tmp.OnNew(e); + m.OnNew(e); - tmp.Save(); + m.Save(); - return tmp; - } - - /// - /// Generates the xmlrepresentation of a member - /// - /// - public override void XmlGenerate(XmlDocument xd) - { - SaveXmlDocument(generateXmlWithoutSaving(xd)); - } - - protected override XmlNode generateXmlWithoutSaving(XmlDocument xd) - { - XmlNode node = xd.CreateNode(XmlNodeType.Element, "node", ""); - XmlPopulate(xd, ref node, false); - node.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName)); - node.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email)); - return node; - } - - - /// - /// Xmlrepresentation of a member - /// - /// The xmldocument context - /// Recursive - should always be set to false - /// A the xmlrepresentation of the current member - public override XmlNode ToXml(XmlDocument xd, bool Deep) - { - XmlNode x = base.ToXml(xd, Deep); - if (x.Attributes["loginName"] == null) - { - x.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName)); - x.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email)); - } - return x; - } - - /// - /// Deltes the current member - /// - [Obsolete("Use System.Web.Security.Membership.DeleteUser")] - public new void delete() - { - DeleteEventArgs e = new DeleteEventArgs(); - FireBeforeDelete(e); - - if (!e.Cancel) - { - // Remove from cache (if exists) - umbraco.cms.businesslogic.cache.Cache.ClearCacheItem(memberLookupCacheKey + Id); - - // delete memeberspecific data! - SqlHelper.ExecuteNonQuery("Delete from cmsMember where nodeId = @id", - SqlHelper.CreateParameter("@id", Id)); - - // delete all relations to groups - foreach (int groupId in this.Groups.Keys) - { - RemoveGroup(groupId); - } - - // Delete all content and cmsnode specific data! - base.delete(); - - FireAfterDelete(e); - } - } - - /// - /// Deletes all members of the membertype specified - /// - /// Used when a membertype is deleted - /// - /// Use with care - /// - /// The membertype which are being deleted - public static void DeleteFromType(MemberType dt) - { - var objs = getContentOfContentType(dt); - foreach (Content c in objs) - { - // due to recursive structure document might already been deleted.. - if (IsNode(c.UniqueId)) - { - Member tmp = new Member(c.UniqueId); - tmp.delete(); - } - } - } - - public void ChangePassword(string newPassword) - { - SqlHelper.ExecuteNonQuery( - "update cmsMember set Password = @password where nodeId = @id", - SqlHelper.CreateParameter("@password", newPassword), - SqlHelper.CreateParameter("@id", Id)); - } - - /// - /// Adds the member to group with the specified id - /// - /// The id of the group which the member is being added to - [MethodImpl(MethodImplOptions.Synchronized)] - [Obsolete("Use System.Web.Security.Roles.AddUserToRole")] - public void AddGroup(int GroupId) - { - AddGroupEventArgs e = new AddGroupEventArgs(); - FireBeforeAddGroup(e); - - if (!e.Cancel) - { - IParameter[] parameters = new IParameter[] { SqlHelper.CreateParameter("@id", Id), - SqlHelper.CreateParameter("@groupId", GroupId) }; - bool exists = SqlHelper.ExecuteScalar("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId", - parameters) > 0; - if (!exists) - SqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)", - parameters); - populateGroups(); - - FireAfterAddGroup(e); - } - } - - /// - /// Removes the member from the MemberGroup specified - /// - /// The MemberGroup from which the Member is removed - [Obsolete("Use System.Web.Security.Roles.RemoveUserFromRole")] - public void RemoveGroup(int GroupId) - { - RemoveGroupEventArgs e = new RemoveGroupEventArgs(); - FireBeforeRemoveGroup(e); - - if (!e.Cancel) - { - SqlHelper.ExecuteNonQuery( - "delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId", - SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId)); - populateGroups(); - FireAfterRemoveGroup(e); - } - } - - private void populateGroups() - { - Hashtable temp = new Hashtable(); - using (IRecordsReader dr = SqlHelper.ExecuteReader( - "select memberGroup from cmsMember2MemberGroup where member = @id", - SqlHelper.CreateParameter("@id", Id))) - { - while (dr.Read()) - temp.Add(dr.GetInt("memberGroup"), - new MemberGroup(dr.GetInt("memberGroup"))); - } - _groups = temp; + return m; } /// @@ -629,13 +344,336 @@ namespace umbraco.cms.businesslogic.member return count > 0; } - /* - public contentitem.ContentItem[] CreatedContent() { - return new contentitem.ContentItem[0]; + /// + /// Deletes all members of the membertype specified + /// + /// Used when a membertype is deleted + /// + /// Use with care + /// + /// The membertype which are being deleted + public static void DeleteFromType(MemberType dt) + { + var objs = getContentOfContentType(dt); + foreach (Content c in objs) + { + // due to recursive structure document might already been deleted.. + if (IsNode(c.UniqueId)) + { + Member tmp = new Member(c.UniqueId); + tmp.delete(); + } + } } - */ + #endregion + #region Public Properties + + /// + /// The name of the member + /// + public override string Text + { + get + { + if (string.IsNullOrEmpty(m_Text)) + { + m_Text = SqlHelper.ExecuteScalar( + "select text from umbracoNode where id = @id", + SqlHelper.CreateParameter("@id", Id)); + } + return m_Text; + } + set + { + m_Text = value; + base.Text = value; + } + } + + /// + /// The members password, used when logging in on the public website + /// + public string Password + { + get + { + if (string.IsNullOrEmpty(m_Password)) + { + m_Password = SqlHelper.ExecuteScalar( + "select Password from cmsMember where nodeId = @id", + SqlHelper.CreateParameter("@id", Id)); + } + return m_Password; + + } + set + { + // We need to use the provider for this in order for hashing, etc. support + // 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) + MemberShipHelper helper = new MemberShipHelper(); + ChangePassword(helper.EncodePassword(value, Membership.Provider.PasswordFormat)); + } + } + + /// + /// The loginname of the member, used when logging in + /// + public string LoginName + { + get + { + if (string.IsNullOrEmpty(m_LoginName)) + { + m_LoginName = SqlHelper.ExecuteScalar( + "select LoginName from cmsMember where nodeId = @id", + SqlHelper.CreateParameter("@id", Id)); + } + return m_LoginName; + } + set + { + SqlHelper.ExecuteNonQuery( + "update cmsMember set LoginName = @loginName where nodeId = @id", + SqlHelper.CreateParameter("@loginName", value), + SqlHelper.CreateParameter("@id", Id)); + m_LoginName = value; + } + } + + /// + /// A list of groups the member are member of + /// + [Obsolete("Use System.Web.Security.Roles.GetRolesForUser()")] + public Hashtable Groups + { + get + { + if (m_Groups == null) + populateGroups(); + return m_Groups; + } + } + + /// + /// The members email + /// + public string Email + { + get + { + return SqlHelper.ExecuteScalar( + "select Email from cmsMember where nodeId = @id", + SqlHelper.CreateParameter("@id", Id)); + } + set + { + SqlHelper.ExecuteNonQuery( + "update cmsMember set Email = @email where nodeId = @id", + SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@email", value)); + } + } + #endregion + + #region Public Methods + + protected override void setupNode() + { + base.setupNode(); + + using (IRecordsReader dr = SqlHelper.ExecuteReader( + @"SELECT Email, LoginName, Password FROM cmsMember WHERE nodeId=@nodeId", + SqlHelper.CreateParameter("@nodeId", this.Id))) + { + if (dr.Read()) + { + if (!dr.IsNull("Email")) + m_Email = dr.GetString("Email"); + m_LoginName = dr.GetString("LoginName"); + m_Password = dr.GetString("Password"); + } + else + { + throw new ArgumentException(string.Format("No Member exists with Id '{0}'", this.Id)); + } + } + } + + /// + /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility + /// + public override void Save() + { + SaveEventArgs e = new SaveEventArgs(); + FireBeforeSave(e); + + if (!e.Cancel) + { + // re-generate xml + 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! + savePreviewXml(generateXmlWithoutSaving(xd), Guid.NewGuid()); + } + + FireAfterSave(e); + } + } + + /// + /// Generates the xmlrepresentation of a member + /// + /// + public override void XmlGenerate(XmlDocument xd) + { + SaveXmlDocument(generateXmlWithoutSaving(xd)); + } + + /// + /// Xmlrepresentation of a member + /// + /// The xmldocument context + /// Recursive - should always be set to false + /// A the xmlrepresentation of the current member + public override XmlNode ToXml(XmlDocument xd, bool Deep) + { + XmlNode x = base.ToXml(xd, Deep); + if (x.Attributes["loginName"] == null) + { + x.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName)); + x.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email)); + } + return x; + } + + /// + /// Deltes the current member + /// + [Obsolete("Use System.Web.Security.Membership.DeleteUser")] + public override void delete() + { + DeleteEventArgs e = new DeleteEventArgs(); + FireBeforeDelete(e); + + if (!e.Cancel) + { + // Remove from cache (if exists) + Cache.ClearCacheItem(GetCacheKey(Id)); + + // delete all relations to groups + foreach (int groupId in this.Groups.Keys) + { + RemoveGroup(groupId); + } + + // delete memeberspecific data! + SqlHelper.ExecuteNonQuery("Delete from cmsMember where nodeId = @id", + SqlHelper.CreateParameter("@id", Id)); + + // Delete all content and cmsnode specific data! + base.delete(); + + FireAfterDelete(e); + } + } + + 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 + m_Password = newPassword; + } + + /// + /// Adds the member to group with the specified id + /// + /// The id of the group which the member is being added to + [MethodImpl(MethodImplOptions.Synchronized)] + [Obsolete("Use System.Web.Security.Roles.AddUserToRole")] + public void AddGroup(int GroupId) + { + AddGroupEventArgs e = new AddGroupEventArgs(); + FireBeforeAddGroup(e); + + if (!e.Cancel) + { + IParameter[] parameters = new IParameter[] { SqlHelper.CreateParameter("@id", Id), + SqlHelper.CreateParameter("@groupId", GroupId) }; + bool exists = SqlHelper.ExecuteScalar("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId", + parameters) > 0; + if (!exists) + SqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)", + parameters); + populateGroups(); + + FireAfterAddGroup(e); + } + } + + /// + /// Removes the member from the MemberGroup specified + /// + /// The MemberGroup from which the Member is removed + [Obsolete("Use System.Web.Security.Roles.RemoveUserFromRole")] + public void RemoveGroup(int GroupId) + { + RemoveGroupEventArgs e = new RemoveGroupEventArgs(); + FireBeforeRemoveGroup(e); + + if (!e.Cancel) + { + SqlHelper.ExecuteNonQuery( + "delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId", + SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId)); + populateGroups(); + FireAfterRemoveGroup(e); + } + } + #endregion + + #region Protected methods + protected override XmlNode generateXmlWithoutSaving(XmlDocument xd) + { + XmlNode node = xd.CreateNode(XmlNodeType.Element, "node", ""); + XmlPopulate(xd, ref node, false); + node.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName)); + node.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email)); + return node; + } + + #endregion + + #region Private methods + private void populateGroups() + { + Hashtable temp = new Hashtable(); + using (IRecordsReader dr = SqlHelper.ExecuteReader( + "select memberGroup from cmsMember2MemberGroup where member = @id", + SqlHelper.CreateParameter("@id", Id))) + { + while (dr.Read()) + temp.Add(dr.GetInt("memberGroup"), + new MemberGroup(dr.GetInt("memberGroup"))); + } + m_Groups = temp; + } + + private static string GetCacheKey(int id) + { + return string.Format("MemberCacheItem_{0}", id); + } + + #endregion #region MemberHandle functions @@ -659,13 +697,6 @@ namespace umbraco.cms.businesslogic.member if (!e.Cancel) { - - Hashtable umbracoMembers = CachedMembers(); - - // Check if member already exists - if (umbracoMembers[m.Id] == null) - umbracoMembers.Add(m.Id, m); - removeCookie("umbracoMemberId"); // Add cookie with member-id, guid and loginname @@ -673,12 +704,18 @@ namespace umbraco.cms.businesslogic.member addCookie("umbracoMemberGuid", m.UniqueId.ToString(), 365); addCookie("umbracoMemberLogin", m.LoginName, 365); - // Debug information - HttpContext.Current.Trace.Write("member", - "Member added to cache: " + m.Text + "/" + m.LoginName + " (" + - m.Id + ")"); + //cache the member + var cachedMember = Cache.GetCacheItem(GetCacheKey(m.Id), m_Locker, + TimeSpan.FromMinutes(30), + delegate + { + // Debug information + HttpContext.Current.Trace.Write("member", + string.Format("Member added to cache: {0}/{1} ({2})", + m.Text, m.LoginName, m.Id)); - _memberCache["umbracoMembers"] = umbracoMembers; + return m; + }); FormsAuthentication.SetAuthCookie(m.LoginName, true); @@ -769,13 +806,6 @@ namespace umbraco.cms.businesslogic.member if (!e.Cancel) { - - Hashtable umbracoMembers = CachedMembers(); - - // Check if member already exists - if (umbracoMembers[m.Id] == null) - umbracoMembers.Add(m.Id, m); - if (!UseSession) { removeCookie("umbracoMemberId"); @@ -792,14 +822,20 @@ namespace umbraco.cms.businesslogic.member HttpContext.Current.Session["umbracoMemberLogin"] = m.LoginName; } - // Debug information - HttpContext.Current.Trace.Write("member", - string.Format("Member added to cache: {0}/{1} ({2})", - m.Text, m.LoginName, m.Id)); - - _memberCache["umbracoMembers"] = umbracoMembers; + //cache the member + var cachedMember = Cache.GetCacheItem(GetCacheKey(m.Id), m_Locker, + TimeSpan.FromMinutes(30), + delegate + { + // Debug information + HttpContext.Current.Trace.Write("member", + string.Format("Member added to cache: {0}/{1} ({2})", + m.Text, m.LoginName, m.Id)); + return m; + }); + FormsAuthentication.SetAuthCookie(m.LoginName, false); m.FireAfterAddToCache(e); @@ -828,11 +864,7 @@ namespace umbraco.cms.businesslogic.member /// Node Id of the member to remove public static void RemoveMemberFromCache(int NodeId) { - Hashtable umbracoMembers = CachedMembers(); - if (umbracoMembers.ContainsKey(NodeId)) - umbracoMembers.Remove(NodeId); - - _memberCache["umbracoMembers"] = umbracoMembers; + Cache.ClearCacheItem(GetCacheKey(NodeId)); } /// @@ -885,15 +917,17 @@ namespace umbraco.cms.businesslogic.member /// A collection of cached members public static Hashtable CachedMembers() { - Hashtable umbracoMembers; - - // Check for member hashtable in cache - if (_memberCache["umbracoMembers"] == null) - umbracoMembers = new Hashtable(); - else - umbracoMembers = (Hashtable)_memberCache["umbracoMembers"]; - - return umbracoMembers; + var h = new Hashtable(); + Cache.ReturnCacheItemsOrdred() + .Cast() + .Where(x => x.Key.ToString().StartsWith("MemberCacheItem_")) + .Select(x => (Member)x.Value) + .ToList() + .ForEach(x => + { + h.Add(x.Id, x); + }); + return h; } /// @@ -1025,22 +1059,22 @@ namespace umbraco.cms.businesslogic.member #endregion + #region Events - //EVENTS /// /// The save event handler /// - new public delegate void SaveEventHandler(Member sender, SaveEventArgs e); + public delegate void SaveEventHandler(Member sender, SaveEventArgs e); /// /// The new event handler /// - new public delegate void NewEventHandler(Member sender, NewEventArgs e); + public delegate void NewEventHandler(Member sender, NewEventArgs e); /// /// The delete event handler /// - new public delegate void DeleteEventHandler(Member sender, DeleteEventArgs e); + public delegate void DeleteEventHandler(Member sender, DeleteEventArgs e); /// /// The add to cache event handler @@ -1085,8 +1119,8 @@ namespace umbraco.cms.businesslogic.member } - new public static event NewEventHandler New; - new protected virtual void OnNew(NewEventArgs e) + public static event NewEventHandler New; + protected virtual void OnNew(NewEventArgs e) { if (New != null) { @@ -1167,182 +1201,188 @@ namespace umbraco.cms.businesslogic.member { AfterDelete(this, e); } - } - } + } + #endregion - /// - /// ONLY FOR INTERNAL USE. - /// This is needed due to a design flaw where the Umbraco membership provider is located - /// in a separate project referencing this project, which means we can't call special methods - /// directly on the UmbracoMemberShipMember class. - /// This is a helper implementation only to be able to use the encryption functionality - /// of the membership provides (which are protected). - /// - /// ... which means this class should have been marked internal with a Friend reference to the other assembly right?? - /// - public class MemberShipHelper : MembershipProvider - { - public override string ApplicationName + #region Membership helper class used for encryption methods + /// + /// ONLY FOR INTERNAL USE. + /// This is needed due to a design flaw where the Umbraco membership provider is located + /// in a separate project referencing this project, which means we can't call special methods + /// directly on the UmbracoMemberShipMember class. + /// This is a helper implementation only to be able to use the encryption functionality + /// of the membership provides (which are protected). + /// + /// ... which means this class should have been marked internal with a Friend reference to the other assembly right?? + /// + internal class MemberShipHelper : MembershipProvider { - get + public override string ApplicationName + { + get + { + throw new NotImplementedException(); + } + set + { + throw new NotImplementedException(); + } + } + + public override bool ChangePassword(string username, string oldPassword, string newPassword) { throw new NotImplementedException(); } - set + + public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new NotImplementedException(); } - } - public override bool ChangePassword(string username, string oldPassword, string newPassword) - { - throw new NotImplementedException(); - } - - public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) - { - throw new NotImplementedException(); - } - - public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) - { - throw new NotImplementedException(); - } - - public override bool DeleteUser(string username, bool deleteAllRelatedData) - { - throw new NotImplementedException(); - } - - public string EncodePassword(string password, MembershipPasswordFormat pwFormat) - { - string encodedPassword = password; - switch (pwFormat) + public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { - case MembershipPasswordFormat.Clear: - break; - case MembershipPasswordFormat.Encrypted: - encodedPassword = - Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); - break; - case MembershipPasswordFormat.Hashed: - HMACSHA1 hash = new HMACSHA1(); - hash.Key = Encoding.Unicode.GetBytes(password); - encodedPassword = - Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); - break; + throw new NotImplementedException(); } - return encodedPassword; - } - public override bool EnablePasswordReset - { - get { throw new NotImplementedException(); } - } + public override bool DeleteUser(string username, bool deleteAllRelatedData) + { + throw new NotImplementedException(); + } - public override bool EnablePasswordRetrieval - { - get { throw new NotImplementedException(); } - } + public string EncodePassword(string password, MembershipPasswordFormat pwFormat) + { + string encodedPassword = password; + switch (pwFormat) + { + case MembershipPasswordFormat.Clear: + break; + case MembershipPasswordFormat.Encrypted: + encodedPassword = + Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); + break; + case MembershipPasswordFormat.Hashed: + HMACSHA1 hash = new HMACSHA1(); + hash.Key = Encoding.Unicode.GetBytes(password); + encodedPassword = + Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); + break; + } + return encodedPassword; + } - public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } + public override bool EnablePasswordReset + { + get { throw new NotImplementedException(); } + } - public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } + public override bool EnablePasswordRetrieval + { + get { throw new NotImplementedException(); } + } - public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) - { - throw new NotImplementedException(); - } + public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) + { + throw new NotImplementedException(); + } - public override int GetNumberOfUsersOnline() - { - throw new NotImplementedException(); - } + public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) + { + throw new NotImplementedException(); + } - public override string GetPassword(string username, string answer) - { - throw new NotImplementedException(); - } + public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) + { + throw new NotImplementedException(); + } - public override MembershipUser GetUser(string username, bool userIsOnline) - { - throw new NotImplementedException(); - } + public override int GetNumberOfUsersOnline() + { + throw new NotImplementedException(); + } - public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) - { - throw new NotImplementedException(); - } + public override string GetPassword(string username, string answer) + { + throw new NotImplementedException(); + } - public override string GetUserNameByEmail(string email) - { - throw new NotImplementedException(); - } + public override MembershipUser GetUser(string username, bool userIsOnline) + { + throw new NotImplementedException(); + } - public override int MaxInvalidPasswordAttempts - { - get { throw new NotImplementedException(); } - } + public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) + { + throw new NotImplementedException(); + } - public override int MinRequiredNonAlphanumericCharacters - { - get { throw new NotImplementedException(); } - } + public override string GetUserNameByEmail(string email) + { + throw new NotImplementedException(); + } - public override int MinRequiredPasswordLength - { - get { throw new NotImplementedException(); } - } + public override int MaxInvalidPasswordAttempts + { + get { throw new NotImplementedException(); } + } - public override int PasswordAttemptWindow - { - get { throw new NotImplementedException(); } - } + public override int MinRequiredNonAlphanumericCharacters + { + get { throw new NotImplementedException(); } + } - public override MembershipPasswordFormat PasswordFormat - { - get { throw new NotImplementedException(); } - } + public override int MinRequiredPasswordLength + { + get { throw new NotImplementedException(); } + } - public override string PasswordStrengthRegularExpression - { - get { throw new NotImplementedException(); } - } + public override int PasswordAttemptWindow + { + get { throw new NotImplementedException(); } + } - public override bool RequiresQuestionAndAnswer - { - get { throw new NotImplementedException(); } - } + public override MembershipPasswordFormat PasswordFormat + { + get { throw new NotImplementedException(); } + } - public override bool RequiresUniqueEmail - { - get { throw new NotImplementedException(); } - } + public override string PasswordStrengthRegularExpression + { + get { throw new NotImplementedException(); } + } - public override string ResetPassword(string username, string answer) - { - throw new NotImplementedException(); - } + public override bool RequiresQuestionAndAnswer + { + get { throw new NotImplementedException(); } + } - public override bool UnlockUser(string userName) - { - throw new NotImplementedException(); - } + public override bool RequiresUniqueEmail + { + get { throw new NotImplementedException(); } + } - public override void UpdateUser(MembershipUser user) - { - throw new NotImplementedException(); - } + public override string ResetPassword(string username, string answer) + { + throw new NotImplementedException(); + } - public override bool ValidateUser(string username, string password) - { - throw new NotImplementedException(); - } + public override bool UnlockUser(string userName) + { + throw new NotImplementedException(); + } + + public override void UpdateUser(MembershipUser user) + { + throw new NotImplementedException(); + } + + public override bool ValidateUser(string username, string password) + { + throw new NotImplementedException(); + } + } + #endregion + } + + } \ No newline at end of file diff --git a/umbraco/cms/businesslogic/member/MemberType.cs b/umbraco/cms/businesslogic/member/MemberType.cs index 017184437d..c022a5241a 100644 --- a/umbraco/cms/businesslogic/member/MemberType.cs +++ b/umbraco/cms/businesslogic/member/MemberType.cs @@ -3,6 +3,7 @@ using System.Data; using System.Xml; using umbraco.cms.businesslogic.propertytype; using System.Linq; +using umbraco.BusinessLogic; namespace umbraco.cms.businesslogic.member { @@ -18,17 +19,13 @@ namespace umbraco.cms.businesslogic.member /// Initializes a new instance of the MemberType class. /// /// MemberType id - public MemberType(int id) : base(id) - { - } + public MemberType(int id) : base(id) { } + /// /// Initializes a new instance of the MemberType class. /// /// MemberType id - public MemberType(Guid id) : base(id) - { - } - + public MemberType(Guid id) : base(id) { } /// /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility @@ -42,16 +39,14 @@ namespace umbraco.cms.businesslogic.member FireAfterSave(e); } } - - + /// /// Create a new MemberType /// /// The name of the MemberType /// Creator of the MemberType - public static MemberType MakeNew( BusinessLogic.User u,string Text) - { - + public static MemberType MakeNew(User u,string Text) + { int ParentId= -1; int level = 1; Guid uniqueId = Guid.NewGuid(); @@ -68,30 +63,32 @@ namespace umbraco.cms.businesslogic.member /// /// Retrieve a list of all MemberTypes /// - new public static MemberType[] GetAll { - get - { - Guid[] Ids = CMSNode.getAllUniquesFromObjectType(_objectType); + public new static MemberType[] GetAll + { + 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; - } - } + MemberType[] retVal = new MemberType[Ids.Length]; + for (int i = 0; i < Ids.Length; i++) retVal[i] = new MemberType(Ids[i]); + return retVal; + } + } /// /// Get an true/false if the Member can edit the given data defined in the propertytype /// /// Propertytype to edit /// True if the Member can edit the data - public bool MemberCanEdit(propertytype.PropertyType pt) { + 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 false; + } /// /// Get a MemberType by it's alias @@ -110,7 +107,7 @@ namespace umbraco.cms.businesslogic.member /// /// Propertytype /// True if the data should be displayed on the profilepage - public bool ViewOnProfile(propertytype.PropertyType pt) + public bool ViewOnProfile(PropertyType pt) { if(propertyTypeRegistered(pt)) { @@ -124,19 +121,21 @@ 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.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)"); + 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)"); - } + } - private bool propertyTypeRegistered(propertytype.PropertyType pt) { - return (SqlHelper.ExecuteScalar("Select count(pk) as tmp from cmsMemberType where NodeId = " + this.Id +" And propertytypeId = "+pt.Id) > 0); - } + private bool propertyTypeRegistered(PropertyType pt) + { + return (SqlHelper.ExecuteScalar("Select count(pk) as tmp from cmsMemberType where NodeId = " + this.Id + " And propertytypeId = " + pt.Id) > 0); + } /// @@ -144,7 +143,7 @@ namespace umbraco.cms.businesslogic.member /// /// PropertyType /// True/False if the data should be displayed - public void setMemberViewOnProfile(propertytype.PropertyType pt, bool value) + public void setMemberViewOnProfile(PropertyType pt, bool value) { int tmpval = 0; if (value) tmpval = 1; @@ -161,15 +160,17 @@ namespace umbraco.cms.businesslogic.member /// /// Use with care /// - new public void delete() + public override void delete() { DeleteEventArgs e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { + // delete all documents of this type Member.DeleteFromType(this); + // delete membertype specific data SqlHelper.ExecuteNonQuery("Delete from cmsMemberType where nodeId = " + this.Id); @@ -178,55 +179,7 @@ namespace umbraco.cms.businesslogic.member FireAfterDelete(e); } } - - //EVENTS - /// - /// The save event handler - /// - public delegate void SaveEventHandler(MemberType sender, SaveEventArgs e); - /// - /// The new event handler - /// - public delegate void NewEventHandler(MemberType sender, NewEventArgs e); - /// - /// The delete event handler - /// - public delegate void DeleteEventHandler(MemberType sender, DeleteEventArgs e); - - - /// - /// Occurs when a language is saved. - /// - public static event SaveEventHandler BeforeSave; - protected virtual void FireBeforeSave(SaveEventArgs e) { - if (BeforeSave != null) - BeforeSave(this, e); - } - - public static event SaveEventHandler AfterSave; - protected virtual void FireAfterSave(SaveEventArgs e) { - if (AfterSave != null) - AfterSave(this, e); - } - - public static event NewEventHandler New; - protected virtual void OnNew(NewEventArgs e) { - if (New != null) - New(this, e); - } - - public static event DeleteEventHandler BeforeDelete; - protected virtual void FireBeforeDelete(DeleteEventArgs e) { - if (BeforeDelete != null) - BeforeDelete(this, e); - } - - public static event DeleteEventHandler AfterDelete; - protected virtual void FireAfterDelete(DeleteEventArgs e) { - if (AfterDelete != null) - AfterDelete(this, e); - } - + public XmlElement ToXml(XmlDocument xd) { XmlElement root = xd.CreateElement("MemberType"); @@ -270,5 +223,60 @@ namespace umbraco.cms.businesslogic.member root.AppendChild(tabs); return root; } + + #region Events + + /// + /// The save event handler + /// + public delegate void SaveEventHandler(MemberType sender, SaveEventArgs e); + /// + /// The new event handler + /// + public delegate void NewEventHandler(MemberType sender, NewEventArgs e); + /// + /// The delete event handler + /// + public delegate void DeleteEventHandler(MemberType sender, DeleteEventArgs e); + + + /// + /// Occurs when a language is saved. + /// + public static event SaveEventHandler BeforeSave; + protected virtual void FireBeforeSave(SaveEventArgs e) + { + if (BeforeSave != null) + BeforeSave(this, e); + } + + public static event SaveEventHandler AfterSave; + protected virtual void FireAfterSave(SaveEventArgs e) + { + if (AfterSave != null) + AfterSave(this, e); + } + + public static event NewEventHandler New; + protected virtual void OnNew(NewEventArgs e) + { + if (New != null) + New(this, e); + } + + public static event DeleteEventHandler BeforeDelete; + protected virtual void FireBeforeDelete(DeleteEventArgs e) + { + if (BeforeDelete != null) + BeforeDelete(this, e); + } + + public static event DeleteEventHandler AfterDelete; + protected virtual void FireAfterDelete(DeleteEventArgs e) + { + if (AfterDelete != null) + AfterDelete(this, e); + } + #endregion } } \ No newline at end of file diff --git a/umbraco/cms/businesslogic/web/Document.cs b/umbraco/cms/businesslogic/web/Document.cs index ceaed69f80..8dcf6b9d7f 100644 --- a/umbraco/cms/businesslogic/web/Document.cs +++ b/umbraco/cms/businesslogic/web/Document.cs @@ -27,12 +27,13 @@ namespace umbraco.cms.businesslogic.web public class Document : Content { #region Constructors + /// /// Constructs a new document /// /// Id of the document /// true if the data shouldn't loaded from the db - public Document(Guid id, bool noSetup) : base(id) { } + public Document(Guid id, bool noSetup) : base(id, noSetup) { } /// /// Initializes a new instance of the Document class. @@ -49,8 +50,7 @@ namespace umbraco.cms.businesslogic.web /// /// The id of the document /// The version of the document - public Document(int id, Guid Version) - : base(id) + public Document(int id, Guid Version) : base(id) { this.Version = Version; } @@ -67,9 +67,12 @@ namespace umbraco.cms.businesslogic.web /// The id of the document public Document(Guid id) : base(id) { } - //TODO: SD: Implement this EVERYWHERE (90 places apparently) - public Document(bool optimizedMode, int id) - : base(id, optimizedMode) + /// + /// Initializes a Document object with one SQL query instead of many + /// + /// + /// + public Document(bool optimizedMode, int id) : base(id, optimizedMode) { this._optimizedMode = optimizedMode; @@ -136,6 +139,7 @@ namespace umbraco.cms.businesslogic.web } } } + #endregion #region Constants and Static members @@ -329,9 +333,18 @@ namespace umbraco.cms.businesslogic.web CMSNode n = new CMSNode(ParentId); int newLevel = n.Level; newLevel++; - MakeNew(ParentId, _objectType, u.Id, newLevel, Name, newId); + + //create the cms node first + CMSNode newNode = MakeNew(ParentId, _objectType, u.Id, newLevel, Name, newId); + + //we need to create an empty document and set the underlying text property Document tmp = new Document(newId, true); + tmp.SetText(Name); + + //create the content data for the new document tmp.CreateContent(dct); + + //now create the document data SqlHelper.ExecuteNonQuery("insert into cmsDocument (newest, nodeId, published, documentUser, versionId, Text) values (1, " + tmp.Id + ", 0, " + u.Id + ", @versionId, @text)", @@ -341,10 +354,10 @@ namespace umbraco.cms.businesslogic.web // Update the sortOrder if the parent was the root! if (ParentId == -1) { - CMSNode c = new CMSNode(newId); - c.sortOrder = GetRootDocuments().Length + 1; + newNode.sortOrder = GetRootDocuments().Length + 1; } + //read the whole object from the db Document d = new Document(newId); //event @@ -1396,24 +1409,30 @@ namespace umbraco.cms.businesslogic.web { base.setupNode(); - IRecordsReader dr = + using (var dr = SqlHelper.ExecuteReader("select published, documentUser, coalesce(templateId, cmsDocumentType.templateNodeId) as templateId, text, releaseDate, expireDate, updateDate from cmsDocument inner join cmsContent on cmsDocument.nodeId = cmsContent.Nodeid left join cmsDocumentType on cmsDocumentType.contentTypeNodeId = cmsContent.contentType and cmsDocumentType.IsDefault = 1 where versionId = @versionId", - SqlHelper.CreateParameter("@versionId", Version)); - if (dr.Read()) + SqlHelper.CreateParameter("@versionId", Version))) { - _creator = User; - _writer = User.GetUser(dr.GetInt("documentUser")); + if (dr.Read()) + { + _creator = User; + _writer = User.GetUser(dr.GetInt("documentUser")); - if (!dr.IsNull("templateId")) - _template = dr.GetInt("templateId"); - if (!dr.IsNull("releaseDate")) - _release = dr.GetDateTime("releaseDate"); - if (!dr.IsNull("expireDate")) - _expire = dr.GetDateTime("expireDate"); - if (!dr.IsNull("updateDate")) - _updated = dr.GetDateTime("updateDate"); + if (!dr.IsNull("templateId")) + _template = dr.GetInt("templateId"); + if (!dr.IsNull("releaseDate")) + _release = dr.GetDateTime("releaseDate"); + if (!dr.IsNull("expireDate")) + _expire = dr.GetDateTime("expireDate"); + if (!dr.IsNull("updateDate")) + _updated = dr.GetDateTime("updateDate"); + } + else + { + throw new ArgumentException(string.Format("No Document exists with Version '{0}'", Version)); + } } - dr.Close(); + _published = HasPublishedVersion(); } diff --git a/umbraco/presentation/umbraco/create/memberTasks.cs b/umbraco/presentation/umbraco/create/memberTasks.cs index 559c37757e..4be77adac6 100644 --- a/umbraco/presentation/umbraco/create/memberTasks.cs +++ b/umbraco/presentation/umbraco/create/memberTasks.cs @@ -76,9 +76,8 @@ namespace umbraco if (cms.businesslogic.member.Member.InUmbracoMemberMode() && TypeID != -1) { cms.businesslogic.member.MemberType dt = new cms.businesslogic.member.MemberType(TypeID); - cms.businesslogic.member.Member m = cms.businesslogic.member.Member.MakeNew(name, dt, BusinessLogic.User.GetUser(_userID)); - m.Password = password; - m.Email = email; + cms.businesslogic.member.Member m = cms.businesslogic.member.Member.MakeNew(name, email, dt, BusinessLogic.User.GetUser(_userID)); + m.Password = password; m.LoginName = name.Replace(" ", "").ToLower(); NewMemberUIEventArgs e = new NewMemberUIEventArgs();