Beispiel #1
0
        public ContentfulService(IHostingEnvironment hostingEnvironment, ICacheService cacheService, IOptions <ContentfulConfig> contentfulConfig, IBaseClient baseClient)
        {
            _hostingEnvironment = hostingEnvironment;
            _cacheService       = cacheService;
            _contentfulConfig   = contentfulConfig.Value;

            _imageDBPath = _hostingEnvironment.WebRootPath + "/data/header-images.json";

            // Build Contentful client
            var options = new ContentfulOptions()
            {
                UsePreviewApi  = false,
                DeliveryApiKey = _contentfulConfig.DeliveryApiKey,
                SpaceId        = _contentfulConfig.SpaceId
            };

            _client = new ContentfulClient(baseClient.GetHttpClient(), options);

            // Build Contentful preview client
            var previewOptions = new ContentfulOptions()
            {
                UsePreviewApi = true,
                PreviewApiKey = _contentfulConfig.PreviewApiKey,
                SpaceId       = _contentfulConfig.SpaceId
            };

            _previewClient = new ContentfulClient(baseClient.GetHttpClient(), previewOptions);
        }
Beispiel #2
0
        public async Task <ActionResult> Index()
        {
            if (Session["username"] != null)
            {
                ViewBag.Session = Session["username"].ToString();
            }
            else
            {
                ViewBag.Session = "Contentful";
            }

            HttpClient httpClient = new HttpClient();
            var        options    = new ContentfulOptions
            {
                DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625",
                PreviewApiKey  = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2",
                SpaceId        = "bda2gc49gm0w"
            };

            var client = new ContentfulClient(httpClient, options);

            var AllCategories = await client.GetEntries(QueryBuilder <Category> .New.ContentTypeIs("category"));

            var AllCategoryItems = await client.GetEntries(QueryBuilder <Product> .New.ContentTypeIs("categoryItems"));

            Homepage model = new Homepage();

            model.Kategori = AllCategories.Items.ToList();
            model.Urun     = AllCategoryItems.Items.ToList();

            return(View(model));
        }
        /// <summary>
        /// Post action from the /settings view.
        /// </summary>
        /// <param name="appOptions">The options provided by the user.</param>
        /// <returns>The updated view or the current view with validation errors.</returns>
        public IActionResult OnPost(SelectedOptions appOptions)
        {
            if (!ModelState.IsValid)
            {
                TempData["Invalid"] = true;
                return(Page());
            }

            if (appOptions.EnableEditorialFeatures)
            {
                HttpContext.Session.SetString("EditorialFeatures", "Enabled");
            }
            else
            {
                HttpContext.Session.SetString("EditorialFeatures", "Disabled");
            }

            var currentOptions = new ContentfulOptions
            {
                DeliveryApiKey = appOptions.AccessToken,
                SpaceId        = appOptions.SpaceId,
                UsePreviewApi  = _manager.Options.UsePreviewApi,
                PreviewApiKey  = appOptions.PreviewToken,
                MaxNumberOfRateLimitRetries = _manager.Options.MaxNumberOfRateLimitRetries,
                ResolveEntriesSelectively   = _manager.Options.ResolveEntriesSelectively,
                ManagementApiKey            = _manager.Options.ManagementApiKey
            };

            HttpContext.Session.SetString(nameof(ContentfulOptions), JsonConvert.SerializeObject(currentOptions));
            TempData["Success"] = true;

            return(RedirectToPage("Settings"));
        }
Beispiel #4
0
        public async Task <ActionResult> Register()
        {
            HttpClient httpClient = new HttpClient();
            var        options    = new ContentfulOptions
            {
                DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625",
                PreviewApiKey  = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2",
                SpaceId        = "bda2gc49gm0w"
            };

            var client = new ContentfulClient(httpClient, options);

            List <string> Cities        = new List <string>();
            var           AllCategories = await client.GetContentType("users");

            foreach (var fields in AllCategories.Fields)
            {
                if (fields.Id == "allCity")
                {
                    Cities = ((Contentful.Core.Models.Management.InValuesValidator)fields.Items.Validations[0]).RequiredValues;
                }
            }
            HttpContext.Cache.Add("City", Cities, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), System.Web.Caching.CacheItemPriority.Normal, null);


            return(View());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentfulClient"/> class.
        /// </summary>
        /// <param name="httpClient">The HttpClient of your application.</param>
        /// <param name="deliveryApiKey">The delivery API key used when communicating with the Contentful API.</param>
        /// <param name="previewApiKey">The preview API key used when communicating with the Contentful Preview API.</param>
        /// <param name="spaceId">The ID of the space to fetch content from.</param>
        /// <param name="usePreviewApi">Whether or not to use the Preview API for requests.
        /// If this is set to true the preview API key needs to be used for <paramref name="deliveryApiKey"/>
        ///  </param>
        public ContentfulClient(HttpClient httpClient, string deliveryApiKey, string previewApiKey, string spaceId, bool usePreviewApi = false)
        {
            _httpClient = httpClient;
            var options = new ContentfulOptions
            {
                DeliveryApiKey = deliveryApiKey,
                SpaceId        = spaceId,
                PreviewApiKey  = previewApiKey,
                UsePreviewApi  = usePreviewApi
            };

            _options = options;
        }
