Using GitHub Copilot chat in Visual Studio 2022

This article demonstrates the advantages and features of GitHub Copilot Chat in Visual Studio 2022 through practical application scenarios and sample code. Finally, readers are encouraged to try to use Copilot Chat in actual work to improve development efficiency and code quality. I hope this information and experience can help and inspire you when using GitHub Copilot.

1. Background

In recent years, the advent of GitHub Copilot has brought new possibilities to the world of software development. As an intelligent programming tool, it greatly improves the programming efficiency of developers. In order to better understand and master the usage skills of GitHub Copilot, I participated in an event called "GitHub Copilot Developer Training Camp".

event display board

2. Activity review

The offline venue in Beijing is in the conference room of the Forbidden City in Beijing Microsoft Building. This is also the first time I have been to Microsoft Building.

microsoft building

This activity can be described as fruitful. Several teachers in the meeting shared GitHub Copilot usage skills and best practices, and gave practical demonstrations. We explore how GitHub Copilot can help developers increase productivity, innovate, and bridge skills gaps. By using GitHub Copilot, developers can focus on solving critical and practical problems, accelerate prototyping, and easily learn new technologies, thereby increasing productivity. In addition, teacher Xu Lei listed 10 examples of AI performing well in programming scenarios, showing how AI can achieve excellent results in various programming tasks, including regular expression writing, writing test code, using hard-to-remember keywords, etc. . As an intelligent programming tool, GitHub Copilot has great potential to help developers improve development efficiency and code quality.

Practical session

Of course, there are also some slight regrets. Our chubby Teacher Lu is actually in Shanghai, but it is also great to see Teacher Xu Lei offline. Another regret is probably that I didn't catch up with the pre-meeting photoshoot. In the morning, I was helping my big friend grab toys for Children’s Day, so I strayed into the art museum, and then I watched the beautiful artwork all morning, so I missed my meal. When we arrived at the meeting place, it was time for the official start. After looking at the conference photo album, I guess it was early to have a separate photo session. It's a pity that only one display board can be placed on it.

In the meeting, mainly introduced the function of Copilot, and showed how to use Copilot Chat in VS Code. Combined with GitHub's Codespaces, we can experience a very convenient and efficient programming process in a completely cloud-based development environment. However, how to use Copilot chat in Visual Studio, known as the most powerful IDE on the surface? Next, let us discuss together.

3. Enable Copilot Chat

3.1 Confirm permissions

Copilot Chat is a capability in GitHub Copilot X, which uses OpenAI GPT-4. For its introduction, you can go to https://github.com/features/preview/copilot-x?WT.mc_id=DT-MVP-5005195 View .

It is still in preview state. If you want to use this feature, first you need to make sure you have registered and have Github Copilot permissions: https://github.com/features/copilot/?WT.mc_id=DT-MVP-5005195

For regular users, you can try Copilot for one month. After confirming that you have the right to use Copilot, you can submit an application for access to the preview function here: https://aka.ms/GHCopilotXPPSignup?WT.mc_id=DT-MVP-5005195 .

After submitting the application, wait for the review, and the review result will be sent to your mailbox. When you receive the "Welcome to the Copilot chat private beta!" email, it means you can use Copilot chat.

waitlist

3.2 Install the plugin

Installing the Copilot Chat extension in Visual Studio 2022 is very simple, just search and githubselect in the extension management Visual Studio Extension for GitHub Copilot Preview.

extension installation

You can also go directly to the Marketplace to download , and then open and install it directly after completion.

After the installation is complete, you need to make sure you have logged in to your Github account in Visual Studio. If you are not familiar with this step, you can go to the help to see: Using GitHub account in Visual Studio .

If there is no problem with the operation, you can find it in the view of the top menu Copilot Chat:

menu

4. User experience

It is said that it would be better to communicate with Copilot in English, but when I saw the interface of Copilot Chat in Visual Studio, I can rest assured of his Chinese comprehension ability:

UI

4.1 How to interact

There are two ways to interact with Copilot chat. In addition to opening the resident dialog window, you can also call out the dialog floating window through the right-click menu (the default shortcut key Alt + /).

right click menu

For dialog-related codes, you can use the cursor to locate a certain line of code, the opening end of a certain class or method. When you activate the dialog, a pink box will remind you of the code area related to the current dialog. Of course, you can also After selecting the relevant area, exhale through the right key:

area

4.2 Analyzing the current exception

In addition to the previous two forms of interaction, when a bug occurs during program debugging, you can also quickly ask for a solution through the "Copilot AI Assistant" in the exception panel:

Copilot

For demonstration here, I modified the code of a normal project to cause a life cycle-related exception. When you click "Copilot AI Assistant", its action is actually to enter "Analyze the current exception" in the dialog box:

exception information

Through the reply results of the above Copilot chat, we will find that the reply here is in English. Students who are familiar with GPT should know that the AI's reply will be adjusted according to the language you prompted (after all, a large number of English error messages are input to AI in the invisible input). However, when I asked again "what is the current error of the program", his reply was intriguing:

ask questions

Of course, his limitations are necessary, since he is, after all, a programming buddy. I also seem to understand his description of not understanding my colloquialism, just like MOSS's warning: no metaphors, rhetorical questions, hints.

Here is a little trick, when your program reports an error, you can ask questions like this to get the error analysis in Chinese: "Analyze the current exception and reply in Chinese"

Analyze the current exception

4.3 Simple test

Next, we simply conduct a few tests to experience some of the convenience brought by Copilot chat. Of course, AI can completely crush humans in many programming scenarios, and more functions need to be explored by yourself. The only certainty is that in the future, programming can basically be separated from search engines and enjoy a more efficient development experience.

4.3.1 Conversational programming

With Copilot chat, in fact, we can complete our development work through continuous chatting and dialogue with it. Next, I tried to let it help me create a WeChat user object for storing in the database:

create object

Here we don't need to worry about naming the object, and we don't need to think about what fields to store. More importantly, he understands our WeChat, and the results generated here are completely fine. He can even put it directly into my project through a shortcut, without me copying and pasting.

4.3.2 Code Explanation

We will have scenarios where we need to read source code, such as: taking over new projects, learning open source projects, etc. The code explanation function of Copilot chat can help us save a lot of time and effort, and he can give you the result in a few milliseconds. Here's a piece of code I'm using to ask him:

/// <summary>
/// 验证来源
/// </summary>
/// <param name="msg_signature">微信的签名</param>
/// <param name="timestamp">时间戳</param>
/// <param name="nonce">随机字符</param>
/// <param name="echostr">加密的字符串</param>
/// <returns></returns>
public string VerifyURL(string msg_signature, string timestamp, string nonce, string echostr)
{
    
    
    // 微信加解密库
    var wxcpt = new WXBizMsgCrypt(_wechat.Value.Token, _wechat.Value.EncodingAesKey, _wechat.Value.CorpId);

    // 接入验证,需要输出 EchoStr 的解密结果
    if (!string.IsNullOrWhiteSpace(echostr))
    {
    
    
        string sEchoStr = "";
        var ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr);
        if (ret != 0)
        {
    
    
            _logger.LogError("ERR: VerifyURL fail, ret: " + ret);
            return "";
        }
        return sEchoStr;
    }
    _logger.LogError("ERR: VerifyURL fail, empty echostr");
    return "";
}

Here's what the reply says:

这个函数是 VerifyURL。它有四个参数:msg_signature,timestamp,nonce 和 echostr。这个函数的主要目的是用于验证接口连接。
首先,这个函数会创建 WXBizMsgCrypt 的对象,该对象的实例用于微信消息的加解密。然后它会检查 echostr 的值是否为非空,如果不为空,则需要将 echostr 的解密结果输出。
为了完成解密过程,这个函数使用 wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr) 方法,该方法返回一个 int 值。如果返回的不是 0,则表示解密失败,函数会通过记录日志输出错误信息并返回空字符串。否则,将解密后的字符串 sEchoStr 返回。
如果 echostr 的值为空,则表示验证失败。函数会记录一个错误日志信息并返回一个空字符串。
如果您需要进一步了解 WXBizMsgCrypt 和如何进行微信消息的加解密,请参考微信官方文档。

