/// <summary>
        /// Populates the EntityViewModel object's properties from the given CommunityDetails object's properties.
        /// </summary>
        /// <param name="thisObject">Current entity view model on which the extension method is called</param>
        /// <param name="communityDetails">CommunityDetails model from which values to be read</param>
        /// <returns>Values populated EntityViewModel instance</returns>
        public static EntityViewModel SetValuesFrom(this EntityViewModel thisObject, CommunityDetails communityDetails)
        {
            if (communityDetails != null)
            {
                if (thisObject == null)
                {
                    thisObject = new EntityViewModel();
                }

                thisObject.Entity = communityDetails.CommunityType == CommunityTypes.Community ? EntityType.Community : EntityType.Folder;

                // Populate the base values using the EntityViewModel's SetValuesFrom method which take EntityDetails as input.
                thisObject.SetValuesFrom(communityDetails as EntityDetails);
            }

            return thisObject;
        }
예제 #2
0
        private IEnumerable<CommunityDetails> GetCommunityDetails(EntityHighlightFilter entityHighlightFilter, PageDetails pageDetails)
        {
            var orderBy = GetCommunityOrderByClause(entityHighlightFilter);
            var condition = GetCommunityConditionClause(entityHighlightFilter);

            // Gets the total items satisfying the
            var totalItemsForCondition = _communitiesViewRepository.GetItemsCount(condition);

            // If TotalCount is already specified in pageDetails, need to consider that. Ignore even if there are more items in the DB.
            if (pageDetails.TotalCount > 0 && totalItemsForCondition > pageDetails.TotalCount)
            {
                totalItemsForCondition = pageDetails.TotalCount;
            }

            pageDetails.TotalPages = (totalItemsForCondition / pageDetails.ItemsPerPage) + ((totalItemsForCondition % pageDetails.ItemsPerPage == 0) ? 0 : 1);

            IEnumerable<CommunitiesView> communities = null;

            // Only for Popular/Top Rated, there is multiple order by which needs to added here.
            if (entityHighlightFilter.HighlightType == HighlightType.Popular)
            {
                // TODO: This is a temporary fix, since multiple order by cannot be passed.
                // Need to do this in a better way, instead of getting all the items.
                communities =   _communitiesViewRepository.GetItems(condition, null, true);
                communities = communities.OrderByDescending(c => c.AverageRating).ThenByDescending(c => c.RatedPeople)
                                .Skip((pageDetails.CurrentPage - 1) * pageDetails.ItemsPerPage)
                                .Take(pageDetails.ItemsPerPage).ToList();
            }
            else
            {
                communities =  _communitiesViewRepository.GetItems(condition, orderBy, true, (pageDetails.CurrentPage - 1) * pageDetails.ItemsPerPage, pageDetails.ItemsPerPage);
            }

            var communityDetails = new List<CommunityDetails>();
            if (communities != null)
            {
                foreach (var community in communities)
                {
                    var communityDetail = new CommunityDetails();

                    // Some of the values which comes from complex objects need to be set through this method.
                    Mapper.Map(community, communityDetail);

                    communityDetails.Add(communityDetail);
                }
            }

            return communityDetails;
        }
예제 #3
0
        /// <summary>
        /// Retrieves the sub communities of a given community. This only retrieves the immediate children.
        /// </summary>
        /// <param name="communityId">ID of the community.</param>
        /// <param name="userId">Id of the user who is accessing</param>
        /// <param name="pageDetails">Details about the pagination</param>
        /// <param name="onlyItemCount">To get only item count, not the entities. When community details page is loaded first time, 
        /// no need to get the communities, only count is enough.</param>
        /// <returns>Collection of sub communities</returns>
        public IEnumerable<CommunityDetails> GetSubCommunities(long communityId, long userId, PageDetails pageDetails, bool onlyItemCount)
        {
            this.CheckNotNull(() => new { pageDetails });

            IList<CommunityDetails> subCommunities = new List<CommunityDetails>();

            var subCommunityIDs = _communityRepository.GetSubCommunityIDs(communityId, userId);

            // Gets the total number of direct sub communities of the community
            pageDetails.TotalCount = subCommunityIDs.Count();

            pageDetails.TotalPages = (pageDetails.TotalCount / pageDetails.ItemsPerPage) + ((pageDetails.TotalCount % pageDetails.ItemsPerPage == 0) ? 0 : 1);

            // When community details page is loaded first time, no need to get the communities, only count is enough.
            if (!onlyItemCount && subCommunityIDs != null && subCommunityIDs.Count() > 0)
            {
                subCommunityIDs = subCommunityIDs.Skip((pageDetails.CurrentPage - 1) * pageDetails.ItemsPerPage).Take(pageDetails.ItemsPerPage);
                foreach (var community in _communityRepository.GetItems(subCommunityIDs))
                {
                    var userRole = _userRepository.GetUserRole(userId, community.CommunityID);
                    var communityDetails = new CommunityDetails(userRole.GetPermission());

                    // Some of the values which comes from complex objects need to be set through this method.
                    communityDetails.SetValuesFrom(community);

                    subCommunities.Add(communityDetails);
                }
            }

            return subCommunities;
        }
