Skip to content

Sample Console App, to understand working of .dotNet Delivery SDK of ContentStack

Notifications You must be signed in to change notification settings

OMpawar-21/Contentstack.SampleConsole

Repository files navigation

Contentstack .NET SDK – Sample Console Application

📖 What is This Project?

This is a learning and demonstration application that shows you how to use Contentstack (a content management system) with .NET applications. Think of it as an interactive tutorial that lets you explore and test different features of Contentstack through a simple menu-driven interface.

What is Contentstack?

Contentstack is a headless Content Management System (CMS) that allows you to:

  • Store and manage your content (like blog posts, product information, pages, etc.)
  • Access that content through APIs (Application Programming Interfaces)
  • Use the same content across websites, mobile apps, and other platforms

What Does This Application Do?

This console application acts as a testing and learning tool that demonstrates how to:

  • Connect to your Contentstack account
  • Retrieve different types of content
  • Search and filter content
  • Work with images and files (assets)
  • Sync content for offline use
  • Query content using taxonomies (categories/tags)

It's perfect for:

  • Developers learning how to integrate Contentstack into .NET applications
  • Content managers who want to understand what's possible with the API
  • Anyone who wants to explore their Contentstack content programmatically

🎯 Key Features

This application provides a comprehensive menu system to explore Contentstack features:

  1. 📋 List Content Types - See all the different types of content in your stack
  2. 🔍 Query Entries - Search and filter your content entries
  3. 📄 Fetch Single Entry - Get detailed information about a specific content item
  4. 🔄 Sync Operations - Download and sync all your content for offline use
  5. 🖼️ Asset Management - Browse and manage images, videos, and files
  6. 🏷️ Taxonomy Queries - Search content by categories, tags, or hierarchical structures

📋 Prerequisites (What You Need Before Starting)

1. .NET SDK (Development Framework)

You need the .NET 7.0 SDK (or later) installed on your computer.

What is .NET SDK?

  • It's a free development framework from Microsoft
  • It allows you to build and run .NET applications
  • Think of it as the "engine" that runs this application

How to Check if You Have It: Open a terminal/command prompt and type:

dotnet --version

If you see a version number (like 7.0.317), you're good! If not, download it from Microsoft's .NET website.

2. Contentstack Account and Stack

You need:

  • A Contentstack account (free tier available at contentstack.com)
  • A Stack (a workspace in Contentstack)
  • API Key - A unique identifier for your stack
  • Delivery Token - A security key that allows reading content
  • Environment - Usually "production" or "development"
  • At least one Content Type with some published Entries (content items)

Don't have these? Don't worry! The setup section below will guide you.


🚀 Setup Instructions (Step-by-Step)

Step 1: Get Your Contentstack Credentials

  1. Log in to Contentstack at app.contentstack.com

  2. Select or Create a Stack

    • If you're new, create a stack
    • If you have one, select it from the dashboard
  3. Find Your API Key

    • Go to SettingsStack
    • Copy the API Key
  4. Create a Delivery Token

    • Go to SettingsTokens
    • Click + New Token
    • Name it (e.g., "Sample Console App")
    • Select your environment (usually "development" or "production")
    • Click Generate
    • Copy the token
  5. Note Your Environment Name

    • This is usually "development", "production", or "staging"
    • You'll see it in the environment dropdown

Step 2: Configure the Application

You have two options to provide your credentials:

Option A: Using App.config File (Recommended for Beginners)

  1. Open the App.config file in the project folder
  2. Replace the placeholder values with your actual credentials:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="api_key" value="YOUR_API_KEY_HERE" />
        <add key="delivery_token" value="YOUR_DELIVERY_TOKEN_HERE" />
        <add key="environment" value="development" />
        <add key="host" value="" />
    </appSettings>
</configuration>

Example:

<add key="api_key" value="" />
<add key="delivery_token" value="" />
<add key="environment" value="" />

⚠️ Important: Never commit your real credentials to version control (like GitHub)!

Option B: Using Environment Variables (Advanced)

If you prefer using environment variables (more secure for production):

On Windows (PowerShell):

$env:CONTENTSTACK_API_KEY="your_api_key"
$env:CONTENTSTACK_DELIVERY_TOKEN="your_delivery_token"
$env:CONTENTSTACK_ENVIRONMENT="development"

On macOS/Linux (Terminal):

export CONTENTSTACK_API_KEY="your_api_key"
export CONTENTSTACK_DELIVERY_TOKEN="your_delivery_token"
export CONTENTSTACK_ENVIRONMENT="development"