Beispiel #6
0
        private ContentfulClient GetClientWithEnvironment(string env = "special")
        {
            var httpClient = new HttpClient(_handler);
            var options    = new ContentfulOptions
            {
                DeliveryApiKey = "123",
                PreviewApiKey  = "3123",
                Environment    = env,
                SpaceId        = "564"
            };
            var client = new ContentfulClient(httpClient, options);

            return(client);
        }
Beispiel #7
0
        public async Task <ActionResult> ProductDetails(string productID)
        {
            HttpClient httpClient = new HttpClient();
            var        options    = new ContentfulOptions
            {
                DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625",
                PreviewApiKey  = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2",
                SpaceId        = "bda2gc49gm0w"
            };
            var client = new ContentfulClient(httpClient, options);

            var ProductDetail = await client.GetEntries(QueryBuilder <Product> .New.ContentTypeIs("categoryItems").FieldEquals(f => f.Sys.Id, productID));

            return(View(ProductDetail.ToList()));
        }
        public async Task Contentful()
        {
            var httpClient = new HttpClient();
            var options    = new ContentfulOptions()
            {
                DeliveryApiKey = "c66a798c5adb7e11727de7831e48f2cf5039b2c2f2595be6f83b67c03fac3e4a",
                PreviewApiKey  = "ae5d997b2a95d49e250939bc350397778bb17ebe56560e8e2442b320668b2550",
                SpaceId        = "fgj5iptu3uwg"
            };
            var client = new ContentfulClient(httpClient, options);

            var entry = await client.GetEntry <Product>("3r6V9g1XzGaKAY4syUuyIg");

            Assert.That(entry.Sys.Id, Is.Not.Null);
        }
Beispiel #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ContentfulClient"/> class.
        /// The main class for interaction with the contentful deliver and preview APIs.
        /// </summary>
        /// <param name="httpClient">The HttpClient of your application.</param>
        /// <param name="options">The options object used to retrieve the <see cref="ContentfulOptions"/> for this client.</param>
        /// <exception cref="ArgumentException">The <see name="options">options</see> parameter was null or empty</exception>
        public ContentfulClient(HttpClient httpClient, ContentfulOptions options)
        {
            _httpClient = httpClient;
            _options    = options;

            if (options == null)
            {
                throw new ArgumentException("The ContentfulOptions cannot be null.", nameof(options));
            }

            if (_options.UsePreviewApi)
            {
                _baseUrl = _baseUrl.Replace("cdn", "preview");
            }
            ResolveEntriesSelectively = _options.ResolveEntriesSelectively;
            SerializerSettings.Converters.Add(new AssetJsonConverter());
        }
        /// <summary>
        /// Post action from the dropdown to switch api.
        /// </summary>
        /// <param name="api">The api to switch to.</param>
        /// <param name="prevPage">The page that originated the post.</param>
        /// <returns>A redirect result back to the originating page.</returns>
        public IActionResult OnPostSwitchApi(string api, string prevPage)
        {
            // Retain all options except whether to use the preview api or not.
            var options = new ContentfulOptions
            {
                UsePreviewApi  = api == "cpa",
                DeliveryApiKey = _manager.Options.DeliveryApiKey,
                SpaceId        = _manager.Options.SpaceId,
                PreviewApiKey  = _manager.Options.PreviewApiKey,
                MaxNumberOfRateLimitRetries = _manager.Options.MaxNumberOfRateLimitRetries,
                ResolveEntriesSelectively   = _manager.Options.ResolveEntriesSelectively,
                ManagementApiKey            = _manager.Options.ManagementApiKey
            };


            HttpContext.Session.SetString(nameof(ContentfulOptions), JsonConvert.SerializeObject(options));
            return(Redirect($"{prevPage}?api={api}"));
        }