code explanation

4.3.3 Answers to questions

First, let's look at a piece of code:

public DbSet<MsgList> MsgLists {
    
     get; private set; }
public DbSet<CursorCache> CursorCache {
    
     get; set; }

The second line of this code is generated by AI. I used the code I wrote earlier private set. Here I ask him: What is the difference between using private set and set here, and which one is better?

The AI's reply here is very accurate, explaining the access level and purpose of set and private set in detail. For beginners, this is undoubtedly very useful, he can help you continuously improve the level of programming.

set 和 private set 是两种访问器的访问限定。 set 具有 public 的访问级别,而 private set 只有类本身内部可以访问。
当你使用 set 时,任何人都可以更改属性的值。这意味着,如果属性的值是不应该更改的,那么你应该使用 private set 而不是set。 这有助于保护对象不受不受控制的更改,并使代码更加安全。
让我们以 OnModelCreating 方法为例。这个方法只会在类内部中被访问,而不会外部进行更改。因此,建议使用 private set 以保护代码。

answer

4.3.4 Provide optimization suggestions

At the same time, he can also help you review the code and provide suggestions for modification. Of course, the tips here are still applicable, and remember to keep up with the "reply in Chinese" later, otherwise the large paragraphs of English will make him forget that the question is in Chinese.

optimization suggestion

4.4 Writing unit tests

Unit testing is an integral part of the software development process, it helps us ensure the quality and functional correctness of the code. Copilot chat can help us quickly create unit tests. The following is the unit test generated for my minimal web API project:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Moq;
using System.Net.Http;
using System.Threading.Tasks;
using WeChatCustomerAzureOpenAI.WeChat;
using Xunit;

public class WeChatCustomerAzureOpenAITest
{
    
    
    private readonly TestServer _server;
    private readonly HttpClient _client;

    public WeChatCustomerAzureOpenAITest()
    {
    
    
        _server = new TestServer(new WebHostBuilder()
            .UseEnvironment("Development")
            .UseStartup<Startup>());
        _client = _server.CreateClient();
    }

    [Fact]
    public async Task Verify_WeChatURL()
    {
    
    
        //Arrange
        var url = "/wechatback?msg_signature=test&timestamp=0&nonce=0&echostr=123";
        //Act
        var response = await _client.GetAsync(url);
        //Assert
        response.EnsureSuccessStatusCode();
        var responseString = await response.Content.ReadAsStringAsync();
        var expectedString = "123";
        Assert.Equal(expectedString, responseString);
    }

    [Fact]
    public async Task Check_Decrypt_Msg()
    {
    
    
        //Arrange
        var sMsg = "123";
        var requestContent = new StringContent(sMsg);
        var context = new DefaultHttpContext();
        context.Request.ContentLength = requestContent.Headers.ContentLength;
        context.Request.Body = await requestContent.ReadAsStreamAsync();

        var wechat = new Mock<WechatServices>().Object;

        var mediator = new Mock<IMediator>().Object;

        var expectedString = sMsg;
        //Act
        var result = await _server.Host.GetService<WechatServices>().DecryptMsg(sMsg, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>());
        await _server.Host.GetService<Mediator>().Publish(new UserBack(result));

        //Assert
        Assert.Equal(expectedString, result);
    }
}

unit test

The unit test here, of course, cannot be used directly, but he has completed a process from zero to one. Through continuous dialogue and adjustment, we will generate satisfactory results.

5. Finally

If you're interested in Copilot and AI and want to learn more, there's a free course from Microsoft Learn that's perfect for you: Learn AI with GitHub Copilot . This series of videos guides you into the world of AI, exploring the basics of machine learning, showing how to build a classification model, and then introducing more advanced algorithms (called neural networks) and their application to computer vision.

Finally, keep this quote in mind: AI itself won’t replace you, but someone with AI skills might. Therefore, I hope everyone can embrace innovation, try new tools, and improve development efficiency and code quality. Let us look forward to the continuous development of Copilot and other similar AI tools to help more developers easily cope with programming challenges and write better software works.

Guess you like

Origin blog.csdn.net/marin1993/article/details/130833441