Step 3: Create Some Content (If You Don't Have Any)

  1. In Contentstack, go to Content Types
  2. Create a new Content Type (e.g., "Blog Post" or "Product")
  3. Add some fields (Title, Description, etc.)
  4. Go to Entries and create at least one entry
  5. Publish the entry (important - unpublished entries won't show up!)

▶️ How to Run the Application

Method 1: From the Project Folder

  1. Open a terminal/command prompt
  2. Navigate to the project folder:
    cd /path/to/Contentstack.SampleConsole
  3. Run the application:
    dotnet run

Method 2: From Anywhere

If you're in a parent folder:

dotnet run --project Contentstack.SampleConsole

What You'll See

After running, you'll see a menu like this:

----------------------------------------
  Contentstack .NET SDK – Sample Console
----------------------------------------
  1. List content types
  2. Entries (content type wise)
  3. Fetch single entry
  4. Sync (show total count)
  5. Assets
  6. Taxonomy Queries
  7. Exit
----------------------------------------
Enter choice (1-7):

Simply type the number of the option you want and press Enter!


📚 Detailed Feature Guide

1. List Content Types

What it does: Shows you all the different types of content in your Contentstack stack.

How to use:

  1. Select option 1 from the main menu
  2. You'll see a list of all content types with their UIDs and titles
  3. A submenu will appear with options to:
    • View the schema (structure) of all content types
    • View the schema of a specific content type

Example output:

Content Types:
  [1] uid: blog_post, title: Blog Post
  [2] uid: product, title: Product
  [3] uid: page, title: Page

Use case: Understanding what types of content are available in your stack.


2. Entries (Content Type Wise)

What it does: Searches and retrieves content entries from a specific content type.

How to use:

  1. Select option 2 from the main menu
  2. Enter a content type UID (or press Enter to auto-detect)
  3. Optionally add filters to narrow down results:
    • Choose a field to filter by
    • Select a filter type (equals, not equals, less than, etc.)
    • Enter the value to filter for
  4. View the results with all fields displayed

Filter Types:

  • Equals - Exact match
  • Not Equals - Exclude matches
  • Less Than - For numbers/dates
  • Greater Than - For numbers/dates
  • Regex - Pattern matching
  • In List - Match any value in a comma-separated list

Example:

Content type UID: blog_post
Add filter? (y/n): y
Field UID: title
Query type: 1=Equals, 2=Not equals...
Enter (1-6): 1
Value: My First Post

Use case: Finding specific content items based on criteria.


3. Fetch Single Entry

What it does: Retrieves detailed information about one specific content entry.

How to use:

  1. Select option 3 from the main menu
  2. Enter the content type UID (e.g., blog_post)
  3. Enter the entry UID (you can find this in Contentstack or from option 2)
  4. View all the entry's fields and data

Example:

Content type UID: blog_post
Entry UID: blt1234567890abcdef

Use case: Getting complete details about a specific piece of content.


4. Sync (Show Total Count)

What it does: Downloads and synchronizes all your content from Contentstack. This is useful for:

  • Offline access
  • Building local databases
  • Initial content migration
  • Keeping a local copy

How to use:

  1. Select option 4 from the main menu
  2. Choose from sync options:
    • Full sync - Downloads everything
    • Full sync with locale - Downloads content for a specific language
    • Full sync by type - Filters by content type (entries, assets, deleted items)
    • Full sync by content type - Downloads only specific content types
    • Delta sync - Downloads only changes since last sync (requires sync token)
    • Next page - Continues downloading if there are multiple pages

Important: The first sync may take time if you have a lot of content. Save the sync_token for future delta syncs!

Use case: Creating local backups, offline access, or initial data migration.


5. Assets

What it does: Manages images, videos, documents, and other files stored in Contentstack.

How to use:

  1. Select option 5 from the main menu
  2. Choose from asset options:
    • Fetch all assets - Lists all files in your asset library
    • Fetch single asset - Get details about a specific file
    • Count assets - See how many files you have

Use case: Browsing your media library, getting file URLs, or checking asset metadata.


6. Taxonomy Queries

What it does: Searches content based on categories, tags, or hierarchical taxonomies.

Taxonomy = A way to organize content into categories, tags, or hierarchical structures (like product categories with subcategories).

How to use:

  1. Select option 6 from the main menu
  2. Choose a query type:
    • Exists - Find entries that have any term in a taxonomy
    • Equal and Above - Find entries with a term and all its parent categories
    • Above - Find entries with parent categories only
    • Equal and Below - Find entries with a term and all its child categories
    • Below - Find entries with child categories only
  3. Enter the taxonomy key (e.g., taxonomies.category)
  4. Enter the term UID (if required)

Example:

Taxonomy key: taxonomies.product_category
Term UID: blt1234567890

Use case: Finding all products in "Electronics" category, or all blog posts tagged with "Technology".


🏗️ Project Structure

This project is organized following best practices for maintainability and clarity:

Contentstack.SampleConsole/
├── Constants/              # All constant values (menu options, config keys)
│   ├── MenuOptions.cs     # Menu choice constants
│   └── ConfigKeys.cs      # Configuration key names
│
├── Services/              # Business logic and operations
│   ├── ConfigurationService.cs      # Handles app configuration
│   ├── ContentstackService.cs      # Wrapper for Contentstack API
│   ├── MenuService.cs              # Menu display and input
│   ├── ContentTypesMenuService.cs  # Content types operations
│   ├── EntriesMenuService.cs       # Entry query/fetch operations
│   ├── SyncMenuService.cs          # Sync operations
│   ├── AssetsMenuService.cs        # Asset operations
│   └── TaxonomyMenuService.cs      # Taxonomy queries
│
├── Helpers/               # Utility functions
│   ├── JsonHelper.cs     # JSON serialization utilities
│   └── ObjectHelper.cs   # Object value extraction utilities
│
├── Models/                # Data models
│   ├── SampleEntry.cs    # Entry model
│   └── SampleEntryWithRef.cs  # Entry with references model
│
├── Program.cs            # Main application entry point
├── App.config            # Configuration file
└── README.md            # This file!

Why This Structure?

  • Separation of Concerns - Each file has a single, clear purpose
  • Easy to Maintain - Find and fix issues quickly
  • Easy to Extend - Add new features without breaking existing code
  • Well Documented - Every class and method has comments explaining what it does
  • Follows Best Practices - Uses industry-standard C# coding patterns

🐛 Troubleshooting

Problem: "Missing required configuration"

What it means: The application can't find your Contentstack credentials.

Solution:

  1. Check that App.config has the correct values
  2. Or set environment variables (see Setup Step 2)
  3. Make sure there are no typos in the keys or values

Problem: "Contentstack error: [error message]"

Common causes and solutions:

  1. Invalid API Key or Delivery Token

    • Double-check you copied them correctly
    • Make sure there are no extra spaces
    • Verify they're from the correct stack
  2. Wrong Environment

    • Check that the environment name matches exactly (case-sensitive)
    • Common values: "development", "production", "staging"
  3. Network Issues

    • Check your internet connection
    • Verify Contentstack is accessible (visit app.contentstack.com)
  4. Token Permissions

    • Make sure your delivery token has read permissions
    • Check that it's not expired or revoked

Problem: "(none returned)" or Empty Results

Possible reasons:

  1. No Content Published

    • Make sure you've published entries in Contentstack
    • Unpublished entries won't appear in API results
  2. Wrong Content Type

    • Verify the content type UID is correct
    • Check that the content type has entries
  3. Environment Mismatch

    • Ensure your delivery token is for the correct environment
    • Published content must be in the same environment
  4. Filter Too Restrictive

    • If using filters, try removing them
    • Check that filter values match your data

Problem: Application Won't Start

Check these:

  1. .NET SDK Installed?

    dotnet --version

    Should show version 7.0 or higher

  2. In Correct Directory? Make sure you're in the project folder or use:

    dotnet run --project Contentstack.SampleConsole
  3. Dependencies Installed? Try restoring packages:

    dotnet restore

💡 Tips for Best Experience

  1. Start Simple - Begin with option 1 (List Content Types) to see what's available

  2. Use Filters Wisely - When querying entries, start without filters, then add them to narrow results

  3. Save Sync Tokens - If you use sync, save the sync_token for faster delta syncs later

  4. Check Content First - Make sure you have published content in Contentstack before testing

  5. Read Error Messages - They usually tell you exactly what's wrong

  6. Explore Submenus - Many options have submenus with additional features


🔒 Security Notes

⚠️ Important Security Reminders:

  1. Never Commit Credentials - Don't push App.config with real credentials to GitHub
  2. Use Environment Variables - For production, prefer environment variables over config files
  3. Rotate Tokens - Regularly update your delivery tokens
  4. Limit Token Permissions - Only grant the minimum permissions needed
  5. Keep Tokens Secret - Treat tokens like passwords

📝 Code Quality Features

This project demonstrates professional software development practices:

Well-Organized Code - Clear folder structure and separation of concerns
Comprehensive Documentation - Every class and method is documented
Error Handling - Graceful error handling throughout
Type Safety - Strong typing and validation
Constants Usage - No magic numbers or hardcoded strings
Maintainable - Easy to understand, modify, and extend
Best Practices - Follows C# and .NET conventions


🎓 Learning Resources

For Beginners

For Developers

  • Contentstack .NET SDK: Check the SDK documentation for advanced features
  • API Reference: Explore Contentstack's REST API documentation
  • Source Code: Review the Services folder to understand implementation patterns

🤝 Contributing

If you want to improve this project:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

📄 License

This is a sample/educational project. Check the license file for details.


❓ Need Help?

  • Contentstack Support: support.contentstack.com
  • Stack Overflow: Tag questions with contentstack and .net
  • GitHub Issues: Open an issue in the repository

🎉 You're All Set!

You now have a fully functional Contentstack exploration tool. Start with option 1 and explore your content!

Happy coding! 🚀

About

Sample Console App, to understand working of .dotNet Delivery SDK of ContentStack

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages