Exemplo n.º 1
0
        public async Task <ContentCategories> GetContentFolders(string parentFolderId = null)
        {
            ContentCategories categories = null;
            string            serviceURL = this.ContentURL + FolderResource + "?$pagesize=" + PageSize;

            if (accessToken == null || !accessToken.IsValid)
            {
                BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
            }

            ServiceHandler serviceHandler = new ServiceHandler();
            string         result         = await serviceHandler.InvokeRESTServiceNoBody(serviceURL, accessToken);

            categories = ParseContentFolderServiceOutput(result);

            //Checking if more calls are required because the paging
            if (categories != null && categories.Items != null && categories.Items.Count < categories.Count)
            {
                ContentCategories overallCategories = new ContentCategories();
                overallCategories.Items = new System.Collections.Generic.List <Category>();

                overallCategories.Items.AddRange(categories.Items);
                overallCategories.Count = categories.Count;

                //The last call should have zero items, this indicates no more pages are available
                while (categories.Items.Count != 0)
                {
                    int pageToRequest = (int)(categories.Page + 1);
                    serviceURL += "&$page=" + pageToRequest;

                    //Because we are iterating, it's better to check if the token is still valid, with OAuth 2.0 the token only lasts 1079 seconds
                    if (accessToken == null || !accessToken.IsValid)
                    {
                        BearerToken tokenBuilder = new BearerToken(AuthenticationURL);
                        accessToken = await tokenBuilder.GetAccessToken(this.clientId, this.secret);
                    }

                    result = await serviceHandler.InvokeRESTServiceNoBody(serviceURL, accessToken);

                    categories = ParseContentFolderServiceOutput(result);

                    if (categories == null)
                    {
                        break;
                    }

                    overallCategories.Items.AddRange(categories.Items);
                }

                categories = overallCategories;
            }

            return(categories);
        }
