Home > Articles

Open Source: GitHub for .NET Developers, Part 1: Version Control

In this new article series, Alessandro Del Sole introduces GitHub, the popular platform for collaboration on open source projects, from the point of view of .NET developers using Visual Studio 2015.
Like this article? We recommend

Like this article? We recommend

Introduction

Without a doubt, open source is becoming more and more important. The term open source not only means releasing your source code to the general public, but also accepting collaboration on your project from other developers. Even Microsoft has strongly embraced open source, releasing many building blocks of the .NET technology as open source projects. Think of .NET Core, the modular runtime for cross-platform applications, or the Visual Basic and C# compilers, which have been open-sourced under the name .NET Compiler Platform (formerly the project "Roslyn"). This approach gives Microsoft the opportunity to accept controlled contributions from the developer community worldwide.

With this way of thinking, open source projects need workspaces that fully support collaboration between development teams and other developers, including source control and task management. Several current platforms support collaboration, such as Team Foundation Server and Visual Studio Team Services, but the most popular is GitHub. For many years, GitHub has been the favorite platform for developers working on systems that are open source by nature, such as Linux. Now, even Microsoft offers all its open source projects on GitHub, including projects that were previously hosted on CodePlex and those comprising the .NET 2015 stack.

This explains why GitHub is becoming more important for developers who work with .NET and Visual Studio 2015, and why you should learn to use at least the most important features and tools of this platform. In this article series, you will learn how to use the tools that Visual Studio 2015 offers for working with open source projects hosted on GitHub. Of course, many of the concepts I discuss in this series will be familiar if you already have experience with other collaboration platforms such as Team Foundation Server.

What Is GitHub?

GitHub is an online platform for sharing source code and for collaborating with other developers, and it's based on the popular Git version-control engine. Git is both interesting and powerful, but because you have to work from the command line, it's not very intuitive, especially for beginners. GitHub makes some steps forward, offering a web-based environment with a graphical user interface; it talks to the Git engine on your behalf.

Every registered GitHub account can host a number of open source projects, each referred to as a repository. The real power of GitHub is that multiple developers, not just the repository's owner, can collaborate on any repository. Visual Studio 2015 includes a special extension for GitHub that allows you to interact with your repositories and collaborate with other people and projects directly from within the development environment. This capability avoids the need for using the Git command line. In most cases, you can also use the GitHub website, making it easy to keep your focus on your code.

In this article series I won't cover the Git command line, and I'll show the GitHub website only when strictly required. Instead, this series will focus deeply on Visual Studio 2015 and its special tools for working with your open source repositories. To make the best use of this series, you should have a GitHub account; you can register for free at https://github.com/join. You will also need Visual Studio 2015, at least Community Edition.

In this first article, I'll show you how to add a Visual Studio solution to GitHub's source control. I'll explain concepts related to local and remote repositories, and show how to add a welcome page and a license agreement to your repositories. In Part 2 of this series, you'll learn how to collaborate on open source projects and some of the tools you can use to manage tasks. In the third and final article, I'll discuss such interesting things as adding documentation files and how to get statistical information.

Adding a Project to GitHub's Source Control

Let's start by creating a new, very simple class library project called FantasticLibrary, as shown in Figure 1. I'm using the Class Library template for the sake of simplicity, but of course you can repeat the same steps with any Visual Studio 2015 solution.

Figure 1 Creating a new sample project.

When the new project is ready, you need to add it to the Git source control, associating the project with a GitHub repository. To accomplish this goal, right-click the solution name in Solution Explorer, and select Add Solution to Source Control. At this point, Visual Studio 2015 will ask you to choose a source control mechanism: either Team Foundation (which might be listed as Team Foundation Server or Visual Studio Team Services) or Git (see Figure 2). Select Git and click OK.

Figure 2 Adding the project to the Git source control.

Some explanations are necessary at this point. When you install Visual Studio 2015, the setup also installs all the necessary Git components to work locally. When you work with Git, a solution is first associated with a local repository, which is added to the source control engine. This means that you actually work locally, and all edits you make to a project are tracked locally. Changes are sent to a corresponding remote repository (we'll create that shortly), which allows for sharing the project with other developers, but only when you explicitly invoke the proper tools.

After you click OK in Solution Explorer, files submitted to source control are displayed with a green plus (+) symbol. Suppose you want to commit the first version of the project. In Solution Explorer, right-click the solution name and click Commit. At this point, Visual Studio shows the Team Explorer tool window, providing an option to describe what's new in this version of the code and showing the list of files that will be committed. Providing a description of the commit is very important, because it helps other developers to understand what edits you made in the new version of committed files. Figure 3 shows how Team Explorer looks before you submit the project for the first commit.

Figure 3 Preparing to commit the first version of the project.

Pay attention to the field called Branch and to its value, master. With Git, a project can be made of multiple channels, each called branch. For each new project, Git automatically creates a new branch called master. As the name implies, this is the main branch in the project. You might want to create additional branches; for instance, if you want to separate the documentation from the source code, or if you want to have one Visual Studio solution per branch. I won't cover creating and managing branches in this article series because it would move our focus too far from the core concepts, but you can check out the GitHub documentation for further details.

Once you've entered a description for your commit, such as First commit in Figure 3, click Commit. Changes (in this case, the whole project) are submitted to a local Git repository that Visual Studio 2015 generates for your project. Team Explorer will show a confirmation message if committing the code succeeds, as shown in Figure 4. The message includes a unique ID assigned to the commit, which is auto-generated by the Git engine; in Figure 4, the ID is 4cc4ccfb.

Figure 4 Local commit executed successfully.

If you switch to Solution Explorer at this point, you'll see that all files under source control display the padlock symbol, which means that the latest version of the code is available in the repository. When you make edits, related files display a red checkmark. Editing re-enables Team Explorer to commit changes, which you can do once you're done with your modifications.

Publishing the Solution to GitHub

Publishing a solution to GitHub makes your source code available at any time via a remote online repository. It also allows other developers, either in your development team or in the developer community, to contribute to your project (this aspect is discussed in Part 2). When you commit your changes to the local repository, Team Explorer displays the commit ID as well as a Sync hyperlink. Clicking this link synchronizes your source code with a remote repository (which we still have to create for the current solution). For this example, go ahead and click Sync.

At this point, you'll be asked to enter your GitHub credentials (see Figure 5).

Figure 5 Entering GitHub credentials.

After authenticating your GitHub credentials, in this example Team Explorer informs you that no remote repository exists for the project you've been working on locally, and it invites you to provide a name. Specify FantasticLibrary as the repository name (see Figure 6) and provide a description, if desired. Finally, click Publish.

Figure 6 Creating a remote repository within Visual Studio 2015.

After a few seconds, Team Explorer informs you that publishing the project to the remote repository has succeeded. To understand what actually happened, open the GitHub website, log in, and select the FantasticLibrary project. As demonstrated in Figure 7, the solution has been correctly published online.

Figure 7 The project is available in the remote GitHub repository.

Every time you commit any changes, GitHub shows the commit description by every file that has a new version. If you make edits online, later you can synchronize those commits with your local repository.

For a better understanding of file versions and commits, let's make some edits to the FantasticLibrary source code. First, rename Class1 as FantasticClass, as shown in Figure 8.

Figure 8 Renaming the auto-generated class.

Next, implement the IDisposable interface to look like the following code:

public class FantasticClass : IDisposable
{

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
            }

            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.

            disposedValue = true;
        }
    }

    // ~FantasticClass() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    void IDisposable.Dispose()
    {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion
}

As Figure 9 shows, the Class1.cs file displays a red checkmark, which means that it has been edited since the last commit.

Figure 9 Files with edits are displayed with a red checkmark.

Now suppose you want to commit your changes to your repository, both locally and remotely. Right-click the solution name and click Commit. In Team Explorer, provide a proper commit description, such as in Figure 10, and then click Commit.

Figure 10 Committing a new version of the source code.

Note that only files with edits are synchronized with the repository, which makes source control very efficient. In Figure 10, only Class1.cs file will be committed. As with the very first commit, you now have published your changes locally, but you also need to share them online. In Team Explorer, click Sync; the list of outgoing commits (typically only one), the author, and the description are displayed (see Figure 11).

Figure 11 Preparing to push the commit to the remote repository.

When ready, click Push and wait for the commit to be synchronized with the remote repository. If you're using Visual Studio 2015 Enterprise, the CodeLens feature will show the commit ID, description, author's name, and the latest updates for a given code block, as in Figure 12.

Figure 12 CodeLens displaying information about commits.

Of course, this feature is particularly useful when you work on a project with other developers. Changes from the latest commit are also visible in the repository's home page, where GitHub shows the description for each commit, making it easy to understand which files have new versions, as shown in Figure 13.

Figure 13 GitHub shows the commit description for each item.

Working with .gitAttribute and .gitIgnore

Every repository needs two additional files, .gitAttributes and .gitIgnore, both of which are automatically generated for you. I won't cover these files in detail here, but it's important to understand some basic information about them:

  • .gitAttributes represents Git settings for the project. The official documentation covers these settings thoroughly.
  • .gitIgnore contains the list of file extensions that are excluded from the source control engine and ignored when you commit changes. Certain files in a Visual Studio solution, by nature, don't need to be submitted to source control. For example, think of .suo files, which contain per-user settings for a solution. If you had to exclude files manually, you would need to know every possible file extension, but Visual Studio 2015 does the job for you, automatically creating and uploading the proper .gitIgnore file, tailored for a .NET project.

Welcoming Visitors to Your Repository

For every repository, GitHub allows you to write a Welcome page, where you can provide a project description, welcome information, links, and whatever else you think is helpful to give users a better idea of your project's purpose. By default, you write a welcome page by creating and editing a file called Readme.md. The .md file extension stands for Markdown, a special markup language commonly used to edit cross-browser text documents. Every document you add to a GitHub repository should be edited using Markdown.

You have two options for adding the Readme.md file:

  • Click the Add a Readme button in the repository's home page.
  • Click New File and specify Readme.md as the filename.

At this point, GitHub offers its Markdown editor to create the document, as shown in Figure 14.

Figure 14 Editing the Readme.md file.

Describing Markdown syntax in detail is outside the scope of this article series, but at minimum you need to know that the number (#) symbol represents a heading and two such symbols (##) represents a subheading; anything that's not between symbols is considered plain text. When you're finished writing the document, click Commit. Notice that you're not simply saving the file; you're actually committing the new file to version control.

Before committing your changes, you can click Preview Changes in the editor to see how the document will look, as demonstrated in Figure 15.

Figure 15 Previewing changes on the Readme.md file.

The same steps apply to any Markdown file you want to create inside a GitHub repository.

Choosing a License Agreement

Choosing the proper license agreement is crucial for any software, and this is even more important with regard to open source projects, because it clarifies how other developers can use your source code in their applications. GitHub provides an easy way to add a license agreement to a repository. In the repository's home page, click New File; then type license.txt. GitHub understands that you want to add a license agreement, and it shows the license picker, a combo box from which you can select one of the popular agreements for open source projects (see Figure 16).

Figure 16 Choosing a license agreement.

Of course, you will have an option to read the content of any license agreement, and you can even write your own. As with documents, you click Commit when you're satisfied with your choice.

Synchronizing Projects

More often than not, you'll probably work on a project from different workstations. GitHub offers the possibility of cloning a repository, and Visual Studio 2015 has built-in tools for this purpose. In Team Explorer, click the Manage Connections link and then enter your GitHub credentials (if required); finally, click Clone. As Figure 17 shows, you'll get a list of repositories associated with your account.

Figure 17 Cloning a repository.

After specifying the path for local repositories on the new machine, click Clone. Visual Studio 2015 creates a local repository for the one you decided to clone, and then Team Explorer will present a list of local solution files (.sln). Cloned repositories are also under source control, so you'll be able to follow all the steps described so far to make edits and commit changes to both the local and the remote repository. This feature ensures that you always work with the latest version of your source code, from anywhere.

Summary

As open source becomes more and more important, developers need specific environments and tools to support collaboration, like GitHub. This first article of the new series explained what GitHub is, why it's very important for developers working with Visual Studio 2015, and how to use the source control tools. In the next article, I'll discuss additional interesting open source topics, such as collaborating with other developers and managing project issues.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020