Exemplo n.º 1
0
        private static T CreateCopyAndEnlistChildren <T>(T original, IGroupUnit <IProviderTypeFilter> unitOfWork) where T : TypedEntity, new()
        {
            var copy = original.CreateShallowCopy();

            // Go through each of the child relation proxies and create a new proxy in the copied item
            foreach (var relationProxy in original.RelationProxies.AllChildRelations())
            {
                var childToCopyId = relationProxy.Item.DestinationId;
                var childToCopy   = unitOfWork.Repositories.Get <T>(childToCopyId);
                if (childToCopy == null)
                {
                    throw new InvalidOperationException(
                              "Cannot copy an entity's relations unless the entity is available as a hydrated object, it's only available as id {0}"
                              .InvariantFormat(relationProxy.Item.DestinationId));
                }

                // Copy the related item and recurse any children it has enlisted
                var copiedChild = CreateCopyAndEnlistChildren(childToCopy, unitOfWork);

                // Add it to our outgoing copy's relation proxies
                copy.RelationProxies.EnlistChild(copiedChild, relationProxy.Item.Type, relationProxy.Item.MetaData.ToArray());

                // Add the duplicate to the repo
                unitOfWork.Repositories.AddOrUpdate(copiedChild);
            }
            return(copy);
        }
        internal static User GetUmbracoUser(IUmbracoApplicationContext appContext, IGroupUnit <ISecurityStore> uow, string username, bool userIsOnline)
        {
            // TODO: Enable type of extension method GetEntityByRelationType to be passed all the way to the provider
            // so that it can use the typemappers collection to map back to a User

            // APN: I changed SingleOrDefault to FirstOrDefault to guard against YSODs if somehow a duplicate user gets into the store [31/Jan]
            var userEntity = uow.Repositories
                             .GetEntityByRelationType <TypedEntity>(
                FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserVirtualRoot)
                             .FirstOrDefault(x => x.Attribute <string>(UserSchema.UsernameAlias) == username);


            if (userEntity == null)
            {
                return(null);
            }

            var user = new User();

            user.SetupFromEntity(userEntity);

            if (userIsOnline)
            {
                user.LastActivityDate = DateTime.UtcNow;

                uow.Repositories.AddOrUpdate(user);
                uow.Complete();
            }

            return(user);
        }
Exemplo n.º 3
0
        internal RebelMembershipUser GetRebelUser(IGroupUnit <ISecurityStore> uow, string username, bool userIsOnline)
        {
            return(AppContext.FrameworkContext.ScopedCache.GetOrCreateTyped <RebelMembershipUser>(GetRebelUserCacheKeyForUsername(username), () =>
            {
                // Use FirstOrDefault in case somehow a duplicate user got into the system
                var matchingUsers = uow.Repositories
                                    .WithParentIds(FixedRelationTypes.DefaultRelationType, VirtualRootId)
                                    .Where(
                    x =>
                    x.EntitySchema.Alias == MembershipUserSchema.SchemaAlias &&
                    x.Attribute <string>(MembershipUserSchema.UsernameAlias) == username)
                                    .OrderByDescending(x => x.UtcCreated)
                                    .FirstOrDefault();

                if (matchingUsers == null)
                {
                    return null;
                }

                var user = new RebelMembershipUser();
                user.SetupFromEntity(matchingUsers);

                //if (userIsOnline)
                //{
                //    user.LastActivityDate = DateTime.UtcNow;

                //    uow.Repositories.AddOrUpdate(user);
                //    uow.Complete();
                //}

                return user;
            }));
        }
        internal static User GetUmbracoUser(IGroupUnit <ISecurityStore> uow, HiveId id, bool userIsOnline)
        {
            var user = uow.Repositories
                       .GetEntityByRelationType <User>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserVirtualRoot)
                       .SingleOrDefault(x => x.Id.Value == id.Value);

            //.SingleOrDefault(x => x.Id.ToString(HiveIdFormatStyle.AsUri) == id.ToString(HiveIdFormatStyle.AsUri));
            //Had to change this comparison to use values because the Uri portion wont work with the membership wrapper provider because the
            //underlying membership providers dont know anything about a URI, therefore teh wrapper only passes in the value portion of the HiveId. SD. 28/11/2011


            if (user == null)
            {
                return(null);
            }

            if (userIsOnline)
            {
                user.LastActivityDate = DateTime.UtcNow;

                uow.Repositories.AddOrUpdate(user);
                uow.Complete();
            }

            return(user);
        }
