public async Task <Contentful.Core.Models.Entry <dynamic> > GetItemFromMgmtAPI(string id)
        {
            // note: consider moving mgmt actions into a new repository so we can
            // avoid giving all requests the mgmt keys & to avoid XxxFromMgmtXxx style
            _logger.LogTrace($"GetItemFromMgmtAPI({id})");
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentException("Missing required parameter", nameof(id));
            }

            var managementClient = new ContentfulManagementClient(_httpClient, _options);

            Contentful.Core.Models.Entry <dynamic> mgmtEntry = null;

            try
            {
                mgmtEntry = await managementClient.GetEntry(id);
            }
            catch (Contentful.Core.Errors.ContentfulException ex)
            {
                var msg = "Error getting entry from mgmt api: " + ex;
                _logger.LogError(msg);
                throw new ContentException(msg, ex);
            }
            catch (Exception ex)
            {
                var msg = "Unable to get entry from mgmt api: " + ex;
                _logger.LogError(msg);
                throw new ProcessException(msg, ex);
            }

            return(mgmtEntry);
        }
        public async Task <Entry <dynamic> > UpdateEntry(dynamic entry)
        {
            _logger.LogTrace($"ContentfulContentRepository.UpdateEntry({entry})");

            if (entry == null)
            {
                throw new ArgumentException("Missing required parameter", nameof(entry));
            }

            try
            {
                var managementClient = new ContentfulManagementClient(_httpClient, _options);
                return(await managementClient.CreateOrUpdateEntry(entry, null, null, entry.SystemProperties.Version));
            }
            catch (Contentful.Core.Errors.ContentfulException ex)
            {
                var msg = "Error updating entry: " + ex;
                _logger.LogError(msg);
                throw new ContentException(msg, ex);
            }
            catch (Exception ex)
            {
                var msg = "Unable to update entry: " + ex;
                _logger.LogError(msg);
                throw new ProcessException(msg, ex);
            }
        }
        public async Task <Contentful.Core.Models.Management.Snapshot> GetLastSnapshot(string id)
        {
            _logger.LogTrace($"ContentfulContentRepository.GetLastSnapshot({id})");

            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentException("Missing required parameter", nameof(id));
            }

            try
            {
                var managementClient = new ContentfulManagementClient(_httpClient, _options);
                var snapshots        = await managementClient.GetAllSnapshotsForEntry(id);

                return(snapshots.FirstOrDefault());
            }
            catch (Contentful.Core.Errors.ContentfulException ex)
            {
                var msg = "Error creating environment: " + ex;
                _logger.LogError(msg);
                throw new ContentException(msg, ex);
            }
            catch (Exception ex)
            {
                var msg = "Unable to create environment: " + ex;
                _logger.LogError(msg);
                throw new ProcessException(msg, ex);
            }
        }
        public async Task <Contentful.Core.Models.Management.ContentfulEnvironment> CreateEnvironment(string id, string name)
        {
            _logger.LogTrace($"ContentfulContentRepository.CreateEnvironment({id}, {name})");

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Missing required parameter", nameof(name));
            }

            try
            {
                var managementClient = new ContentfulManagementClient(_httpClient, _options);
                var env = await managementClient.CreateOrUpdateEnvironment(id, name);

                return(env);
            }
            catch (Contentful.Core.Errors.ContentfulException ex)
            {
                var msg = "Error creating environment: " + ex;
                _logger.LogError(msg);
                throw new ContentException(msg, ex);
            }
            catch (Exception ex)
            {
                var msg = "Unable to create environment: " + ex;
                _logger.LogError(msg);
                throw new ProcessException(msg, ex);
            }
        }