Exemplo n.º 2
0
        private ContentCategories ParseContentFolderServiceOutput(string serviceOutput)
        {
            ContentCategories categories = null;

            try
            {
                categories = JsonConvert.DeserializeObject <ContentCategories>(serviceOutput);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            return(categories);
        }
Exemplo n.º 3
0
        public async Task GetFolderWithFilter()
        {
            Exception         exception  = null;
            ContentCategories categories = null;

            try
            {
                categories = await dataExtensionManager.GetContentFolders("0");
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.Null(exception);
            Assert.True(categories != null);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Transform ContentCategories into a tree representation, useful for binding to TreeView
        /// </summary>
        /// <param name="categories">Regular list of categories</param>
        /// <returns>Tree representation</returns>
        public Category ConvertContentFolderToCategoryTree(ContentCategories categories)
        {
            var sortedList = categories.Items.OrderBy(x => x.ParentId).ToList();

            Category root = null;

            foreach (var item in sortedList)
            {
                if (root == null)
                {
                    root = new Category {
                        Id           = item.Id,
                        CategoryType = item.CategoryType,
                        Description  = item.Description,
                        EnterpriseId = item.EnterpriseId,
                        MemberId     = item.MemberId,
                        Name         = item.Name,
                        ParentId     = item.ParentId
                    };

                    root.Folders = new List <IFolder>();

                    continue;
                }

                if (item.ParentId == root.Id)
                {
                    root.Folders.Add(item);
                }
                else
                {
                    var category = root.Folders.Where(c => c.Id == item.ParentId).FirstOrDefault();

                    if (category.Folders == null)
                    {
                        category.Folders = new List <IFolder>();
                    }

                    category.Folders.Add(item);
                }
            }

            return(root);
        }
Exemplo n.º 5
0
        public async Task GetFoldersTree()
        {
            Exception         exception  = null;
            ContentCategories categories = null;
            Category          category   = null;

            try
            {
                categories = await dataExtensionManager.GetContentFolders();

                category = dataExtensionManager.ConvertContentFolderToCategoryTree(categories);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            Assert.Null(exception);
            Assert.True(categories != null);
            Assert.True(category != null);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Refreshes the current object.
        /// </summary>
        public void Refresh()
        {
            GetMetaData();

            if (!Content.IsNew)
            {
                Relation.GetFieldsByDataId("relation_related_id", Content.Id).ForEach(r => ContentCategories.Add(r.RelatedId));
                Categories = new MultiSelectList(Category.GetFields("category_id, category_name",
                                                                    new Params()
                {
                    OrderBy = "category_name"
                }), "Id", "Name", ContentCategories);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Saves the edit model.
        /// </summary>
        public bool SaveAll(bool draft)
        {
            var context = HttpContext.Current;
            var hasfile = UploadedFile != null || ServerFile != null;

            byte[]    data = null;
            WebClient web  = new WebClient();

            // Check if the original URL has been updated, and if so
            if (!Content.IsNew && !String.IsNullOrEmpty(Content.OriginalUrl))
            {
                var old = Content.GetSingle(Content.Id);
                if (old != null)
                {
                    if (Content.OriginalUrl != old.OriginalUrl)
                    {
                        FileUrl = Content.OriginalUrl;
                    }
                }
            }

            // Download file from web
            if (!hasfile && !String.IsNullOrEmpty(FileUrl))
            {
                data = web.DownloadData(FileUrl);
                Content.OriginalUrl = FileUrl;
                Content.LastSynced  = Convert.ToDateTime(web.ResponseHeaders[HttpResponseHeader.LastModified]);
            }

            var media = new MediaFileContent();

            if (hasfile)
            {
                if (UploadedFile != null)
                {
                    media.Filename    = UploadedFile.FileName;
                    media.ContentType = UploadedFile.ContentType;
                    using (var reader = new BinaryReader(UploadedFile.InputStream)) {
                        media.Body = reader.ReadBytes(Convert.ToInt32(UploadedFile.InputStream.Length));
                    }
                }
                else
                {
                    media.Filename    = ServerFile.Name;
                    media.ContentType = MimeType.Get(ServerFile.Name);
                    using (var stream = ServerFile.OpenRead()) {
                        media.Body = new byte[ServerFile.Length];
                        stream.Read(media.Body, 0, media.Body.Length);
                    }
                }
            }
            else if (data != null)
            {
                media.Filename    = FileUrl.Substring(FileUrl.LastIndexOf('/') + 1);
                media.ContentType = web.ResponseHeaders["Content-Type"];
                media.Body        = data;
            }
            else
            {
                media = null;
            }

            var saved = false;

            if (!Content.IsFolder)
            {
                // Only save permalinks for non-folders
                var filename = !String.IsNullOrEmpty(Content.Filename) ? Content.Filename : (!String.IsNullOrEmpty(media.Filename) ? media.Filename : "");
                if (Permalink.IsNew && String.IsNullOrEmpty(Permalink.Name))
                {
                    Permalink.Name = Permalink.Generate(!Content.IsFolder ? filename : Content.Name, Models.Permalink.PermalinkType.MEDIA);
                }
                try {
                    Permalink.Save();
                } catch (DuplicatePermalinkException) {
                    if (Permalink.IsNew)
                    {
                        Permalink.Name = Content.Id + Permalink.Name.Substring(Permalink.Name.LastIndexOf('.'));
                        Permalink.Save();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                Content.PermalinkId = Guid.Empty;
            }

            if (draft)
            {
                saved = Content.Save(media);
            }
            else
            {
                saved = Content.SaveAndPublish(media);
            }

            if (saved)
            {
                // Save related information
                Relation.DeleteByDataId(Content.Id);
                List <Relation> relations = new List <Relation>();
                ContentCategories.ForEach(c => relations.Add(new Relation()
                {
                    DataId = Content.Id, RelatedId = c, IsDraft = false, Type = Relation.RelationType.CONTENTCATEGORY
                })
                                          );
                relations.ForEach(r => r.Save());

                // Save extensions
                foreach (var ext in Extensions)
                {
                    // Call OnSave
                    ext.Body.OnManagerSave(Content);

                    ext.ParentId = Content.Id;
                    ext.Save();
                    if (!draft)
                    {
                        if (Extension.GetScalar("SELECT COUNT(extension_id) FROM extension WHERE extension_id=@0 AND extension_draft=0", ext.Id) == 0)
                        {
                            ext.IsNew = true;
                        }
                        ext.IsDraft = false;
                        ext.Save();
                    }
                }
                // Reset file url
                FileUrl = "";

                return(true);
            }
            return(false);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Saves the edit model.
        /// </summary>
        public bool SaveAll()
        {
            var context = HttpContext.Current;
            var hasfile = UploadedFile != null;

            byte[]    data = null;
            WebClient web  = new WebClient();


            if (!hasfile && !String.IsNullOrEmpty(FileUrl))
            {
                data = web.DownloadData(FileUrl);
            }

            if (hasfile || data != null)
            {
                // Check if this is an image
                try {
                    Image img = null;

                    if (hasfile)
                    {
                        img = Image.FromStream(UploadedFile.InputStream);
                    }
                    else
                    {
                        MemoryStream mem = new MemoryStream(data);
                        img = Image.FromStream(mem);
                    }

                    // Image img = Image.FromStream(UploadedFile.InputStream) ;
                    try {
                        // Resize the image according to image max width
                        int max = Convert.ToInt32(SysParam.GetByName("IMAGE_MAX_WIDTH").Value);
                        if (max > 0)
                        {
                            img = Drawing.ImageUtils.Resize(img, max);
                        }
                    } catch {}
                    Content.IsImage = true;
                    Content.Width   = img.Width;
                    Content.Height  = img.Height;
                } catch {
                    Content.IsImage = false;
                }
                if (hasfile)
                {
                    Content.Filename = UploadedFile.FileName;
                    Content.Type     = UploadedFile.ContentType;
                    Content.Size     = UploadedFile.ContentLength;
                }
                else
                {
                    Content.Filename = FileUrl.Substring(FileUrl.LastIndexOf('/') + 1);
                    Content.Type     = web.ResponseHeaders["Content-Type"];
                    Content.Size     = Convert.ToInt32(web.ResponseHeaders["Content-Length"]);
                }
            }

            if (Content.Save())
            {
                // Save related information
                Relation.DeleteByDataId(Content.Id);
                List <Relation> relations = new List <Relation>();
                ContentCategories.ForEach(c => relations.Add(new Relation()
                {
                    DataId = Content.Id, RelatedId = c, IsDraft = false, Type = Relation.RelationType.CONTENTCATEGORY
                })
                                          );
                relations.ForEach(r => r.Save());

                // Save the physical file
                if (hasfile || data != null)
                {
                    string path = context.Server.MapPath("~/App_Data/content");
                    if (File.Exists(Content.PhysicalPath))
                    {
                        File.Delete(Content.PhysicalPath);
                        Content.DeleteCache();
                    }
                    if (hasfile)
                    {
                        UploadedFile.SaveAs(Content.PhysicalPath);
                    }
                    else
                    {
                        FileStream   writer = new FileStream(Content.PhysicalPath, FileMode.Create);
                        BinaryWriter binary = new BinaryWriter(writer);
                        binary.Write(data);
                        binary.Flush();
                        binary.Close();
                    }
                }
                // Reset file url
                FileUrl = "";

                // Delete possible old thumbnails
                Content.DeleteCache();

                return(true);
            }
            return(false);
        }