public void CloseConnectionBeforeDataContextDisposal()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["Global"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();

            // set an opening connection and close it before the data context disposed
            using (MembershipDataContext ctx = new MembershipDataContext(connection))
            {
                Application application = ctx.Applications.FirstOrDefault();
                Assert.IsNotNull(application);
                Assert.AreEqual(ConnectionState.Open, connection.State);
                connection.Close();
            }

            connection = new SqlConnection(connectionString);
            // set an closed connection and close it before the data context disposed
            using (MembershipDataContext ctx = new MembershipDataContext(connection))
            {
                Application application = ctx.Applications.FirstOrDefault();
                Assert.IsNotNull(application);
                Assert.AreEqual(ConnectionState.Closed, connection.State);
                connection.Close();
            }
        }
        private void UpdateSubOrganizationsStatus(MembershipDataContext ctx, Guid[] parentOrganizationIds, OrganizationStatus status)
        {
            var q = from org in ctx.Organizations
                    where org.ParentOrganizationId.HasValue
                        && parentOrganizationIds.Contains(org.ParentOrganizationId.Value)
                        && org.Status != status
                    select org;

            if (q.Count() == 0) return;

            foreach (Organization organization in q.AsEnumerable())
            {
                organization.Status = status;
                base.RemoveCache(organization.OrganizationId);
            }

            UpdateSubOrganizationsStatus(ctx, q.Select(org => org.OrganizationId).ToArray(), status);
        }
        private static OrganizationObject Convert2OrganizationObject(MembershipDataContext ctx, Organization org)
        {
            OrganizationObject organizationObject = new OrganizationObject()
            {
                ExtensionDataTypeId = org.ExtensionDataTypeId,
                OrganizationId = org.OrganizationId,
                OrganizationCode = org.OrganizationCode,
                OrganizationName = org.OrganizationName,
                OrganizationTypeId = org.OrganizationTypeId,
                Description = org.Description,
                Status = org.Status,
                CreatedBy = org.CreatedBy,
                CreatedDate = org.CreatedDate,
                LastUpdatedBy = org.LastUpdatedBy,
                LastUpdatedDate = org.LastUpdatedDate,
                ParentOrganizationId = org.ParentOrganizationId
            };

            foreach (OrganizationsInHierarchy organizationsInHierarchy in org.Hierarchies)
                organizationObject.Hierarchies[organizationsInHierarchy.HierarchyType] = organizationsInHierarchy.HierarchyDataId;

            organizationObject.ParseExtensionPropertiesFrom(org);
            return organizationObject;
        }
        private Relationship GetRelationshipFromDb(MembershipDataContext ctx, Guid objectXId, Guid objectYId, string relationshipType)
        {
            Guid smallId = IsXLessThanY(objectXId, objectYId) ? objectXId : objectYId;
            Guid bigId = smallId != objectXId ? objectXId : objectYId;
            var q = from r in ctx.Relationships
                    where r.ApplicationId == authenticationContext.ApplicationId
                        && r.ObjectXId == smallId
                        && r.ObjectYId == bigId
                        && r.RelationshipType == relationshipType
                    select r;

            return q.FirstOrDefault();
        }
        private static void ValidateUserData(MembershipDataContext ctx, Guid applicationId, UserObject userObject)
        {
            // check user name
            if (Kit.IsEmpty(userObject.UserName) || userObject.UserName.Length > 256)
                throw new ValidationException(Resources.InvalidUserName);

            if (ctx.Users.Where(user => user.UserName == userObject.UserName && user.ApplicationId == applicationId && user.UserId != userObject.UserId).Count() > 0)
                throw new ValidationException(Resources.ExistedUserName);

            // check display name
            if (Kit.IsEmpty(userObject.DisplayName) || userObject.DisplayName.Length > 256)
                throw new ValidationException(Resources.InvalidDisplayName);

            if (ctx.Users.Where(user => user.DisplayName == userObject.DisplayName && user.ApplicationId == applicationId && user.UserId != userObject.UserId).Count() > 0)
                throw new ValidationException(Resources.ExistedDisplayName);

            // check email
            if (Kit.IsEmpty(userObject.Email) && AspNetMembership.Provider.RequiresUniqueEmail)
                throw new ValidationException(Resources.UserEmailCannotBeEmpty);

            if (!Kit.IsEmpty(userObject.Email) && userObject.Email.Length > 256)
                throw new ValidationException(Resources.InvalidUserEmail);

            if (AspNetMembership.Provider.RequiresUniqueEmail && ctx.Users.Where(user => user.Membership.LoweredEmail == userObject.Email.ToLowerInvariant() && user.ApplicationId == applicationId && user.UserId != userObject.UserId).Count() > 0)
                throw new ValidationException(Resources.ExistedUserEmail);
        }
        public void TwoDataContextSharesSingleConnection()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["Global"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();

            // MembershipDataContext creates an application using an opening connection
            Application application = null;
            string applicationName = "TwoDataContextSharesOpeningConnection";
            using (MembershipDataContext ctx = new MembershipDataContext(connection))
            {
                application = new Application
                {
                    ApplicationName = applicationName,
                    LoweredApplicationName = applicationName.ToLowerInvariant()
                };

                ctx.Applications.InsertOnSubmit(application);
                ctx.SubmitChanges();
            }

            Assert.AreEqual(ConnectionState.Open, connection.State);

            // ExtensionModelDataContext creates an object metadata using an opening connection
            using (ExtensionModelDataContext ctx = new ExtensionModelDataContext(connection))
            {
                ObjectMetadata objectMetadata = new ObjectMetadata
                {
                    ApplicationId = application.ApplicationId,
                    Category = "Linq2SQLDataContextTests.Category",
                    Name = "Linq2SQLDataContextTests.Name",
                    LastUpdatedOn = DateTime.UtcNow
                };

                ctx.ObjectMetadatas.InsertOnSubmit(objectMetadata);
                ctx.SubmitChanges();
            }

            Assert.AreEqual(ConnectionState.Open, connection.State);
            connection.Close();

            connection = new SqlConnection(connectionString);
            // MembershipDataContext removes an application using an closed connection
            using (MembershipDataContext ctx = new MembershipDataContext(connection))
            {
                application = ctx.Applications.FirstOrDefault(app => app.ApplicationName == applicationName);
                Assert.IsNotNull(application);
                ctx.Applications.DeleteOnSubmit(application);
                ctx.SubmitChanges();
            }

            Assert.AreEqual(ConnectionState.Closed, connection.State);

            // ExtensionModelDataContext removes an object metadata using an closed connection
            using (ExtensionModelDataContext ctx = new ExtensionModelDataContext(connection))
            {
                ObjectMetadata objectMetadata = ctx.ObjectMetadatas.FirstOrDefault(metadata => metadata.Name == "Linq2SQLDataContextTests.Name");
                Assert.IsNotNull(objectMetadata);
                ctx.ObjectMetadatas.DeleteOnSubmit(objectMetadata);
                ctx.SubmitChanges();
            }

            Assert.AreEqual(ConnectionState.Closed, connection.State);
        }
        public void TransactionScopeWithoutDTCTest()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["Global"].ConnectionString;
            using (TransactionScope ts = new TransactionScope())
            {
                // creates an application using MembershipDataContext
                Application application = null;
                string applicationName = string.Format(CultureInfo.InvariantCulture, "TransactionScopeWithoutDTCTest.{0}", Guid.NewGuid());
                using (MembershipDataContext ctx = new MembershipDataContext(connectionString))
                {
                    application = new Application
                    {
                        ApplicationName = applicationName,
                        LoweredApplicationName = applicationName.ToLowerInvariant()
                    };

                    ctx.Applications.InsertOnSubmit(application);
                    ctx.SubmitChanges();

                }

                // creates an object metadata using ExtensionModelDataContext
                using (ExtensionModelDataContext ctx = new ExtensionModelDataContext(connectionString))
                {
                    Assert.AreEqual(ConnectionState.Closed, ctx.Connection.State);
                    ObjectMetadata objectMetadata = new ObjectMetadata
                    {
                        ApplicationId = application.ApplicationId,
                        Category = "TransactionScopeWithoutDTCTest.Category",
                        Name = "TransactionScopeWithoutDTCTest.Name",
                        LastUpdatedOn = DateTime.UtcNow
                    };

                    ctx.ObjectMetadatas.InsertOnSubmit(objectMetadata);
                    ctx.SubmitChanges();
                }

                // deletes above created temporary data using managed ado.net command.
                using (MembershipDataContext membershipDataContext = new MembershipDataContext())
                using (ExtensionModelDataContext extensionModelDataContext = new ExtensionModelDataContext())
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE ApplicationId='{1}' AND Name='{2}'",
                        extensionModelDataContext.Mapping.GetTable(typeof(ObjectMetadata)).TableName,
                        application.ApplicationId,
                        "TransactionScopeWithoutDTCTest.Name");
                    command.CommandType = CommandType.Text;
                    command.ExecuteNonQuery();

                    command.CommandText = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE ApplicationId='{1}'",
                        membershipDataContext.Mapping.GetTable(typeof(Application)).TableName,
                        application.ApplicationId);
                    command.ExecuteNonQuery();
                }

                // gets the user "admin" by ASP.NET Membership
                Assert.IsNotNull(System.Web.Security.Membership.GetUser("admin"), "The user admin should exist.");

                ts.Complete();
            }
        }
        private void RecursivelyDeleteChildHierarchyData(MembershipDataContext ctx, Guid[] parentHierarchyDataIds)
        {
            if (parentHierarchyDataIds == null || parentHierarchyDataIds.Length == 0) return;

            foreach (Guid parentHierarchyDataId in parentHierarchyDataIds)
                base.RemoveCache(parentHierarchyDataId);

            List<HierarchyData> hierarchyDataList = ctx.HierarchyDatas.Where(d => parentHierarchyDataIds.Contains(d.ParentHierarchyDataId.Value)).ToList();
            ctx.HierarchyDatas.DeleteAllOnSubmit(hierarchyDataList);

            Guid[] hierarchyDataIdArray = hierarchyDataList.Select(d => d.HierarchyDataId).ToArray();
            RecursivelyDeleteChildHierarchyData(ctx, hierarchyDataIdArray);
        }