예제 #4
0
        private void SendNewCommunityMail(CommunityDetails communityDetails, string server)
        {
            try
            {
                // Send Mail.
                var request = new NewEntityRequest();
                request.EntityType = communityDetails.CommunityType == CommunityTypes.Community ? EntityType.Community : EntityType.Folder;
                request.EntityID = communityDetails.ID;
                request.EntityName = communityDetails.Name;
                request.EntityLink = string.Format(CultureInfo.InvariantCulture, "{0}Community/Index/{1}", server, communityDetails.ID);
                request.UserID = communityDetails.CreatedByID;
                request.UserLink = string.Format(CultureInfo.InvariantCulture, "{0}Profile/Index/{1}", server, communityDetails.CreatedByID);

                SendMail(request);
            }
            catch (Exception)
            {
                // Ignore all exceptions.
            }
        }
예제 #5
0
        public async Task<ActionResult> New(CommunityInputViewModel communityJson)
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext(_communityService, _notificationService);
            }

            if (ModelState.IsValid)
            {
                var communityDetails = new CommunityDetails();
                Mapper.Map(communityJson, communityDetails);

                // Set thumbnail properties
                communityDetails.Thumbnail = new FileDetail() { AzureID = communityJson.ThumbnailID };
                communityDetails.CreatedByID = CurrentUserId;
                communityJson.ID = communityDetails.ID = _communityService.CreateCommunity(communityDetails);

                // Send Notification Mail
                _notificationService.NotifyNewEntityRequest(communityDetails, HttpContext.Request.Url.GetServerLink());

                return new JsonResult { Data = new { ID = communityDetails.ID } };
            }
            
            // In case of any validation error stay in the same page.
            return new JsonResult { Data = false };
        }
예제 #6
0
        public long CreateCommunity(CommunityDetails communityDetail)
        {
            // Make sure communityDetails is not null
            this.CheckNotNull(() => new { communityDetails = communityDetail });

            var userRole = GetCommunityUserRole(communityDetail.ParentID, communityDetail.CreatedByID);
            if (!CanCreateCommunity(communityDetail.ParentID, userRole))
            {
                throw new HttpException(401, Resources.NoPermissionCreateCommunityMessage);
            }

            // In case if the community getting created is "User" type, check that the same user already has a "User" community associated with him.
            // There should be only one "User" community to be created per user.
            if (communityDetail.CommunityType == CommunityTypes.User)
            {
                var existingUserCommunity = _communityRepository.GetItem(
                    c => c.CommunityTypeID == (int) CommunityTypes.User && c.CreatedByID == communityDetail.CreatedByID);

                if (existingUserCommunity != null)
                {
                    return existingUserCommunity.CommunityID;
                }
            }

            // 1. Add Community details to the community object.
            var community = new Community();
            Mapper.Map(communityDetail, community);

            // While creating the community, IsDeleted to be false always.
            community.IsDeleted = false;

            community.CreatedDatetime = community.ModifiedDatetime = DateTime.UtcNow;

            // 2. Add Thumbnail to blob
            if (communityDetail.Thumbnail != null && communityDetail.Thumbnail.AzureID != Guid.Empty)
            {
                if (MoveThumbnail(communityDetail.Thumbnail))
                {
                    community.ThumbnailID = communityDetail.Thumbnail.AzureID;
                }
            }

            // 3. Add Tag details. This will also take care of creating tags if they are not there in the Layerscape database.
            SetCommunityTags(communityDetail.Tags, community);

            var parentAddedToUserRole = false;
            if (communityDetail.ParentID > 0)
            {
                // 4. Add Parent Community details
                var communityRelation = new CommunityRelation
                {
                    ParentCommunityID = communityDetail.ParentID,
                    ChildCommunityID = communityDetail.ID
                };

                // TODO: Need to rename the Data Model property CommunityRelation1 with a more meaningful name.
                // Note that the relation to be added is to CommunityRelation1 since the current Community is Child.
                // When the current community is parent, it's relation to be added in CommunityRelation.
                community.CommunityRelation1.Add(communityRelation);

                var parentCommunity = _communityRepository.GetItem(c => c.CommunityID == communityDetail.ParentID);
                if (parentCommunity != null && parentCommunity.UserCommunities.Count > 0)
                {
                    parentCommunity.ModifiedByID = communityDetail.CreatedByID;
                    parentCommunity.ModifiedDatetime = DateTime.UtcNow;

                    // 5. Inherit Parent Permission Details
                    foreach (var communityUserRole in parentCommunity.UserCommunities)
                    {
                        var userCommunityRole = new UserCommunities
                        {
                            CommunityId = communityDetail.ID,
                            UserID = communityUserRole.UserID,
                            RoleID = communityUserRole.RoleID,
                            IsInherited = true,
                            CreatedDatetime = DateTime.UtcNow
                        };

                        // Add the current community to the use role

                        // Add the existing users along with their roles

                        community.UserCommunities.Add(userCommunityRole);

                        if (communityUserRole.UserID == communityDetail.CreatedByID)
                        {
                            parentAddedToUserRole = true;
                        }
                    }
                }
            }

            if (!parentAddedToUserRole)
            {
                // 6. Add Owner Permission Details only if its not already inherited.
                var userCommunity = new UserCommunities
                {
                    CommunityId = communityDetail.ID,
                    UserID = communityDetail.CreatedByID,
                    CreatedDatetime = DateTime.UtcNow,
                    RoleID = (int) UserRole.Owner,
                    IsInherited = false
                };

                // User who is creating the community is the owner.
                community.UserCommunities.Add(userCommunity);
            }

            // Add the community to the repository
            _communityRepository.Add(community);

            // Save all the changes made.
            _communityRepository.SaveChanges();

            return community.CommunityID;
        }
