Introduction
Learn how to solve unusual task in Microsoft Visual Studio 2022 and later using GitHub Copilot Chat.
Overview
- Learn how to read an unorthodox file structure
- Transform json data
- Create a .svg file
- Create a class using the builder pattern
Example 1
A developer receives the following text file with a unusual format, people separated with a dashed line and has extra whitespace at the end of the file.
Note
The prompt used here could had been done with more details but lets kee it simple for learning purposes. For how to create great prompts check out the following youtube video.
The file comes from an external source so and the external source refuses to provide a different format.
Karen
Payne
09/24/1956
------------------------------------
Jim
Beam
08/23/1923
------------------------------------
Anne
Jones
12/14/1987
------------------------------------
Step 1
Create, in this case a new console project and place the above text file into the root of the project named people.txt and set Copy to Output Directory to Copy if newer.
Step 2
Open GitHub Copilot Chat from the upper right corner of VS2022 IDE.
Ask Copilot to read the file
read #file:'people.txt' into a Person class
Using # will provide a list of file names to select from, select people.txt
Click the paper airplane at the bottom of the chat window for Copilot to provide a solution.
The solution (too large to show here)
- Provides explanations of code produced.
- Provides step-by-step instructions and code
Code to read the file.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace EncodeJsonApp
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateOnly BirthDate { get; set; }
public static List<Person> ReadPeopleFromFile(string filePath)
{
var people = new List<Person>();
var lines = File.ReadAllLines(filePath);
for (int i = 0; i < lines.Length; i += 4)
{
if (i + 2 < lines.Length)
{
var firstName = lines[i].Trim();
var lastName = lines[i + 1].Trim();
var birthDate = DateOnly.ParseExact(lines[i + 2].Trim(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
people.Add(new Person
{
FirstName = firstName,
LastName = lastName,
BirthDate = birthDate
});
}
}
return people;
}
}
}
Code to perform the work using the code above.
using System;
using System.Collections.Generic;
namespace EncodeJsonApp
{
class Program
{
static void Main(string[] args)
{
string filePath = "EncodeJsonApp/people.txt";
List<Person> people = Person.ReadPeopleFromFile(filePath);
foreach (var person in people)
{
Console.WriteLine($"Name: {person.FirstName} {person.LastName}, Birth Date: {person.BirthDate}");
}
}
}
}
Step 3
Copilot provides a button for the Person class to be inserted into a new file, click it.
Step 4
We did not ask Copilot to handle trailing empty lines, lets add code for this.
var lines = File.ReadAllLines(filePath)
.Where(line => !string.IsNullOrWhiteSpace(line))
.ToArray();
Next for clarity let's rename the variable i to index as index is much easier to read.
Step 5
For the code to run above code, use Copilot's copy code button and paste into Program.cs.
using System;
using System.Collections.Generic;
namespace EncodeJsonApp
{
class Program
{
static void Main(string[] args)
{
string filePath = "EncodeJsonApp/people.txt";
List<Person> people = Person.ReadPeopleFromFile(filePath);
foreach (var person in people)
{
Console.WriteLine($"Name: {person.FirstName} {person.LastName}, Birth Date: {person.BirthDate}");
}
}
}
}
Change
string filePath = "EncodeJsonApp/people.txt";
To
string filePath = "people.txt";
So people in the executable folder is read from.
Note
Add Console.ReadLine(); may be needed after the foreach
Step 6
Press F5 to ran to get the following.
Step 7
The method Person.ReadPeopleFromFile belongs in a separate file.
- Reference the Person class use #Person (a list is provided)
- Explain the refactor
extract from class ReadPeopleFromFile method to a new class file named FileOperations
Click the paper airplane and the following is provided. Click insert button.
Remove ReadPeopleFromFile method from the Person class and update Program.Main method as shown below.
Press F5 to ran to get the following, same as before the refactoring.
Optional steps
Person class and FileOperations files are in the root folder of the project.
Consider
- Creating a Models folder and place Person class in this folder.
- Create a Class folder and place FileOperations in this folder.
Example 1 summary
The lessons here are getting started with asking a simple question for (dependent on experience of the developer) how to deal with an uncommon task using references to files via # option for Copilot. Also, not trying to have everything done in a single Copilot prompt.
Example 1 code
Example 2
The task is to take the following json and encode with accent characters.
[
{
"FirstName": "José",
"LastName": "Fernández "
},
{
"FirstName": "Miguel",
"LastName": "López"
},
{
"FirstName": "Ángel",
"LastName": "Pérez"
}
]
Open the file and press CTRL + /
Enter the following prompt.
encode FirstName and LastName with HTML accent characters
Click the Paper Airplane and we get.
Alternate
In a class like the Main method of a console project, use # to select the file and use the same prompt as the first time.
Example 2 summary
Copilot can be useful for more than code, here the reader learned how to work with a structured file.
Example 3
A developer wants to learn the builder pattern. Let’s try asking Copilot to create a class using the builder pattern to create a simple example for constructing a house. Note since we keep the prompt simple or purpose so once the code is understood more code can be added such as assertion.
The prompt
Create a class using the builder pattern for a house
Copilot produces the following which a developer use the insert in a new file.
public class House
{
public string Foundation { get; private set; }
public string Structure { get; private set; }
public string Roof { get; private set; }
public string Interior { get; private set; }
private House() { }
public class Builder
{
private readonly House _house;
public Builder()
{
_house = new House();
}
public Builder SetFoundation(string foundation)
{
_house.Foundation = foundation;
return this;
}
public Builder SetStructure(string structure)
{
_house.Structure = structure;
return this;
}
public Builder SetRoof(string roof)
{
_house.Roof = roof;
return this;
}
public Builder SetInterior(string interior)
{
_house.Interior = interior;
return this;
}
public House Build()
{
return _house;
}
}
}
Copilot also provides sample code for trying out the above code.
partial class Program
{
static void Main(string[] args)
{
House house = new House.Builder()
.SetFoundation("Concrete")
.SetStructure("Wood and Brick")
.SetRoof("Shingles")
.SetInterior("Modern")
.Build();
Console.WriteLine($"House Details:\nFoundation: " +
$"{house.Foundation}\nStructure: " +
$"{house.Structure}\nRoof: {house.Roof}\nInterior: {house.Interior}");
Console.ReadLine();
}
}
Example 3 summary
Here the point was to show how Copilot can help learn new coding techniques.
Example 4
Using .svg files are preferred for showing images for web projects. Let's have Copilot create a red asterisk svg file.
In any file, press CTRL + /
Enter the following prompt followed by clicking the paper airplane.
create a red asterisk svg file
Response in a file named NewFile.txt
<svg width="100" height="100" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2V22M2 12H22M4.93 4.93L19.07 19.07M4.93 19.07L19.07 4.93" stroke="red" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
Save it as RedAsterisk.svg
Note
The height and width can easily be changed to suit the needs of a task.
Article summary
Information has been provided to use Copilot Chat and inline prompting. Prompting was kept simple as prompt engineering is a completely different topic.