Beispiel #11
0
        public void Initialize()
        {
            //Barrel.Current.EmptyAll();
            var httpClient = new HttpClient();
            var options    = new ContentfulOptions()
            {
                DeliveryApiKey = "i1sZI3TtJdmSCExSb99A-7mKPOAdUO7YwfIe2sFLMmI",
                PreviewApiKey  = "_LEWxIyIa2o7JBhdhKXyVkERhqDpqj18oHUiTmmswu8",
                SpaceId        = "1eifs2l9mf3m",
                UsePreviewApi  = true
            };

            Client = new ContentfulClient(httpClient, options);

            itemEntriesKeysList = Barrel.Current.Get <List <string> >(EntriesKeyListId) ?? new List <string>();
            itemAssetsKeysList  = Barrel.Current.Get <List <string> >(AssetsKeyListId) ?? new List <string>();

            nextSyncUrl = Barrel.Current.Get <string>(nameof(nextSyncUrl));
        }
Beispiel #12
0
        public async Task <ActionResult> Category(string categoryID)
        {
            HttpClient httpClient = new HttpClient();
            var        options    = new ContentfulOptions
            {
                DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625",
                PreviewApiKey  = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2",
                SpaceId        = "bda2gc49gm0w"
            };
            var client = new ContentfulClient(httpClient, options);

            var AllItems = await client.GetEntries(QueryBuilder <Product> .New.ContentTypeIs("categoryItems"));

            var FilterCategoryItems = AllItems.Where(c => c.categoryRef.Any(x => string.Equals(x["$ref"].ToString(), categoryID)));
            var AllCategories       = await client.GetEntries(QueryBuilder <Category> .New.ContentTypeIs("category"));

            var model = new Homepage();

            model.Urun     = FilterCategoryItems.ToList();
            model.Kategori = AllCategories.ToList();
            return(View("Index", model));
        }
Beispiel #13
0
        public async Task <ActionResult> Contact()
        {
            HttpClient httpClient = new HttpClient();
            var        options    = new ContentfulOptions
            {
                DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625",
                PreviewApiKey  = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2",
                SpaceId        = "bda2gc49gm0w"
            };

            var client   = new ContentfulClient(httpClient, options);
            var PageInfo = await client.GetEntry <Pages>("6pe3lPKCzpsyz9nZBpJzbr");

            List <PageContent> currentPageContents = new List <PageContent>();

            foreach (var item in PageInfo.modules)
            {
                currentPageContents.Add(await client.GetEntry <PageContent>(item["sys"]["id"].ToString()));
            }

            return(View(currentPageContents));
        }
Beispiel #14
0
        public async Task <ActionResult> UserControl(string username, string password)
        {
            HttpClient httpClient = new HttpClient();
            var        options    = new ContentfulOptions
            {
                DeliveryApiKey = "4df4c5c7ed276605d36b9d880f1455aea05fe9b47e2da6acf518c0771d300625",
                PreviewApiKey  = "3aaec008db04a17e144539715f539354ff73cf8d82c2548c3045bbcfc2ee32a2",
                SpaceId        = "bda2gc49gm0w"
            };
            var client = new ContentfulClient(httpClient, options);

            var AllItems = await client.GetEntries(QueryBuilder <User> .New.ContentTypeIs("users"));

            foreach (var item in AllItems)
            {
                if (item.Username.ToLower() == username.ToLower() && item.Password.ToLower() == password.ToLower() && username != null && password != null)
                {
                    Session["username"] = username;
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(RedirectToAction("Index", "State"));
        }
Beispiel #15
0
 /// <summary>
 /// Initializes a new <see cref="ContentfulOptionsManager"/>.
 /// </summary>
 /// <param name="options">The ContentfulOptions loaded from application configuration.</param>
 /// <param name="accessor">The IHttpContextAccessor used to get access to the HttpContext.</param>
 public ContentfulOptionsManager(IOptions <ContentfulOptions> options, IHttpContextAccessor accessor)
 {
     _options  = options.Value;
     _accessor = accessor;
 }
 public ContentRemove(IMediator mediator, IOptions <ContentfulOptions> contentfulOptions)
 {
     _mediator          = mediator;
     _contentfulOptions = contentfulOptions.Value;
 }
Beispiel #17
0
 /// <summary>
 /// Instantiate the view component.
 /// </summary>
 /// <param name="httpClient">The httpclient to use for a separate call to the Contentful API.</param>
 /// <param name="optionsManager">The class that manages the Contentful configuration for the application.</param>
 public EntryStateViewComponent(HttpClient httpClient, IContentfulOptionsManager optionsManager)
 {
     _httpClient = httpClient;
     _options    = optionsManager.Options;
 }
Beispiel #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentfulManagementClient"/> class.
 /// </summary>
 /// <param name="httpClient">The HttpClient of your application.</param>
 /// <param name="options">The <see cref="ContentfulOptions"/> used for this client.</param>
 //public ContentfulManagementClientWrapper(HttpClient httpClient, ContentfulOptions options, ILogger<IContentManagementClient> logger) :
 public ContentfulManagementClientWrapper(HttpClient httpClient, ContentfulOptions options) :
     this(httpClient, new OptionsWrapper <ContentfulOptions>(options))
 {
 }
Beispiel #19
0
        public async Task <int> OnExecute(CommandLineApplication app, IConsole console)
        {
            var http    = new HttpClient();
            var options = new ContentfulOptions
            {
                DeliveryApiKey = ApiKey,
                SpaceId        = SpaceId,
                Environment    = Environment
            };
            var client = new ContentfulClient(http, options);

            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.Name);

                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.Name)}");
                    //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 ContentfulContentRepository(HttpClient httpClient, ILogger <ContentfulContentRepository> logger, ContentfulOptions options)
 {
     _logger     = logger;
     _httpClient = httpClient;
     _options    = options;
 }
