C# example
Overview
This C# example demonstrates how to interact with the Unity Version Control CM REST API to perform common repository management operations. You can use this code as a foundation for building Unity Version Control integrations into your C# applications or tools.
The example includes a console application that allows you to do the following actions:
- List repositories: View all available repositories on your Unity Version Control server.
- Create repositories: Add new repositories with custom names and server configurations.
- Rename repositories: Update existing repository names.
- Delete repositories: Remove repositories from your server.
The code uses HttpClient
to make REST API calls and demonstrates proper error handling and response parsing patterns that you can apply in your own Unity Version Control integrations.
Program
/Program.cs
using Csharp_examples.Actions;
using Csharp_examples.Models;
using Csharp_examples.Utils;
using System;
using System.Collections.Generic;
namespace Csharp_examples;
class Program
{
static void Main(string[] args)
{
// Display available operations to the user
Console.Write(mActions);
string optionStr = Console.ReadLine();
int option;
Int32.TryParse(optionStr, out option);
// Route to the appropriate repository operation based on user selection
switch (option)
{
case 1:
default:
ListRepositories();
break;
case 2:
CreateRepository();
break;
case 3:
RenameRepository();
break;
case 4:
DeleteRepository();
break;
}
}
static void ListRepositories()
{
// Retrieve all repositories from the Unity Version Control server
List<Repository> repositories = ApiUtils.ReadRepositoryList().Result;
// Display repository information in a readable format
foreach (Repository repo in repositories)
{
Console.WriteLine(string.Format(" {0}_{1} {2} {3}",
repo.RepId.Id, repo.RepId.ModuleId, repo.Name, repo.Server));
}
}
static void CreateRepository()
{
// Collect repository details from user input
Console.Write("Write a name for the repository: ");
string name = Console.ReadLine();
Console.Write("Write the direction of the server: ");
string server = Console.ReadLine();
// Prepare the repository creation request
CreateRepository action = new CreateRepository()
{
Name = name,
Server = server
};
// Send the creation request and display confirmation
Repository newRepo = ApiUtils.CreateRepository(action).Result;
Console.Write(string.Format("Repository {0} successfully created!", newRepo.Name));
}
static void RenameRepository()
{
// Show available repositories so user can select which one to rename
ListRepositories();
Console.Write("Write the name of the repository to rename: ");
string repository = Console.ReadLine();
Console.Write(string.Format("Write a new name for {0}: ", repository));
string newName = Console.ReadLine();
// Prepare the rename request with the new name
Rename action = new Rename()
{
Name = newName
};
// Execute the rename operation and confirm success
Repository renamedRepo = ApiUtils.RenameRepository(repository, action).Result;
Console.Write(string.Format("Repository {0} successfully renamed to {1}.",
repository, renamedRepo.Name));
}
static void DeleteRepository()
{
// Display repositories so user can choose which one to delete
ListRepositories();
Console.Write("Write the name of the repository to delete: ");
string repository = Console.ReadLine();
// Perform the deletion and notify user of completion
ApiUtils.DeleteRepository(repository).Wait();
Console.Write(string.Format("Repository {0} successfully deleted!", repository));
}
// Menu text displayed to guide user through available operations
static string mActions = @"1 - List repositories (cm repository list)
2 - Create a repository (cm repository create)
3 - Rename a repository (cm repository rename)
4 - Delete a repository (cm repository delete)
Select an option (1/2/3/4): ";
}
Actions
These classes define the data structures for API requests. They serve as data transfer objects (DTOs) that are serialized to JSON when making API calls to the Unity Version Control CM server.
/Actions/CreateRepository.cs
namespace Csharp_examples.Actions;
public class CreateRepository
{
public string Name { get; set; }
public string Server { get; set; }
}
/Actions/Rename.cs
namespace Csharp_examples.Actions;
public class Rename
{
public string Name { get; set; }
}
Utils
This utility class handles all HTTP communication with the Unity Version Control CM API. It demonstrates how to
configure HttpClient
for REST API calls and provides reusable methods for common repository operations with proper
error handling.
/Utils/ApiUtils.cs
using Csharp_examples.Actions;
using Csharp_examples.Models;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Csharp_examples.Utils;
public class ApiUtils
{
static HttpClient GetHttpClient()
{
HttpClient client = new HttpClient();
// Configure the base URL for your Unity Version Control CM server
client.BaseAddress = new Uri("http://localhost:9090/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
public static async Task<List<Repository>> ReadRepositoryList()
{
HttpClient client = GetHttpClient();
using (client)
{
// Make GET request to retrieve all repositories
HttpResponseMessage response = await client.GetAsync("api/v1/repos");
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception(string.Format(
"API Status Code {0}. Expected OK.", response.StatusCode));
// Parse the JSON response into a list of Repository objects
return await response.Content.ReadAsAsync<List<Repository>>();
}
}
public static async Task<Repository> CreateRepository(CreateRepository createParams)
{
HttpClient client = GetHttpClient();
using (client)
{
// Send POST request with repository creation parameters
HttpResponseMessage response =
await client.PostAsJsonAsync("api/v1/repos", createParams);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception(string.Format(
"API Status Code {0}. Expected OK.", response.StatusCode));
// Return the newly created repository object
return await response.Content.ReadAsAsync<Repository>();
}
}
public static async Task<Repository> RenameRepository(string repositoryName, Rename renameParam)
{
HttpClient client = GetHttpClient();
// Build the endpoint URL with the target repository name
string uri = string.Format("api/v1/repos/{0}", repositoryName);
using (client)
{
// Send PUT request to update the repository name
HttpResponseMessage response =
await client.PutAsJsonAsync(uri, renameParam);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception(string.Format(
"API Status Code {0}. Expected OK.", response.StatusCode));
// Return the updated repository object with the new name
return await response.Content.ReadAsAsync<Repository>();
}
}
public static async Task DeleteRepository(string repositoryName)
{
HttpClient client = GetHttpClient();
// Build the endpoint URL for the repository to delete
string uri = string.Format("api/v1/repos/{0}", repositoryName);
using (client)
{
// Send DELETE request to remove the repository
HttpResponseMessage response =
await client.DeleteAsync(uri);
// Delete operations return 204 No Content on success
if (response.StatusCode != System.Net.HttpStatusCode.NoContent)
throw new Exception(string.Format(
"API Status Code {0}. Expected NoContent.", response.StatusCode));
}
}
}