예제 #7
0
        /// <summary>
        /// Creates the private community details for the given community. User id is used to check if the user is having any
        /// pending requests on the private community.
        /// </summary>
        /// <param name="community">Community for which private community details has to be created</param>
        /// <param name="userId">Current user id</param>
        /// <returns>Community details instance</returns>
        private CommunityDetails CreatePrivateCommunityDetails(Community community, long? userId)
        {
            CommunityDetails communityDetails = null;

            var permission = Permission.Visitor;

            // Check if already any pending approvals are there.
            if (userId.HasValue && _userRepository.PendingPermissionRequests(userId.Value, community.CommunityID))
            {
                permission = Permission.PendingApproval;
            }

            communityDetails = new CommunityDetails(permission);
            communityDetails.ID = community.CommunityID;
            communityDetails.Name = community.Name;
            communityDetails.Description = community.Description;
            communityDetails.AccessTypeID = (int)AccessType.Private;
            communityDetails.CommunityType = (CommunityTypes)community.CommunityTypeID;

            // Set Thumbnail properties.
            var thumbnailDetail = new FileDetail();
            thumbnailDetail.AzureID = community.ThumbnailID.HasValue ? community.ThumbnailID.Value : Guid.Empty;
            communityDetails.Thumbnail = thumbnailDetail;

            return communityDetails;
        }