Exemplo n.º 5
0
        public static ISchemaBuilderStep <T, TProviderFilter> SaveTo <T, TProviderFilter>(
            this ISchemaBuilderStep <T, TProviderFilter> builder,
            IGroupUnit <TProviderFilter> writer)
            where TProviderFilter : class, IProviderTypeFilter
            where T : EntitySchema, new()
        {
            Mandate.ParameterNotNull(builder, "builder");
            Mandate.ParameterNotNull(writer, "writer");
            Mandate.ParameterCondition(!writer.WasAbandoned, "writer.WasAbandoned");

            writer.Repositories.Schemas.AddOrUpdate(builder.Item);

            return(builder);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Sets up a Member by Member Type alias.
        /// </summary>
        /// <param name="member">The member.</param>
        /// <param name="alias">The alias.</param>
        /// <param name="uow">The uow.</param>
        public static void SetupFromSchema(this Member member, string alias, IGroupUnit<ISecurityStore> uow)
        {
            var memberGroupRelations = uow.Repositories.Schemas
                .GetDescendentRelations(Framework.Security.Model.FixedHiveIds.MasterMemberProfileSchema, FixedRelationTypes.DefaultRelationType);
            var memberTypes = uow.Repositories.Schemas
                .Get<EntitySchema>(true, memberGroupRelations.Select(x => x.DestinationId).ToArray());
            var memberType = memberTypes.SingleOrDefault(x => x.Alias.Equals(alias, StringComparison.InvariantCultureIgnoreCase));

            if (memberType == null)
                throw new ApplicationException(string.Format("No member type found with the alias '{0}'", alias));

            var compositeMemberType = uow.Repositories.Schemas.GetComposite(memberType);

            member.SetupFromSchema(compositeMemberType);
        }
Exemplo n.º 7
0
        public static Rebel.Framework.Persistence.Model.IO.File GetPackageFileById(IGroupUnit <IFileStore> uow,
                                                                                   HiveId id)
        {
            var folder = uow.Repositories.Get <Rebel.Framework.Persistence.Model.IO.File>(id);

            if (folder == null)
            {
                return(null);
            }

            var fileIds     = uow.Repositories.GetChildRelations(folder.Id).Select(x => x.DestinationId).ToArray();
            var files       = uow.Repositories.Get <Rebel.Framework.Persistence.Model.IO.File>(true, fileIds);
            var packageFile = files.SingleOrDefault(x => x.Name.EndsWith(".nupkg"));

            return(packageFile);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Sets up a Member by Member Type alias.
        /// </summary>
        /// <param name="member">The member.</param>
        /// <param name="alias">The alias.</param>
        /// <param name="uow">The uow.</param>
        public static void SetupFromSchema(this Member member, string alias, IGroupUnit <ISecurityStore> uow)
        {
            var memberGroupRelations = uow.Repositories.Schemas
                                       .GetDescendentRelations(Framework.Security.Model.FixedHiveIds.MasterMemberProfileSchema, FixedRelationTypes.DefaultRelationType);
            var memberTypes = uow.Repositories.Schemas
                              .Get <EntitySchema>(true, memberGroupRelations.Select(x => x.DestinationId).ToArray());
            var memberType = memberTypes.SingleOrDefault(x => x.Alias.Equals(alias, StringComparison.InvariantCultureIgnoreCase));

            if (memberType == null)
            {
                throw new ApplicationException(string.Format("No member type found with the alias '{0}'", alias));
            }

            var compositeMemberType = uow.Repositories.Schemas.GetComposite(memberType);

            member.SetupFromSchema(compositeMemberType);
        }
Exemplo n.º 9
0
        internal RebelMembershipUser GetRebelUser(IGroupUnit <ISecurityStore> uow, HiveId id, bool userIsOnline)
        {
            return(AppContext.FrameworkContext.ScopedCache.GetOrCreateTyped <RebelMembershipUser>(GetRebelUserCacheKeyForId(id), () =>
            {
                // TODO: Enable type of extension method GetEntityByRelationType to be passed all the way to the provider
                // so that it can use the typemappers collection to map back to a User

                // APN: I changed SingleOrDefault to FirstOrDefault to guard against YSODs if somehow a duplicate user gets into the store [31/Jan]
                //var userEntity = uow.Repositories
                //    .GetEntityByRelationType<RebelMembershipUser>(FixedRelationTypes.DefaultRelationType, _virtualRootId)
                //    .SingleOrDefault(x => x.EntitySchema.Alias == MembershipUserSchema.SchemaAlias && x.Username == username);

                // Get a list of all member relations
                var memberRelations = uow.Repositories.GetChildRelations(VirtualRootId, FixedRelationTypes.DefaultRelationType)
                                      .Select(x => x.DestinationId)
                                      .ToList();

                // Get a list of all users / members with a matching id
                var userEntities =
                    uow.Repositories.Where(
                        x => x.EntitySchema.Alias == MembershipUserSchema.SchemaAlias &&
                        x.Id == id).ToList();

                // Get the first matching user with a member relation
                var userEntity = userEntities.FirstOrDefault(x => memberRelations.Any(y => y.Value == x.Id.Value));

                if (userEntity == null)
                {
                    return null;
                }

                var user = new RebelMembershipUser();
                user.SetupFromEntity(userEntity);

                //if (userIsOnline)
                //{
                //    user.LastActivityDate = DateTime.UtcNow;

                //    uow.Repositories.AddOrUpdate(user);
                //    uow.Complete();
                //}

                return user;
            }));
        }
Exemplo n.º 10
0
        public static PackageDefinition GetPackageDefinitionById(IGroupUnit <IFileStore> uow,
                                                                 HiveId id)
        {
            var folder = uow.Repositories.Get <Rebel.Framework.Persistence.Model.IO.File>(id);

            if (folder == null)
            {
                return(null);
            }

            var fileIds        = uow.Repositories.GetChildRelations(folder.Id).Select(x => x.DestinationId).ToArray();
            var files          = uow.Repositories.Get <Rebel.Framework.Persistence.Model.IO.File>(true, fileIds);
            var definitionFile = files.SingleOrDefault(x => x.Name.EndsWith(".definition"));

            if (definitionFile == null)
            {
                return(null);
            }

            var contents = Encoding.UTF8.GetString(definitionFile.ContentBytes);

            if (string.IsNullOrWhiteSpace(contents))
            {
                return(null);
            }
            try
            {
                var def = contents.DeserializeJson <PackageDefinition>();
                def.Id = id;

                return(def);
            }
            catch (global::System.Exception)
            {
                return(null);
            }
        }
Exemplo n.º 11
0
        internal static void CreateThumbnails(IGroupUnit <IFileStore> uow, File original, string mediaId, string thumbSizes = null)
        {
            if (original.IsImage())
            {
                var img = Image.FromStream(new MemoryStream(original.ContentBytes));

                // Create default thumbnail
                CreateThumbnail(uow, original, img, mediaId, 100);

                // Create additional thumbnails
                if (!String.IsNullOrEmpty(thumbSizes))
                {
                    var sizes = thumbSizes.Split(',');
                    foreach (var size in sizes)
                    {
                        var intSize = 0;
                        if (Int32.TryParse(size, out intSize))
                        {
                            CreateThumbnail(uow, original, img, mediaId, intSize);
                        }
                    }
                }
            }
        }
Exemplo n.º 12
0
        internal static void CreateThumbnails(IGroupUnit<IFileStore> uow, File original, string mediaId, string thumbSizes = null)
        {
            if (original.IsImage())
            {
                var img = Image.FromStream(new MemoryStream(original.ContentBytes));

                // Create default thumbnail
                CreateThumbnail(uow, original, img, mediaId, 100);

                // Create additional thumbnails
                if (!String.IsNullOrEmpty(thumbSizes))
                {
                    var sizes = thumbSizes.Split(',');
                    foreach (var size in sizes)
                    {
                        var intSize = 0;
                        if (Int32.TryParse(size, out intSize))
                        {
                            CreateThumbnail(uow, original, img, mediaId, intSize);
                        }
                    }
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates the thumbnail.
        /// </summary>
        /// <param name="uow">The uow.</param>
        /// <param name="original">The original.</param>
        /// <param name="image">The image.</param>
        /// <param name="mediaId">The media id.</param>
        /// <param name="maxWidthHeight">Height of the max width.</param>
        private void CreateThumbnail(IGroupUnit <IFileStore> uow, File original, Image image, string mediaId, int maxWidthHeight)
        {
            var extension     = Path.GetExtension(original.Name).ToLower();;
            var thumbFileName = Path.GetFileNameWithoutExtension(original.Name) + "_" + maxWidthHeight + extension;

            // Create file entity
            var thumb = new File
            {
                RootedPath = mediaId + "/" + thumbFileName
            };

            // Resize image
            var val  = (float)image.Width / (float)maxWidthHeight;
            var val2 = (float)image.Height / (float)maxWidthHeight;

            var num = Math.Max(val, val2);

            var num2 = (int)Math.Round((double)((float)image.Width / num));
            var num3 = (int)Math.Round((double)((float)image.Height / num));

            if (num2 == 0)
            {
                num2 = 1;
            }

            if (num3 == 0)
            {
                num3 = 1;
            }

            using (var bitmap = new Bitmap(num2, num3))
                using (var graphics = Graphics.FromImage(bitmap))
                {
                    graphics.SmoothingMode     = SmoothingMode.HighQuality;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;

                    var destRect = new Rectangle(0, 0, num2, num3);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                    var            imageEncoders = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo encoder       = null;
                    if (extension == ".png" || extension == ".gif")
                    {
                        encoder = imageEncoders.Single(t => t.MimeType.Equals("image/png"));
                    }
                    else
                    {
                        encoder = imageEncoders.Single(t => t.MimeType.Equals("image/jpeg"));
                    }

                    var stream            = new MemoryStream();
                    var encoderParameters = new EncoderParameters();
                    encoderParameters.Param[0] = new EncoderParameter(global::System.Drawing.Imaging.Encoder.Quality, 90L);
                    bitmap.Save(stream, encoder, encoderParameters);

                    thumb.ContentBytes = stream.ToArray();
                }

            // Add or update file
            uow.Repositories.AddOrUpdate(thumb);

            // Create relation
            uow.Repositories.AddRelation(original, thumb, FixedRelationTypes.ThumbnailRelationType, 0, new RelationMetaDatum("size", maxWidthHeight.ToString()));
        }
Exemplo n.º 14
0
        protected virtual void EnsureInheritanceRelations(TEditorModel model, EntitySchema entity, IGroupUnit <IContentStore> uow)
        {
            var currentRelations =
                uow.Repositories.GetParentRelations(entity.Id, FixedRelationTypes.DefaultRelationType).ToArray();

            var selectedInheritFrom =
                model.InheritFrom.Where(
                    x => x.Selected && !model.InheritFrom.Any(y => y.Selected && y.ParentValues.Contains(x.Value))).Select(
                    x => HiveId.Parse(x.Value)).ToArray();

            // Remove relations provided we're not going to remove the only relation to the root
            if (!selectedInheritFrom.Any())
            {
                foreach (var relation in currentRelations.Where(x => x.SourceId != RootSchemaObj.Id))
                {
                    uow.Repositories.RemoveRelation(relation);
                }

                // Ensure we have a relation to the root schema
                uow.Repositories.AddRelation(new Relation(FixedRelationTypes.DefaultRelationType, RootSchemaObj.Id, entity.Id));
            }
            else
            {
                foreach (var relation in currentRelations.Where(x => !selectedInheritFrom.Any(hiveId => hiveId == x.SourceId)))
                {
                    uow.Repositories.RemoveRelation(relation);
                }
            }

            // Go through the selected inheritance and add a relation
            foreach (var id in selectedInheritFrom.Where(id => !currentRelations.Any(y => y.SourceId == id)))
            {
                uow.Repositories.AddRelation(new Relation(FixedRelationTypes.DefaultRelationType, id, entity.Id));
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// When editing or creating a document type, this binds the model, checks for errors, determines which
        /// actions to take based on the button pressed, adds appropriate notifications and persists the data.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        private ActionResult ProcessSubmit(TEditorModel model, EntitySchema entity, IGroupUnit <IContentStore> uow)
        {
            Mandate.ParameterNotNull(model, "model");

            EnsureSelectListData(model);

            //bind the model to the posted values
            model.BindModel(this);

            //process creating a new tab
            ProcessCreatingTab(model);
            //process deleting a tab
            var tabToDelete = ProcessDeletingTab(model);
            //process deleting property
            var propToDelete = ProcessDeletingProperty(model);

            //check if we are NOT adding a new property, if not then remove the invalid required validation
            if (!model.IsCreatingNewProperty)
            {
                foreach (var m in ModelState.Where(x => x.Key.StartsWith("NewProperty")))
                {
                    m.Value.Errors.Clear();
                }
            }

            if (!ModelState.IsValid)
            {
                AddValidationErrorsNotification();
                return(View("Edit", model));
            }

            //convert to persistence entity
            if (entity == null)
            {
                //map to a new entity
                entity = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <TEditorModel, EntitySchema>(model);
            }
            else
            {
                //map to existing
                BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map(model, entity);
            }

            //if we're creating a new property, then add one
            if (model.IsCreatingNewProperty)
            {
                //need to set the ordinal to the max sort order for the properties on the tab its being saved to
                var defsOnGroup = entity.AttributeDefinitions.Where(x => x.AttributeGroup.Id == model.NewProperty.TabId).ToArray();
                var maxOrdinal  = defsOnGroup.Any() ? defsOnGroup.Max(x => x.Ordinal) : 0;


                model.NewProperty.SortOrder = entity.AttributeDefinitions.Any()
                                                  ? maxOrdinal + 1
                                                  : 0;
                var propertyEntity = BackOfficeRequestContext.Application.FrameworkContext.TypeMappers.Map <DocumentTypeProperty, AttributeDefinition>(model.NewProperty);
                entity.AttributeDefinitions.Add(propertyEntity);
            }

            // Manage relations
            EnsureInheritanceRelations(model, entity, uow);

            //Save the entity
            uow.Repositories.Schemas.AddOrUpdate(entity);

            Notifications.Add(new NotificationMessage(
                                  "DocumentType.Save.Message".Localize(this),
                                  "DocumentType.Save.Title".Localize(this),
                                  NotificationType.Success));

            return(RedirectToAction("Edit", new { id = entity.Id }));
        }
Exemplo n.º 16
0
 private UserGroup GetUserGroupByName(string name, IGroupUnit <ISecurityStore> uow)
 {
     return(uow.Repositories.GetEntityByRelationType <UserGroup>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserGroupVirtualRoot)
            .SingleOrDefault(x => x.Name.ToLower() == name.ToLower()));
 }
        internal static User GetUmbracoUser(IGroupUnit<ISecurityStore> uow, HiveId id, bool userIsOnline)
        {
            var user = uow.Repositories
                .GetEntityByRelationType<User>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserVirtualRoot)
                .SingleOrDefault(x => x.Id.Value == id.Value);
            //.SingleOrDefault(x => x.Id.ToString(HiveIdFormatStyle.AsUri) == id.ToString(HiveIdFormatStyle.AsUri));
            //Had to change this comparison to use values because the Uri portion wont work with the membership wrapper provider because the 
            //underlying membership providers dont know anything about a URI, therefore teh wrapper only passes in the value portion of the HiveId. SD. 28/11/2011
            

            if (user == null) return null;

            if (userIsOnline)
            {
                user.LastActivityDate = DateTime.UtcNow;

                uow.Repositories.AddOrUpdate(user);
                uow.Complete();
            }

            return user;
        }
        internal static User GetUmbracoUser(IUmbracoApplicationContext appContext, IGroupUnit<ISecurityStore> uow, string username, bool userIsOnline)
        {
            // TODO: Enable type of extension method GetEntityByRelationType to be passed all the way to the provider
            // so that it can use the typemappers collection to map back to a User

            // APN: I changed SingleOrDefault to FirstOrDefault to guard against YSODs if somehow a duplicate user gets into the store [31/Jan]
            var userEntity = uow.Repositories
                .GetEntityByRelationType<TypedEntity>(
                    FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserVirtualRoot)
                .FirstOrDefault(x => x.Attribute<string>(UserSchema.UsernameAlias) == username);


            if (userEntity == null) return null;

            var user = new User();
            user.SetupFromEntity(userEntity);

            if (userIsOnline)
            {
                user.LastActivityDate = DateTime.UtcNow;

                uow.Repositories.AddOrUpdate(user);
                uow.Complete();
            }

            return user;
        }
        internal UmbracoMembershipUser GetUmbracoUser(IGroupUnit<ISecurityStore> uow, HiveId id, bool userIsOnline)
        {
            return AppContext.FrameworkContext.ScopedCache.GetOrCreateTyped<UmbracoMembershipUser>(GetUmbracoUserCacheKeyForId(id), () =>
            {
                // TODO: Enable type of extension method GetEntityByRelationType to be passed all the way to the provider
                // so that it can use the typemappers collection to map back to a User

                // APN: I changed SingleOrDefault to FirstOrDefault to guard against YSODs if somehow a duplicate user gets into the store [31/Jan]
                //var userEntity = uow.Repositories
                //    .GetEntityByRelationType<UmbracoMembershipUser>(FixedRelationTypes.DefaultRelationType, _virtualRootId)
                //    .SingleOrDefault(x => x.EntitySchema.Alias == MembershipUserSchema.SchemaAlias && x.Username == username);

                // Get a list of all member relations
                var memberRelations = uow.Repositories.GetChildRelations(VirtualRootId, FixedRelationTypes.DefaultRelationType)
                    .Select(x => x.DestinationId)
                    .ToList();

                // Get a list of all users / members with a matching id
                var userEntities =
                    uow.Repositories.Where(
                        x => x.EntitySchema.Alias == MembershipUserSchema.SchemaAlias
                            && x.Id == id).ToList();

                // Get the first matching user with a member relation
                var userEntity = userEntities.FirstOrDefault(x => memberRelations.Any(y => y.Value == x.Id.Value));

                if (userEntity == null) return null;

                var user = new UmbracoMembershipUser();
                user.SetupFromEntity(userEntity);

                //if (userIsOnline)
                //{
                //    user.LastActivityDate = DateTime.UtcNow;

                //    uow.Repositories.AddOrUpdate(user);
                //    uow.Complete();
                //}

                return user;
            });
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates a deep copy of an object and adds the copied children to the repository. Does not add the root duplicate to the repo, the caller should do this.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="original">The original.</param>
        /// <param name="newParent">The new parent.</param>
        /// <param name="relationType">Type of the relation.</param>
        /// <param name="ordinal">The ordinal.</param>
        /// <param name="unitOfWork">The unit of work.</param>
        /// <param name="metaData">The meta data.</param>
        /// <returns></returns>
        public static T CreateDeepCopyToNewParentInRepo <T>(this T original, IRelatableEntity newParent, AbstractRelationType relationType, int ordinal, IGroupUnit <IProviderTypeFilter> unitOfWork, params RelationMetaDatum[] metaData)
            where T : TypedEntity, new()
        {
            Mandate.ParameterNotNull(newParent, "newParent");
            Mandate.ParameterNotNull(relationType, "relationType");

            var copy = CreateCopyAndEnlistChildren(original, unitOfWork);

            // We've been given a new parent so add that to the copied item's relatinproxies
            copy.RelationProxies.EnlistParent(newParent, relationType, ordinal, metaData);

            return(copy);
        }
 private IEnumerable<UserGroup> GetUserGroupsByName(string[] names, IGroupUnit<ISecurityStore> uow)
 {
     return uow.Repositories.GetEntityByRelationType<UserGroup>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserGroupVirtualRoot)
         .Where(x => names.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase))
         .ToArray();
 }
 private UserGroup GetUserGroupByName(string name, IGroupUnit<ISecurityStore> uow)
 {
     return uow.Repositories.GetEntityByRelationType<UserGroup>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserGroupVirtualRoot)
             .SingleOrDefault(x => x.Name.ToLower() == name.ToLower());
 }
Exemplo n.º 23
0
        internal static void CreateThumbnail(IGroupUnit<IFileStore> uow, File original, Image image, string mediaId, int maxWidthHeight)
        {
            var extension = Path.GetExtension(original.Name).ToLower();
            var thumbFileName = Path.GetFileNameWithoutExtension(original.Name) + "_" + maxWidthHeight + extension;

            // Create file entity
            var thumb = new File
                            {
                                RootedPath = mediaId + "/" + thumbFileName             
                            };

            // Resize image
            var val = (float)image.Width / (float)maxWidthHeight;
            var val2 = (float)image.Height / (float)maxWidthHeight;

            var num = Math.Max(val, val2);

            var num2 = (int)Math.Round((double)((float)image.Width / num));
            var num3 = (int)Math.Round((double)((float)image.Height / num));

            if (num2 == 0)
            {
                num2 = 1;
            }

            if (num3 == 0)
            {
                num3 = 1;
            }

            using(var bitmap = new Bitmap(num2, num3))
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                var destRect = new Rectangle(0, 0, num2, num3);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                var imageEncoders = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo encoder = null;
                if (extension == ".png" || extension == ".gif")
                    encoder = imageEncoders.Single(t => t.MimeType.Equals("image/png"));
                else
                    encoder = imageEncoders.Single(t => t.MimeType.Equals("image/jpeg"));

                var stream = new MemoryStream();
                var encoderParameters = new EncoderParameters();
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 90L);
                bitmap.Save(stream, encoder, encoderParameters);

                thumb.ContentBytes = stream.ToArray();
            }

            // Add or update file
            uow.Repositories.AddOrUpdate(thumb);

            // Create relation
            uow.Repositories.AddRelation(original, thumb, FixedRelationTypes.ThumbnailRelationType, 0, new RelationMetaDatum("size", maxWidthHeight.ToString()));
        }
        internal UmbracoMembershipUser GetUmbracoUser(IGroupUnit<ISecurityStore> uow, string username, bool userIsOnline)
        {
            return AppContext.FrameworkContext.ScopedCache.GetOrCreateTyped<UmbracoMembershipUser>(GetUmbracoUserCacheKeyForUsername(username), () =>
            {
                // Use FirstOrDefault in case somehow a duplicate user got into the system
                var matchingUsers = uow.Repositories
                    .WithParentIds(FixedRelationTypes.DefaultRelationType, VirtualRootId)
                    .Where(
                        x =>
                        x.EntitySchema.Alias == MembershipUserSchema.SchemaAlias &&
                        x.Attribute<string>(MembershipUserSchema.UsernameAlias) == username)
                    .OrderByDescending(x => x.UtcCreated)
                    .FirstOrDefault();

                if (matchingUsers == null) return null;

                var user = new UmbracoMembershipUser();
                user.SetupFromEntity(matchingUsers);

                //if (userIsOnline)
                //{
                //    user.LastActivityDate = DateTime.UtcNow;

                //    uow.Repositories.AddOrUpdate(user);
                //    uow.Complete();
                //}

                return user;
            });
        }
Exemplo n.º 25
0
 private IEnumerable <UserGroup> GetUserGroupsByName(string[] names, IGroupUnit <ISecurityStore> uow)
 {
     return(uow.Repositories.GetEntityByRelationType <UserGroup>(FixedRelationTypes.DefaultRelationType, FixedHiveIds.UserGroupVirtualRoot)
            .Where(x => names.Contains(x.Name, StringComparer.InvariantCultureIgnoreCase))
            .ToArray());
 }