Beispiel #21
0
 /// <summary>
 /// Instantiates the view component.
 /// </summary>
 /// <param name="optionsManager">The class that manages the Contentful configuration for the application.</param>
 public EditorialFeaturesViewComponent(IContentfulOptionsManager optionsManager)
 {
     _options = optionsManager.Options;
 }
Beispiel #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentfulClient"/> class.
 /// </summary>
 /// <param name="httpClient">The HttpClient of your application.</param>
 /// <param name="options">The <see cref="ContentfulOptions"/> used for this client.</param>
 public ContentfulClient(HttpClient httpClient, ContentfulOptions options) :
     this(httpClient, new OptionsWrapper <ContentfulOptions>(options))
 {
 }
Beispiel #23
0
        /// <summary>
        /// Invokes this middleware.
        /// </summary>
        /// <param name="context">The HttpContext of the request to extract breadcrumbs from.</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var query = context.Request.Query;

            if (query.ContainsKey("space_id") && query.ContainsKey("preview_token") && query.ContainsKey("delivery_token"))
            {
                var currentOptions = new ContentfulOptions();
                currentOptions.DeliveryApiKey = query["delivery_token"];
                currentOptions.SpaceId        = query["space_id"];
                currentOptions.PreviewApiKey  = query["preview_token"];
                currentOptions.UsePreviewApi  = query.ContainsKey("api") && query["api"] == "cpa";
                currentOptions.MaxNumberOfRateLimitRetries = _manager.Options.MaxNumberOfRateLimitRetries;
                currentOptions.ResolveEntriesSelectively   = _manager.Options.ResolveEntriesSelectively;
                currentOptions.ManagementApiKey            = _manager.Options.ManagementApiKey;

                var validateableOptions = new SelectedOptions
                {
                    AccessToken  = currentOptions.DeliveryApiKey,
                    PreviewToken = currentOptions.PreviewApiKey,
                    SpaceId      = currentOptions.SpaceId
                };
                var validationContext = new ValidationContext(validateableOptions, context.RequestServices, null);
                var validationResult  = validateableOptions.Validate(validationContext);

                if (validationResult.Any())
                {
                    var modelStateErrors = new List <ModelStateError>();

                    foreach (var result in validationResult)
                    {
                        foreach (var member in result.MemberNames)
                        {
                            modelStateErrors.Add(new ModelStateError {
                                ErrorMessage = result.ErrorMessage, Key = member
                            });
                        }
                    }

                    context.Session.SetString("SettingsErrors", JsonConvert.SerializeObject(modelStateErrors));
                    context.Session.SetString("SettingsErrorsOptions", JsonConvert.SerializeObject(validateableOptions));
                    context.Response.Redirect("/settings");
                    context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
                    context.Response.Headers.Add("Pragma", "no-cache");
                    return;
                }
                else
                {
                    context.Session.SetString(nameof(ContentfulOptions), JsonConvert.SerializeObject(currentOptions));
                }
            }
            else if (query.ContainsKey("api"))
            {
                var currentOptions = new ContentfulOptions
                {
                    UsePreviewApi  = query["api"] == "cpa",
                    DeliveryApiKey = _manager.Options.DeliveryApiKey,
                    SpaceId        = _manager.Options.SpaceId,
                    PreviewApiKey  = _manager.Options.PreviewApiKey,
                    MaxNumberOfRateLimitRetries = _manager.Options.MaxNumberOfRateLimitRetries,
                    ResolveEntriesSelectively   = _manager.Options.ResolveEntriesSelectively,
                    ManagementApiKey            = _manager.Options.ManagementApiKey
                };

                context.Session.SetString(nameof(ContentfulOptions), JsonConvert.SerializeObject(currentOptions));
            }

            if (query.ContainsKey("editorial_features") && string.Equals(query["editorial_features"], "enabled", StringComparison.InvariantCultureIgnoreCase))
            {
                context.Session.SetString("EditorialFeatures", "Enabled");
            }
            else if (query.ContainsKey("editorial_features"))
            {
                context.Session.SetString("EditorialFeatures", "Disabled");
            }

            await _next(context);
        }