예제 #8
0
        /// <summary>
        /// Creates default user community.
        /// </summary>
        /// <param name="userId">User identity.</param>
        private void CreateDefaultUserCommunity(long userId)
        {
            // This will used as the default community when user is uploading a new content.
            // This community will need to have the following details:
            var communityDetails = new CommunityDetails();

            // 1. This community type should be User
            communityDetails.CommunityType = CommunityTypes.User;

            // 2. CreatedBy will be the new USER.
            communityDetails.CreatedByID = userId;

            // 3. This community is not featured.
            communityDetails.IsFeatured = false;

            // 4. Name should be NONE.
            communityDetails.Name = Resources.UserCommunityName;

            // 5. Access type should be private.
            communityDetails.AccessTypeID = (int)AccessType.Private;

            // 6. Set the category ID of general interest. We need to set the Category ID as it is a foreign key and cannot be null.
            communityDetails.CategoryID = (int)CategoryType.GeneralInterest;

            // 7. Create the community
            _communityService.CreateCommunity(communityDetails);
        }
        private long CreateCollection(string filename, Stream fileContent, ProfileDetails profileDetails, CommunityDetails parentCommunity)
        {
            // Get name/ tags/ category from Tour.
            var collectionDoc = new XmlDocument();
            ContentDetails content = null;

            // NetworkStream is not Seek able. Need to load into memory stream so that it can be sought
            using (Stream writablefileContent = new MemoryStream())
            {
                fileContent.CopyTo(writablefileContent);
                writablefileContent.Position = 0;
                content = GetContentDetail(filename, writablefileContent, profileDetails, parentCommunity);
                writablefileContent.Seek(0, SeekOrigin.Begin);
                collectionDoc = collectionDoc.SetXmlFromWtml(writablefileContent);
            }

            if (collectionDoc != null)
            {
                content.Name = collectionDoc.GetAttributeValue("Folder", "Name");
            }

            var contentService = DependencyResolver.Current.GetService(typeof(IContentService)) as IContentService;
            var contentId = content.ID = contentService.CreateContent(content);

            if (contentId > 0)
            {
                var notificationService = DependencyResolver.Current.GetService(typeof(INotificationService)) as INotificationService;
                notificationService.NotifyNewEntityRequest(content, BaseUri() + "/");
            }

            return contentId;
        }
        private ContentDetails GetContentDetail(string filename, Stream fileContent, ProfileDetails profileDetails, CommunityDetails parentCommunity)
        {
            var content = new ContentDetails();

            var fileDetail = UpdateFileDetails(filename, fileContent);

            content.ContentData = fileDetail;
            content.CreatedByID = profileDetails.ID;

            // By Default the access type will be private.
            content.AccessTypeID = (int)AccessType.Public;

            // Get the Category/Tags from Parent.
            content.ParentID = parentCommunity.ID;
            content.ParentType = parentCommunity.CommunityType;
            content.CategoryID = parentCommunity.CategoryID;

            return content;
        }
        private long CreateTour(string filename, Stream fileContent, ProfileDetails profileDetails, CommunityDetails parentCommunity)
        {
            var tourDoc = new XmlDocument();
            ContentDetails content = null;

            // NetworkStream is not Seek able. Need to load into memory stream so that it can be sought
            using (Stream writablefileContent = new MemoryStream())
            {
                fileContent.CopyTo(writablefileContent);
                writablefileContent.Position = 0;
                content = GetContentDetail(filename, writablefileContent, profileDetails, parentCommunity);
                writablefileContent.Position = 0;
                tourDoc = tourDoc.SetXmlFromTour(writablefileContent);
            }

            if (tourDoc != null)
            {
                // Note that the spelling of Description is wrong because that's how WWT generates the WTT file.
                content.Name = tourDoc.GetAttributeValue("Tour", "Title");
                content.Description = tourDoc.GetAttributeValue("Tour", "Descirption");
                content.DistributedBy = tourDoc.GetAttributeValue("Tour", "Author");
                content.TourLength = tourDoc.GetAttributeValue("Tour", "RunTime");
            }

            var contentService = DependencyResolver.Current.GetService(typeof(IContentService)) as IContentService;
            var contentId = content.ID = contentService.CreateContent(content);

            if (contentId > 0)
            {
                var notificationService = DependencyResolver.Current.GetService(typeof(INotificationService)) as INotificationService;
                notificationService.NotifyNewEntityRequest(content, BaseUri() + "/");
            }

            return contentId;
        }
        private long CreateContent(string filename, Stream fileContent, ProfileDetails profileDetails, CommunityDetails parentCommunity)
        {
            ContentDetails content = null;

            // No need to get into a memory stream as the stream is sent as is and need not be loaded
            using (Stream writablefileContent = new MemoryStream())
            {
                fileContent.CopyTo(writablefileContent);
                writablefileContent.Position = 0;
                content = GetContentDetail(filename, writablefileContent, profileDetails, parentCommunity);
                content.Name = Path.GetFileNameWithoutExtension(filename);
            }

            var contentService = DependencyResolver.Current.GetService(typeof(IContentService)) as IContentService;
            var contentId = content.ID = contentService.CreateContent(content);

            if (contentId > 0)
            {
                var notificationService = DependencyResolver.Current.GetService(typeof(INotificationService)) as INotificationService;
                notificationService.NotifyNewEntityRequest(content, BaseUri() + "/");
            }

            return contentId;
        }
        public async Task<bool> RegisterUser()
        {
            var profileDetails = await ValidateAuthentication();

            if (profileDetails == null)
            {
                var svc = new LiveIdAuth();
                dynamic jsonResult = svc.GetMeInfo(System.Web.HttpContext.Current.Request.Headers["LiveUserToken"]);
                profileDetails = new ProfileDetails(jsonResult);
                // While creating the user, IsSubscribed to be true always.
                profileDetails.IsSubscribed = true;

                // When creating the user, by default the user type will be of regular. 
                profileDetails.UserType = UserTypes.Regular;
                profileDetails.ID = ProfileService.CreateProfile(profileDetails);
                    
                // This will used as the default community when user is uploading a new content.
                // This community will need to have the following details:
                var communityDetails = new CommunityDetails
                {
                    CommunityType = CommunityTypes.User,// 1. This community type should be User
                    CreatedByID = profileDetails.ID,// 2. CreatedBy will be the new USER.
                    IsFeatured = false,// 3. This community is not featured.
                    Name = Resources.UserCommunityName,// 4. Name should be NONE.
                    AccessTypeID = (int) AccessType.Private,// 5. Access type should be private.
                    CategoryID = (int) CategoryType.GeneralInterest// 6. Set the category ID of general interest. We need to set the Category ID as it is a foreign key and cannot be null.
                };

                // 7. Create the community
                _communityService.CreateCommunity(communityDetails);

                // Send New user notification.
                _notificationService.NotifyNewEntityRequest(profileDetails,
                    HttpContext.Request.Url.GetServerLink());
            }
            else
            {
                throw new WebFaultException<string>("User already registered", HttpStatusCode.BadRequest);
            } 
            return true;
        }
