Develop C# Apps

Prerequisites

This tutorial assumes that you have:

  • installed YugabyteDB, created a universe, and are able to interact with it using the Redis shell. If not, please follow these steps in the quick start guide.
  • installed Visual Studio

Writing a HelloWorld C# app

In your Visual Studio create a new Project and choose Console Application as template. Follow the instructions to save the project.

Install StackExchange.Redis C# driver

To install the driver in your Visual Studio project

  • Open your Project Solution View.
  • Right-click on Packages and click Add Packages.Add Package
  • Search for StackExchange.Redis and click Add Package.Search Package

Copy the contents below to your Program.cs file.

  1. using System;
  2. using System.Collections.Generic;
  3. using StackExchange.Redis;
  4. namespace Yugabyte_CSharp_Demo
  5. {
  6. class Program
  7. {
  8. static private void printHash(HashEntry[] hashes)
  9. {
  10. foreach (var hashEntry in hashes)
  11. {
  12. Console.WriteLine(string.Format("{0}: {1}", hashEntry.Name, hashEntry.Value));
  13. }
  14. }
  15. static void Main(string[] args)
  16. {
  17. try
  18. {
  19. ConfigurationOptions config = new ConfigurationOptions
  20. {
  21. EndPoints =
  22. {
  23. { "127.0.0.1", 6379 },
  24. },
  25. CommandMap = CommandMap.Create(new HashSet<string>
  26. { // EXCLUDE commands that are not fully supported on YugabyteDB side.
  27. "SUBSCRIBE", "CLUSTER", "TIME", "PING"
  28. }, available: false)
  29. };
  30. ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(config);
  31. IDatabase redisDB = connection.GetDatabase();
  32. var hashKey = "1";
  33. HashEntry[] setHash = {
  34. new HashEntry("name", "John"),
  35. new HashEntry("age", 35),
  36. new HashEntry("language", "C#"),
  37. new HashEntry("client", "Redis")
  38. };
  39. Console.WriteLine("Successfully executed HMSET:");
  40. printHash(setHash);
  41. redisDB.HashSet(hashKey, setHash);
  42. var getHash = redisDB.HashGetAll(hashKey);
  43. Console.WriteLine("Successfully executed HMGET:");
  44. printHash(getHash);
  45. }
  46. catch (RedisConnectionException e)
  47. {
  48. Console.WriteLine("Unable to make a connection to local YugabyteDB. " +
  49. "Error:", e.Message);
  50. }
  51. }
  52. }
  53. }

Running the C# app

Run the C# app from menu select Run -> Start Without Debugging

You should see the following as the output.

  1. Successfully executed HMSET:
  2. name: John
  3. age: 35
  4. language: C#
  5. client: Redis
  6. Successfully executed HMGET:
  7. age: 35
  8. client: Redis
  9. language: C#
  10. name: John