Esempio n. 5
0
        public async Task <ActionResult> UserAdd(string username, string password, Array City)
        {
            HttpClient httpClient = new HttpClient();
            var        client     = new ContentfulManagementClient(httpClient, "CFPAT-0188062dc4d4c5bdc61c744ffae9f600e56164b944e1a6c8d422ad1a0257525d", "bda2gc49gm0w");

            var entry = new Entry <dynamic>();

            entry.SystemProperties    = new SystemProperties();
            entry.SystemProperties.Id = Guid.NewGuid().ToString();
            entry.Fields = new
            {
                username = new Dictionary <string, string>()
                {
                    { "en-US", username }
                },
                password = new Dictionary <string, string>()
                {
                    { "en-US", password }
                },
                allCity = new Dictionary <string, Array>()
                {
                    { "en-US", City }
                }
            };

            await client.CreateOrUpdateEntry(entry, contentTypeId : "users");

            await client.PublishEntry(entry.SystemProperties.Id, 1);


            return(View("Index"));
        }
        public Client(string AuthToken, string Space)
        {
            this.AuthToken = AuthToken;
            this.Space     = Space;
            var httpClient = new HttpClient();

            _apiClient = new ContentfulManagementClient(httpClient, AuthToken, Space);
        }
Esempio n. 7
0
        public async Task <IEnumerable <VisualSpace> > GetSpaces(string key)
        {
            var ctfClient = new ContentfulManagementClient(_httpClient, new ContentfulOptions {
                ManagementApiKey = key
            });
            var ctfSpaces = await ctfClient.GetSpaces();

            return(ctfSpaces.Select(VisualSpaceFactory.CreateSpace));
        }
Esempio n. 8
0
        public async Task <IEnumerable <VisualTypeGroup> > GetTypes(string key, string spaceId, string groupNameSeparator)
        {
            var ctfClient = new ContentfulManagementClient(_httpClient, new ContentfulOptions {
                ManagementApiKey = key, SpaceId = spaceId
            });
            var ctfTypes = (await ctfClient.GetContentTypes()).OrderBy(c => c.Name).ToList();

            return(GroupTypes(ctfTypes.Select(VisualTypeFactory.CreateType), groupNameSeparator));
        }
        /// <summary>
        /// Publishes the content items referenced by the project.
        /// </summary>
        /// <param name="slug">The slug identifying the project</param>
        /// <returns></returns>
        public async Task <List <string> > PublishProject(string slug)
        {
            _logger.LogTrace($"ContentfulContentRepository.PublishProject({slug})");

            if (string.IsNullOrWhiteSpace(slug))
            {
                throw new ArgumentException("Missing required parameter", nameof(slug));
            }

            try
            {
                var cful             = new ContentfulClient(_httpClient, _options);
                var managementClient = new ContentfulManagementClient(_httpClient, _options);

                var facetQuery = new QueryBuilder <Project>()
                                 .ContentTypeIs("project")
                                 .FieldEquals("fields.slug", slug)
                                 .Include(8);
                _logger.LogInformation($"executing CMS call with query: {facetQuery.Build()}");

                // Retrieve the entire content tree by starting at the project and pulling includes
                // an arbitrary depth of 8
                var entrySet = await cful.GetEntries(facetQuery);

                // todo: determine if our process will already have the actual project published or not.
                // var projectId = entrySet.Items.FirstOrDefault().Sys.Id;
                var includedEntryIds = entrySet.IncludedEntries.Select(x => x.SystemProperties.Id);
                // todo: publish assets, too.
                // var includedAssetIds = entrySet.IncludedAssets.Select(x => x.SystemProperties.Id);

                foreach (var entry in entrySet.IncludedEntries)
                {
                    var id = entry.SystemProperties.Id;
                    // Retrieve the item from mgmt API. Version is not included from delivery API so we get it again.
                    var mgmtEntry = await managementClient.GetEntry(id);

                    var latestVersion = mgmtEntry.SystemProperties.Version.GetValueOrDefault();
                    var result        = await managementClient.PublishEntry(id, latestVersion);
                }

                return(null);
            }
            catch (Contentful.Core.Errors.ContentfulException ex)
            {
                var msg = "Error retrieving content: " + ex;
                _logger.LogError(msg);
                throw new ContentException(msg, ex);
            }
            catch (Exception ex)
            {
                var msg = "Unable to retrieve content: " + ex;
                _logger.LogError(msg);
                throw new ProcessException(msg, ex);
            }
        }
Esempio n. 10
0
        public override async Task <User> GetUser(string key)
        {
            var ctfClient = new ContentfulManagementClient(_httpClient, new ContentfulOptions {
                ManagementApiKey = key
            });
            var ctfUser = await ctfClient.GetCurrentUser();

            return(new User
            {
                Name = ctfUser.FirstName,
                Token = key
            });
        }