예제 #14
0
        private IEnumerable<CommunityDetails> GetFeaturedCommunityDetails(EntityHighlightFilter entityHighlightFilter, PageDetails pageDetails)
        {
            Func<FeaturedCommunitiesView, object> orderBy = c => c.SortOrder;
            var condition = GetFeaturedCommunitiesCondition(entityHighlightFilter);

            // Gets the total items satisfying the
            var totalItemsForCondition = _featuredCommunitiesViewRepository.GetItemsCount(condition);

            // If TotalCount is already specified in pageDetails, need to consider that. Ignore even if there are more items in the DB.
            if (pageDetails.TotalCount > 0 && totalItemsForCondition > pageDetails.TotalCount)
            {
                totalItemsForCondition = pageDetails.TotalCount;
            }

            pageDetails.TotalPages = (totalItemsForCondition / pageDetails.ItemsPerPage) + ((totalItemsForCondition % pageDetails.ItemsPerPage == 0) ? 0 : 1);

            IEnumerable<FeaturedCommunitiesView> communities = null;

            communities =  _featuredCommunitiesViewRepository.GetItems(condition, orderBy, false, (pageDetails.CurrentPage - 1) * pageDetails.ItemsPerPage, pageDetails.ItemsPerPage);

            var communityDetails = new List<CommunityDetails>();
            if (communities != null)
            {
                foreach (var community in communities)
                {
                    var communityDetail = new CommunityDetails();

                    // Some of the values which comes from complex objects need to be set through this method.
                    Mapper.Map(community, communityDetail);

                    communityDetails.Add(communityDetail);
                }
            }

            return communityDetails;
        }
예제 #15
0
        public IEnumerable<CommunityDetails> GetCommunities(long userId, PageDetails pageDetails, bool onlyPublic)
        {
            this.CheckNotNull(() => new { userID = userId, pageDetails });

            IList<CommunityDetails> userCommunities = new List<CommunityDetails>();

            Func<CommunitiesView, object> orderBy = c => c.LastUpdatedDatetime;

            // Get all the community ids to which user is given role of contributor or higher.
            var userCommunityIds = _userRepository.GetUserCommunitiesForRole(userId, UserRole.Contributor, onlyPublic);

            // Get only the communities for the current page.
            userCommunityIds = userCommunityIds.Skip((pageDetails.CurrentPage - 1) * pageDetails.ItemsPerPage).Take(pageDetails.ItemsPerPage);

            Expression<Func<CommunitiesView, bool>> condition = c => userCommunityIds.Contains(c.CommunityID);

            foreach (var community in _communitiesViewRepository.GetItems(condition, orderBy, true))
            {
                CommunityDetails communityDetails;
                if (onlyPublic)
                {
                    // In case of only public, user is looking at somebody else profile and so just send the user role as Visitor.
                    communityDetails = new CommunityDetails(Permission.Visitor);
                }
                else
                {
                    var userRole = _userRepository.GetUserRole(userId, community.CommunityID);
                    communityDetails = new CommunityDetails(userRole.GetPermission());
                }

                Mapper.Map(community, communityDetails);
                userCommunities.Add(communityDetails);
            }

            return userCommunities;
        }
예제 #16
0
        /// <summary>
        /// Gets the Related Community details for the given community.
        /// </summary>
        /// <param name="entityHighlightFilter">Filters needed while retrieving collection of entities</param>
        /// <param name="pageDetails">Details about the pagination</param>
        /// <returns>Collection of related communities</returns>
        private IEnumerable<CommunityDetails> GetRelatedCommunityDetails(EntityHighlightFilter entityHighlightFilter, PageDetails pageDetails)
        {
            var userId = entityHighlightFilter.EntityId.HasValue ? entityHighlightFilter.EntityId.Value : 0;

            var relatedCommunityIds = _communityTagsRepository.GetRelatedCommunityIDs(userId, entityHighlightFilter.UserID);

            var condition = GetRelatedCommunitiesCondition(relatedCommunityIds);

            // Gets the total items satisfying the
            var totalItemsForCondition = _communitiesViewRepository.GetItemsCount(condition);

            // If TotalCount is already specified in pageDetails, need to consider that. Ignore even if there are more items in the DB.
            if (pageDetails.TotalCount > 0 && totalItemsForCondition > pageDetails.TotalCount)
            {
                totalItemsForCondition = pageDetails.TotalCount;
            }

            pageDetails.TotalPages = (totalItemsForCondition / pageDetails.ItemsPerPage) + ((totalItemsForCondition % pageDetails.ItemsPerPage == 0) ? 0 : 1);

            IEnumerable<CommunitiesView> communities = null;

            relatedCommunityIds = relatedCommunityIds.Skip((pageDetails.CurrentPage - 1) * pageDetails.ItemsPerPage).Take(pageDetails.ItemsPerPage);
            condition = GetRelatedCommunitiesCondition(relatedCommunityIds);

            communities =  _communitiesViewRepository.GetItems(condition, null, false);

            var communityDetails = new List<CommunityDetails>();
            if (communities != null)
            {
                foreach (var communityId in relatedCommunityIds)
                {
                    var communityDetail = new CommunityDetails();
                    var community = communities.Where(c => c.CommunityID == communityId).FirstOrDefault();

                    // Some of the values which comes from complex objects need to be set through this method.
                    Mapper.Map(community, communityDetail);

                    communityDetails.Add(communityDetail);
                }
            }

            return communityDetails;
        }
예제 #17
0
        protected async Task<LiveLoginResult> TryAuthenticateFromHttpContext(ICommunityService communityService, INotificationService notificationService)
        {
            var svc = new LiveIdAuth();
            var result = await svc.Authenticate();
            if (result.Status == LiveConnectSessionStatus.Connected)
            {
                var client = new LiveConnectClient(result.Session);
                SessionWrapper.Set("LiveConnectClient", client);
                SessionWrapper.Set("LiveConnectResult", result);
                SessionWrapper.Set("LiveAuthSvc", svc);

                var getResult = await client.GetAsync("me");
                var jsonResult = getResult.Result as dynamic;
                var profileDetails = ProfileService.GetProfile(jsonResult.id);
                if (profileDetails == null)
                {
                    profileDetails = new ProfileDetails(jsonResult);
                    // While creating the user, IsSubscribed to be true always.
                    profileDetails.IsSubscribed = true;

                    // When creating the user, by default the user type will be of regular. 
                    profileDetails.UserType = UserTypes.Regular;
                    profileDetails.ID = ProfileService.CreateProfile(profileDetails);

                    // This will used as the default community when user is uploading a new content.
                    // This community will need to have the following details:
                    var communityDetails = new CommunityDetails
                    {
                        CommunityType = CommunityTypes.User, // 1. This community type should be User
                        CreatedByID = profileDetails.ID, // 2. CreatedBy will be the new USER.
                        IsFeatured = false, // 3. This community is not featured.
                        Name = Resources.UserCommunityName, // 4. Name should be NONE.
                        AccessTypeID = (int) AccessType.Private, // 5. Access type should be private.
                        CategoryID = (int) CategoryType.GeneralInterest
                        // 6. Set the category ID of general interest. We need to set the Category ID as it is a foreign key and cannot be null.
                    };

                    // 7. Create the community
                    communityService.CreateCommunity(communityDetails);

                    // Send New user notification.
                    notificationService.NotifyNewEntityRequest(profileDetails,
                        HttpContext.Request.Url.GetServerLink());
                }

                SessionWrapper.Set<long>("CurrentUserID", profileDetails.ID);
                SessionWrapper.Set<string>("CurrentUserProfileName",
                    profileDetails.FirstName + " " + profileDetails.LastName);
                SessionWrapper.Set("ProfileDetails", profileDetails);
                SessionWrapper.Set("AuthenticationToken", result.Session.AuthenticationToken);
            }
            return result;
        }
예제 #18
0
        /// <summary>
        /// Creates the community details for the given community. User id is used to check the user role
        /// on the community,based on that, CommunityDetails might be null in case is user is not having permission.
        /// </summary>
        /// <param name="community">Community for which community details has to be created</param>
        /// <param name="userId">Current user id</param>
        /// <param name="checkPendingRequest">Check for pending requests of the user</param>
        /// <returns>Community details instance</returns>
        private CommunityDetails CreateCommunityDetails(Community community, long? userId, bool checkPendingRequest)
        {
            CommunityDetails communityDetails = null;

            if (community != null)
            {
                Permission permission;
                var userRole = GetCommunityUserRole(community.CommunityID, userId);

                if (!CanReadCommunity(userRole))
                {
                    throw new HttpException(401, Resources.NoPermissionReadCommunityMessage);
                }

                permission = userRole.GetPermission();

                // 1. For visitors (not assigned any roles for the community) who are logged in, need to find if any role request is pending approval.
                // 2. Pending approval is needed only for community details, not to be added in other places.
                if (checkPendingRequest &&
                        userRole == UserRole.Visitor &&
                        userId.HasValue &&
                        _userRepository.PendingPermissionRequests(userId.Value, community.CommunityID))
                {
                    permission = Permission.PendingApproval;
                }

                communityDetails = new CommunityDetails(permission);

                // Some of the values which comes from complex objects need to be set through this method.
                communityDetails.SetValuesFrom(community);

                communityDetails.ViewCount = community.ViewCount.HasValue ? community.ViewCount.Value : 0;

                // Update parent details based on the permission.
                var parent = Enumerable.FirstOrDefault(community.CommunityRelation1);
                if (parent != null && parent.Community != null)
                {
                    var parentUserRole = GetCommunityUserRole(parent.Community.CommunityID, userId);

                    if (!CanReadCommunity(parentUserRole))
                    {
                        communityDetails.ParentName = string.Empty;
                        communityDetails.ParentID = -1;
                        communityDetails.ParentType = CommunityTypes.None;
                    }
                }
            }

            return communityDetails;
        }