Esempio n. 11
0
        /// <summary>
        /// Creates a number of content types in Contentful.
        /// </summary>
        /// <param name="contentTypes">The content types to create.</param>
        /// <param name="configuration">The configuration for the creation process.</param>
        /// <param name="client">The optional client to use for creation.</param>
        /// <returns>A list of created or updated content types.</returns>
        public static async Task <List <ContentType> > CreateContentTypes(IEnumerable <ContentTypeInformation> contentTypes, ContentfulCodeFirstConfiguration configuration, IContentfulManagementClient client = null)
        {
            var managementClient = client;

            if (managementClient == null)
            {
                var httpClient = new HttpClient();
                managementClient = new ContentfulManagementClient(httpClient, configuration.ApiKey, configuration.SpaceId);
            }

            var createdTypes = new List <ContentType>();

            var existingContentTypes = (await managementClient.GetContentTypes()).ToList();

            if (configuration.ForceUpdateContentTypes == false)
            {
                //remove any pre-existing content types from the list to be created.
                contentTypes = contentTypes.Where(c => !existingContentTypes.Any(x => x.SystemProperties.Id == c.ContentType.SystemProperties.Id));
            }

            foreach (var contentTypeInfo in contentTypes)
            {
                //make sure to add correct version for existing content types
                contentTypeInfo.ContentType.SystemProperties.Version = existingContentTypes.FirstOrDefault(c => c.SystemProperties.Id == contentTypeInfo.ContentType.SystemProperties.Id)?.SystemProperties.Version;

                var createdContentType = await managementClient.CreateOrUpdateContentType(contentTypeInfo.ContentType, version : contentTypeInfo.ContentType.SystemProperties.Version);

                if (configuration.PublishAutomatically)
                {
                    createdContentType = await managementClient.ActivateContentType(createdContentType.SystemProperties.Id, createdContentType.SystemProperties.Version ?? 1);
                }

                createdTypes.Add(createdContentType);

                if (contentTypeInfo.InterfaceControls != null && contentTypeInfo.InterfaceControls.Any())
                {
                    var currentInterface = await managementClient.GetEditorInterface(createdContentType.SystemProperties.Id);


                    foreach (var control in contentTypeInfo.InterfaceControls)
                    {
                        var index = currentInterface.Controls.FindIndex(c => c.FieldId == control.FieldId);
                        currentInterface.Controls[index] = control;
                    }
                    await managementClient.UpdateEditorInterface(currentInterface, createdContentType.SystemProperties.Id, currentInterface.SystemProperties.Version.Value);
                }
            }

            return(createdTypes);
        }
        /// <summary>
        /// Publishes the content item with the provided ID
        /// </summary>
        /// <param name="id">The id identifying the item</param>
        /// <returns></returns>
        public async Task <int> PublishItem(string id)
        {
            _logger.LogTrace($"PublishItem({id})");

            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentException("Missing required parameter", nameof(id));
            }

            var managementClient = new ContentfulManagementClient(_httpClient, _options);
            var mgmtEntry        = await GetItemFromMgmtAPI(id);

            try
            {
                var latestVersion    = mgmtEntry.SystemProperties.Version.GetValueOrDefault();
                var publishedVersion = mgmtEntry.SystemProperties.PublishedVersion.GetValueOrDefault();

                // note: this is intended to reduce re-pubishing already published items but
                // a bug in contentful ALWAYS increments the latest version, no matter what.
                // Leaving for future, but should probably ask contentful about it.
                if (publishedVersion < latestVersion)
                {
                    var result = await managementClient.PublishEntry(id, latestVersion);

                    return(result.SystemProperties.PublishedVersion.GetValueOrDefault());
                }

                return(publishedVersion);
            }
            catch (Contentful.Core.Errors.ContentfulException ex)
            {
                var msg = "Error publishing entry: " + ex;
                _logger.LogError(msg);
                throw new ContentException(msg, ex);
            }
            catch (Exception ex)
            {
                var msg = "Unable to publishing entry: " + ex;
                _logger.LogError(msg);
                throw new ProcessException(msg, ex);
            }
        }