예제 #19
0
        private IEnumerable<CommunityDetails> GetAllFeaturedCommunities(EntityHighlightFilter entityHighlightFilter)
        {
            Func<FeaturedCommunitiesView, object> orderBy = c => c.SortOrder;

            Expression<Func<FeaturedCommunitiesView, bool>> condition = condition = c => c.FeaturedCategoryID == (int)entityHighlightFilter.CategoryType
                    && (c.CommunityTypeID == (int)CommunityTypes.Community || c.CommunityTypeID == (int)CommunityTypes.Folder);

            var communities =  _featuredCommunitiesViewRepository.GetItems(condition, orderBy, false);

            var communityDetails = new List<CommunityDetails>();
            if (communities != null)
            {
                foreach (var community in communities)
                {
                    var communityDetail = new CommunityDetails();

                    // Some of the values which comes from complex objects need to be set through this method.
                    Mapper.Map(community, communityDetail);

                    communityDetails.Add(communityDetail);
                }
            }

            return communityDetails;
        }
예제 #20
0
 /// <summary>
 /// Creates the new community in Layerscape with the given details passed in CommunitiesView instance.
 /// </summary>
 /// <param name="communityDetail">Details of the community</param>
 /// <returns>Id of the community created. Returns -1 is creation is failed.</returns>
 public async Task<long> CreateCommunityAsync(CommunityDetails communityDetail)
 {
     return CreateCommunity(communityDetail);
 }
예제 #21
0
        private IEnumerable<CommunityDetails> GetAllCommunities(EntityHighlightFilter entityHighlightFilter)
        {
            Func<CommunitiesView, object> orderBy = c => c.LastUpdatedDatetime;

            var accessType = AccessType.Public.ToString();
            Expression<Func<CommunitiesView, bool>> condition = null;
            if (entityHighlightFilter.CategoryType != CategoryType.All)
            {
                condition = c => c.CategoryID == (int)entityHighlightFilter.CategoryType && c.AccessType == accessType
                    && (c.CommunityTypeID == (int)CommunityTypes.Community || c.CommunityTypeID == (int)CommunityTypes.Folder);
            }
            else
            {
                condition = c => c.AccessType == accessType && 
                    (c.CommunityTypeID == (int)CommunityTypes.Community || c.CommunityTypeID == (int)CommunityTypes.Folder);
            }

            var communities =  _communitiesViewRepository.GetItems(condition, orderBy, true);

            var communityDetails = new List<CommunityDetails>();
            if (communities != null)
            {
                foreach (var community in communities)
                {
                    var communityDetail = new CommunityDetails();

                    // Some of the values which comes from complex objects need to be set through this method.
                    Mapper.Map(community, communityDetail);

                    communityDetails.Add(communityDetail);
                }
            }

            return communityDetails;
        }