Esempio n. 13
0
        public static async Task Create()
        {
            try
            {
                var httpClient = new HttpClient();

                var client = new ContentfulManagementClient(httpClient,
                                                            "<content_management_api_key>", "<space_id>");

                var extension = await client.GetExtension("<extension_id>");

                extension.SystemProperties.Version = extension.SystemProperties.Version + 1;

                extension.Parameters = new UiExtensionParametersLists
                {
                    InstanceParameters = new List <UiExtensionParameters>
                    {
                        new UiExtensionParameters
                        {
                            // Update these fields as required
                            Id          = "sections",
                            Name        = "Section names",
                            Type        = "Symbol",
                            Required    = false,
                            Description = "Define the sections that will be re-ordered. The list is separated by commas."
                        }
                    }
                };

                extension.SystemProperties.Id = null;
                extension.Src    = "https://www.google.com";
                extension.SrcDoc = null;

                // You will need to over-ride the srcdoc after you run this

                await client.CreateExtension(extension);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        public async Task <int> OnExecute(CommandLineApplication app, IConsole console)
        {
            var http   = new HttpClient();
            var client = new ContentfulManagementClient(http, new ContentfulOptions
            {
                ManagementApiKey = ManagementToken,
                SpaceId          = SpaceId,
                Environment      = Environment
            });

            try
            {
                _contentTypes = await client.GetContentTypes();
            }
            catch (ContentfulException ce)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Error.WriteLine("There was an error communicating with the Contentful API: " + ce.Message);
                Console.Error.WriteLine($"Request ID: {ce.RequestId}");
                Console.Error.WriteLine("" + ce.ErrorDetails?.Errors);
                Console.Error.WriteLine("Please verify that your api key and access token are correct");
                Console.ResetColor();
                return(Program.ERROR);
            }

            Console.WriteLine($"Found {_contentTypes.Count()} content types.");
            var path = "";

            if (string.IsNullOrEmpty(Path))
            {
                path = Directory.GetCurrentDirectory();
                Console.WriteLine($"No path specified, creating files in current working directory {path}");
            }
            else
            {
                Console.WriteLine($"Path specified. Files will be created at {Path}");
                path = Path;
            }

            var dir = new DirectoryInfo(path);

            if (dir.Exists == false)
            {
                Console.WriteLine($"Path {path} does not exist and will be created.");
                dir.Create();
            }

            foreach (var contentType in _contentTypes)
            {
                var safeFileName = GetSafeFilename(contentType.SystemProperties.Id);

                var file = new FileInfo($"{dir.FullName}{System.IO.Path.DirectorySeparatorChar}{safeFileName}.cs");
                if (file.Exists && !Force)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    var prompt = Prompt.GetYesNo($"The folder already contains a file with the name {file.Name}. Do you want to overwrite it?", true);
                    Console.ResetColor();
                    if (prompt == false)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"Skipping {file.Name}");
                        Console.ResetColor();
                    }
                }

                using (var sw = file.CreateText())
                {
                    var sb = new StringBuilder();
                    sb.AppendLine(_templateStart);
                    sb.AppendLine($"namespace {Namespace}");
                    //start namespace
                    sb.AppendLine("{");

                    sb.AppendLine($"    public class {FormatClassName(contentType.SystemProperties.Id)}");
                    //start class
                    sb.AppendLine("    {");

                    sb.AppendLine("        public SystemProperties Sys { get; set; }");

                    foreach (var field in contentType.Fields)
                    {
                        sb.AppendLine($"        public {GetDataTypeForField(field)} {FirstLetterToUpperCase(field.Id)} {{ get; set; }}");
                    }

                    //end class
                    sb.AppendLine("    }");
                    //end namespace
                    sb.AppendLine("}");

                    sw.WriteLine(sb.ToString());
                }
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Files successfully created!");
            Console.ResetColor();

            return(Program.OK);
        }
        public IContentfulManagementClient GetManagementClient(ContentfulConfig config)
        {
            var client = new ContentfulManagementClient(_httpClient, config.ManagementKey, config.SpaceKey);

            return(client);
        }