예제 #22
0
        /// <summary>
        /// Creates the new community in Layerscape with the given details passed in CommunitiesView instance.
        /// </summary>
        /// <param name="communityDetail">Details of the community</param>
        /// <param name="userId">User Identity</param>
        /// <returns>Id of the community created. Returns -1 is creation is failed.</returns>
        public async void UpdateCommunity(CommunityDetails communityDetail, long userId)
        {
            // Make sure communityDetails is not null
            this.CheckNotNull(() => new { communityDetails = communityDetail });

            var community =  _communityRepository.GetItem((Community c) => c.CommunityID == communityDetail.ID && c.IsDeleted == false);

            // Make sure community is not null
            this.CheckNotNull(() => new { community });

            var userRole = GetCommunityUserRole(community.CommunityID, userId);
            if (!CanEditDeleteCommunity(community, userId, userRole))
            {
                throw new HttpException(401, Resources.NoPermissionUpdateCommunityMessage);
            }

            // For deleted communities, do not updates the changes.
            if (community.IsDeleted.HasValue && !community.IsDeleted.Value)
            {
                // Do not let the user to change the Community as public in case if it is offensive.
                // This scenario might happen when the edit page is left open or cached and meantime Community is marked as offensive 
                // by the Site Admin.
                if (community.IsOffensive.HasValue && (bool)community.IsOffensive && communityDetail.AccessTypeID == (int)AccessType.Public)
                {
                    communityDetail.AccessTypeID = (int)AccessType.Private;
                    communityDetail.IsOffensive = true;
                }

                Mapper.Map(communityDetail, community);

                community.ModifiedByID = userId;
                community.ModifiedDatetime = DateTime.UtcNow;

                // 1. Add Thumbnail to blob
                if (communityDetail.Thumbnail != null)
                {
                    if (communityDetail.Thumbnail.AzureID != Guid.Empty && community.ThumbnailID != communityDetail.Thumbnail.AzureID)
                    {
                        if (MoveThumbnail(communityDetail.Thumbnail))
                        {
                            community.ThumbnailID = communityDetail.Thumbnail.AzureID;
                        }
                        else
                        {
                            community.ThumbnailID = Guid.Empty;
                        }
                    }
                    else if (communityDetail.Thumbnail.AzureID == Guid.Empty)
                    {
                        community.ThumbnailID = Guid.Empty;
                    }
                }

                // 2. Update Tag details. This will also take care of creating tags if they are not there in the Layerscape database.
                SetCommunityTags(communityDetail.Tags, community);

                // 3. Update User role details. Any change in parent, roles need to be updated.
                //      Even if there was no parent before, need to check if any parent is mentioned now.
                // Get the previous parent if any. Note that there will be only one parent.
                long previousParent = 0;
                if (community.CommunityRelation1.Count == 1)
                {
                    previousParent = community.CommunityRelation1.ElementAt(0).ParentCommunityID;
                }

                if (communityDetail.ParentID != previousParent)
                {
                    _userCommunitiesRepository.InheritParentRoles(community, communityDetail.ParentID);
                }

                // 4. Update Parent Community details in case if Parent is specified

                // TODO: Need to check if we can move the community.

                // Few things to be noted:
                // a) Obviously the count to be 0 or 1 always.
                // b) A community can be child of only once parent community or folder and hence only one CommunityRelation1
                if (community.CommunityRelation1.Count > 0 && community.CommunityRelation1.ElementAt(0).ParentCommunityID != communityDetail.ParentID)
                {
                    community.CommunityRelation1.Clear();
                }

                if (communityDetail.ParentID > 0 && community.CommunityRelation1.Count == 0)
                {
                    // Add Parent Community details again
                    var communityRelation = new CommunityRelation();
                    communityRelation.ParentCommunityID = communityDetail.ParentID;
                    communityRelation.ChildCommunityID = communityDetail.ID;

                    // TODO: Need to rename the Data Model property CommunityRelation1 with a more meaningful name.
                    // Note that the relation to be added is to CommunityRelation1 since the current Community is Child.
                    // When the current community is parent, it's relation to be added in CommunityRelation.
                    community.CommunityRelation1.Add(communityRelation);
                }

                // Mark the Community as updated
                _communityRepository.Update(community);

                // TODO: Need to check the concurrency scenarios.
                // Save all the changes made.
                _communityRepository.SaveChanges();
            }
            else
            {
                // TODO: Need to throw exception informing user that the community is deleted.
            }
        }
예제 #23
0
        /// <summary>
        /// Gets all the communities from the Layerscape database including the deleted items.
        /// </summary>
        /// <param name="userId">Id of the user who is accessing</param>
        /// <param name="categoryId">Category ID for which communities to be fetched</param>
        /// <returns>List of all communities</returns>
        public async Task<IEnumerable<CommunityDetails>> GetAllCommunities(long userId, int? categoryId)
        {
            Func<AllCommunitiesView, object> orderBy = c => c.LastUpdatedDatetime;
            var communityDetails = new List<CommunityDetails>();

            if (_userRepository.IsSiteAdmin(userId))
            {
                Expression<Func<AllCommunitiesView, bool>> condition = null;
                if (categoryId != null)
                {
                    condition = ac => ac.CategoryID == categoryId && ac.CommunityTypeID != (int)CommunityTypes.User;
                }
                else
                {
                    condition = ac => ac.CommunityTypeID != (int)CommunityTypes.User;
                }

                foreach (var community in  _allCommunitiesViewRepository.GetItems(condition, orderBy, true))
                {
                    var communityDetail = new CommunityDetails();
                    Mapper.Map(community, communityDetail);
                    communityDetails.Add(communityDetail);
                }
            }

            return communityDetails;
        }
예제 #24
0
        public async Task<JsonResult> Edit(CommunityInputViewModel community)
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext(_communityService, _notificationService);
            }
            try
            {
                var communityDetails = new CommunityDetails();
                Mapper.Map(community, communityDetails);

                // Set thumbnail properties
                communityDetails.Thumbnail = new FileDetail {AzureID = community.ThumbnailID};

                if (CurrentUserId == 0)
                {
                    return Json("error: user not logged in");
                }
                _communityService.UpdateCommunity(communityDetails, CurrentUserId);
                return Json(new {id = community.ID});
            }
            catch (Exception exception)
            {
                
            }

            return Json("error: community not saved");
            
        }
예제 #25
0
 /// <summary>
 /// Notify the user about the new community.
 /// </summary>
 /// <param name="communityDetails">Community details</param>
 /// <param name="server">Server details.</param>
 public void NotifyNewEntityRequest(CommunityDetails communityDetails, string server)
 {
     if (Constants.CanSendNewEntityMail)
     {
         SendNewCommunityMail(communityDetails, server);
     }
 }