.NET Archives - PowerD365 https://powerd365.net/category/net/ Training platform for Microsoft business applications Mon, 28 Mar 2022 16:45:39 +0000 en-GB hourly 1 https://wordpress.org/?v=6.8 The Current Status Of The Windows Forms Designer For .NET Applications https://powerd365.net/the-current-status-of-the-windows-forms-designer-for-net-applications/ https://powerd365.net/the-current-status-of-the-windows-forms-designer-for-net-applications/#respond Thu, 24 Mar 2022 11:59:46 +0000 https://powerd365.net/?p=3696 The Windows Forms (WinForms) Team has been working hard over the last few Visual Studio release cycles to bring the WinForms designer for.NET applications up to equivalence with the.NET Framework designer. As you may know, a new WinForms designer was required to support.NET Core 3.1 and later.NET 5+ apps. As a result of the [...]

The post The Current Status Of The Windows Forms Designer For .NET Applications appeared first on PowerD365.

]]>

The Windows Forms (WinForms) Team has been working hard over the last few Visual Studio release cycles to bring the WinForms designer for.NET applications up to equivalence with the.NET Framework designer. As you may know, a new WinForms designer was required to support.NET Core 3.1 and later.NET 5+ apps. As a result of the differences between.NET and the.NET Framework-based WinForms designer that everyone knows and loves, the task necessitated a near-complete redesign of the designer. The purpose of this blog post is to provide you with some information on the new architecture and the changes made. And, of course, how those changes will affect you when you develop custom controls and.NET WinForms apps.

After reading this blog post, you should be familiar with the fundamental difficulties that the new WinForms designer is intended to answer, as well as have a high-level grasp of the major components of this new approach.

How far have we come?

While we intended for perfect parity between the OOP designer and the.NET Framework designer for the release of Visual Studio 2022, we still have a few items on the queue. Having said that, the current generation of the OOP designer already has the majority of the substantial enhancements at all essential levels:

Performance: Beginning with Visual Studio 2019 v16.10, the performance of the OOP designer has been significantly enhanced. We tried to enhance the experience of interacting with controls on the design surface, such as selecting and moving controls, by lowering project load times.

Databinding Support: WinForms in Visual Studio 2022 introduces a more simplified method to handling Data Sources in the OOP designer, with a focus on Object Data Sources.

This new method is exclusive to the OOP designer and.NET-based apps.

Extensibility SDK for WinForms Designer: Because of perceived differences between the OOP designer and the.NET Framework designer, producers of third-party controls for.NET will need to use a special WinForms Designer SDK to construct bespoke Control Designers that run in the context of the OOP designer.

An inside peek at the WinForms designer

Designing Forms and User Controls using the WinForms designer reveals a few surprises to those who delve under the hood for the first time:

1. The layout is not “saved” (serialized) by the designer in XML or JSON. It directly serializes the Forms/User Control description to code — in the new OOP designer, which is either C# or Visual Basic .NET When a user places a Toggle on a Form, the code for generating the Button and assigning its properties is created into the Form’s ‘Initialize Component’ function. When you open the form in the designer, the ‘Initialize Component’ function is parsed, and a shadow.NET assembly is built on the fly from that code. This assembly includes an executable version of ‘Initialize Component,’ which is loaded in the designer’s context. The ‘Initialize Component’ function is then called, and the designer can now see the resultant Form with all of its control definitions and given properties. This type of serialization is known as Code Document Object Model serialization, or Code DOM serialization for short. This is why you shouldn’t directly modify ‘Initialize Component’: the method will be overridden the next time you visually alter something on the Form and save it, and your changes will be lost.

2. Every WinForms control has two code layers. The code for control that executes during runtime comes first, followed by a control designer that regulates the behavior at design time. The functionality of the control designer for each control is not incorporated in the designer itself. A specialized control designer, on the other hand, works with Visual Studio services and features.

We encountered a significant issue when we chose to offer apps developed on.NET Core 3.1 and.NET 5+ in the original designer. Visual Studio is built on the.NET Framework, but for projects that target a different runtime, it must round-trip the designer code by serializing and deserializing it. While you can run.NET Framework-based types in.NET Core/.NET 5+ programs with some restrictions, the opposite is not true. This is known as the “type resolution problem.” The Textbox control is a fantastic illustration of this: in.NET Core 3.1, we added a new property named ‘Placeholder Text.’ That property does not exist on ‘Textbox’ in the.NET Framework.

Furthermore, during design time, a Form with all of its controls and components renders itself to the designer. As a result, the code that instantiates the form and displays it in the Designer window must be executed in.NET rather than.NET Framework, so that newer properties available only in.NET also reflect the actual appearance and behavior of the controls, components, and, eventually, the entire Form or User Control.

Because we intend to keep developing and introducing new features in the future, the situation will only worsen. As a result, we needed to create a method that allowed for such cross-framework interactions between the WinForms designer and Visual Studio.

Navigate to the Design Tools Server.

Developers must view their Forms in the designer exactly as they will appear at runtime (WYSIWYG). The Code Dom serializer must execute in the context of the version of.NET the project is targeting, whether it be the ‘Place holder Text’ property from the previous example or the layout of a form with the appropriate default font. And we obviously can’t do that if the Code Dom serialization is going concurrently with Visual Studio. To address this, we execute the designer outside of the process (thus the name Out of Process Designer) in a new.NET (Core) process named DesignToolsServer. The DesignToolsServer process uses the same.NET version and bitness (x86 or x64) as your application.

When you double-click a Form or a User Control in Solution Explorer, Visual Studio’s designer loader service detects the.NET version and creates a DesignToolsServer process. The designer loader then transfers the code from the ‘Initialize Component’ function to the DesignToolsServer process, which can now

operate under the desired.NET runtime and deal with every type and property the runtime supports.

Design-Tools-Server-Bitness

While exiting a process solves the type-resolution problem, it poses a few new problems in terms of user interaction inside Visual Studio. For example, consider the Property Browser, which is included with Visual Studio (and therefore also .NET Framework-based). It’s designed to show the.NET Types, but it can’t since the Code Dom serializer can’t (de)serialize .NET types.

Control Proxies and Custom Property Descriptors

To enable interaction with Visual Studio, the DesignToolsServer presents proxy classes for form components and controls developed in the Visual Studio process, in addition to the genuine components and controls on the form created in the DesignToolsServer.exe process. An object proxy is constructed for each one on the form. While the actual controls are located in the DesignToolsServer process, the object proxy instances are located in the client — the Visual Studio process. If you now pick an actual.NET WinForms control on the form, Visual Studio will select an object proxy instead. And that object proxy does not have the same attributes as its server-side counterpart control.

It instead translates the control’s properties 1:1 with new proxy property descriptors that allow Visual Studio to communicate with the server process.

So, clicking on a button control on the form now causes the following (simplified) series of actions to occur in order for the properties to appear in the Property Browser:

1. The mouse click occurs in the Visual Studio process on a unique window known as the Input Shield. It’s a sneeze guard if you will, and its sole purpose is to intercept mouse messages sent to the DesignToolsServer process.

2. The mouse click is received by the DesignToolsServer and forwarded to the Behavior Service. The Behavior Service locates the control and forwards it to the Selection Service, which performs the appropriate processes to choose that control.

3. During that process, the Behavior Service also locates the corresponding Control Designer and takes the appropriate processes to allow that Control Designer to render any adorners and glyphs are required for that control. Consider the preceding Split Panel example’s Designer Action Glyphs or custom selection marks.

4. The control selection is reported back to Visual Studio’s Selection Service through the Selection Service.

5. Visual Studio now understands which object proxy in the DesignToolsServer corresponds to the specified control. The object proxy is chosen by the Visual Studio selection service. This causes the values of the chosen control (object proxy) in the Property Browser to be updated once again.

6. In turn, the Property Browser searches the Property Descriptors of the chosen object proxy, which are mapped to the proxy descriptors of the real control in the DesignToolsServer’s process. So, for each property that the Property Browser needs to update, it does Get Value on the corresponding proxy Property Descriptor, which results in a cross-process call to the server to obtain the real value of that control’s property, which is then shown in the Property Browser.

Designer-Processes-Diagram

Features that will be added in the future and those that will be taken off

While we have almost reached parity with the.NET Framework Designer, there are still a few places where the OOP Designer needs improvement:

1. The Tab Order interaction has been developed and is being tested. This functionality will be available in Visual Studio 17.1 Preview 3 when it is released. Apart from the Tab Order feature now included in the.NET Framework Designer, we intend to expand the Tab Order Interaction, making it simpler to reorder, particularly in huge forms or portions of large forms.

2. The Component Designer has not yet been completed, but we are actively working on it. However, the use of Components is fully supported, and the Component Tray is compatible with the.NET Framework Designer. It should be noted, however, that not all of the components that were available by default in the Toolbox in the.NET Framework are supported in the OOP Designer. We have chosen not to support in the OOP Designer certain components that are only available through.NET Platform Extensions (see Windows Compatibility Pack). If you still require certain components, you can utilize them directly in.NET code.

3. The OOP Designer does not include the Typed DataSet Designer. The same is true for type editors in the.NET Framework that go straight to the SQL

Query Editor (like the DataSet component editor). Typed DataSets require the Data Source Provider Service, which is not provided by WinForms. While they have improved the support for Object Data Sources and urge Developers to use it in conjunction with more recent ORMs like EFCore, the OOP Designer can only accept typed DataSets on existing forms that have been migrated from.NET Framework applications.

Highlights and noteworthy takeaways

So, while the majority of the fundamental Designer capability is identical to that of the.NET Framework Designer, there are several crucial differences:

They removed the.NET WinForms Designer from the procedure. While Visual Studio 2022 only supports the 64-bit.NET Framework, the new Designer’s server process operates in the bitness of the project and as a.NET process. This, however, comes with a few breaking changes, mostly with the creation of Control Designers.

Object Data Sources are fundamental to data binding. While legacy support for Typed Dataset-based data layers is presently restricted, they encourage adopting contemporary ORMs like EntityFramework or, even better, EFCore for.NET. To create Object Data Sources, use the DesignBindingPicker and the new Databinding Dialog.

The WinForms Designer Extensibility SDK is required by control library writers that want greater Design-Time Support for their controls than custom-type editors. Framework control designers can no longer operate without changing them for the new.NET WinForms Designer’s OOP architecture.

Let us know what subjects you’d want to hear about in relation to the WinForms Designer—the new Object Data Source capability in the OOP Designer and the WinForms Designer SDK are currently in the works and at the top of our list.

Please keep in mind that the WinForms.NET runtime is open source, and you are welcome to contribute! Check out the WinForms GitHub repo if you have any suggestions, have encountered issues, or wish to take on PRs related to the WinForms runtime.

The post The Current Status Of The Windows Forms Designer For .NET Applications appeared first on PowerD365.

]]>
https://powerd365.net/the-current-status-of-the-windows-forms-designer-for-net-applications/feed/ 0
GitHub Actions For .NET: An Overview https://powerd365.net/github-actions-for-net-an-overview/ https://powerd365.net/github-actions-for-net-an-overview/#respond Thu, 24 Mar 2022 11:41:46 +0000 https://powerd365.net/?p=3686 Understand how GitHub Actions can enhance your .NET programming workflow and workplace efficiency in this article. I'll teach you about using workflow composition to automate common .NET app development situations. An overview of GitHub Actions By the support of GitHub Actions, programmers who use GitHub to manage their repositories have robust integration (CI) and [...]

The post GitHub Actions For .NET: An Overview appeared first on PowerD365.

]]>

Understand how GitHub Actions can enhance your .NET programming workflow and workplace efficiency in this article. I’ll teach you about using workflow composition to automate common .NET app development situations.

An overview of GitHub Actions

By the support of GitHub Actions, programmers who use GitHub to manage their repositories have robust integration (CI) and continuous deployment (CD) functionality. When programmers submit modifications to a GitHub repository’s primary subsidiary (usually main), this is a typical developer dilemma. While these modifications are frequently reviewed by users, robotic tests can be used to guarantee that the code builds and the tests execute. 

GitHub Actions enable you to create, debug, and publish your code directly from your https://github.com codebase. Workflows on GitHub absorb GitHub Actions. Within your Git repository, a YAML (either *.yml or *.yaml) file is called a GitHub workflow. These process files are located at the root of the repository’s.github/workflows/ directory. A workflow is a set of instructions that includes one or more GitHub Actions, each of which performs a specified action.

The GitHub Actions jargon

Let’s specify a few of these concepts so that we don’t use them incorrectly:

  • GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform for automating your build, test, and deployment process.
  • A workflow is a programmable automated procedure that performs one or more tasks.
  • A workflow run is triggered by an event, which is a specific activity in a repository.
  • A job is a series of workflow stages that all run on the same runner.
  • An action is a GitHub Actions platform custom application that performs a sophisticated but regularly repeated activity.
  • runner: When your workflows are triggered, a runner is a server that executes them.

The workflow code on GitHub

Workflow requirements are outlined in the order in which tasks should be completed and the actions that should be followed. Each process has a title and a collection of prompts, or actions, that must be addressed. Unless your process is repeatable, you must define at least one trigger for it to execute. When modifications are published or a merge application is sent to the standard line, a common .NET GitHub workflow is to build and test your C# code. Take a look at the following procedural file: 

name: build and test
on:
push:
pull_request:
branches: [ main ] paths-ignore:
‘README.md’
env:
DOTNET_VERSION: ‘6.0.x’
jobs:
build-and-test:
name: build-and-test-${{matrix.os}}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest] steps:
– uses: actions/checkout@v2
– name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
– name: Install dependencies
run: dotnet restore
– name: Build
run: dotnet build –configuration Releaseno-restore
– name: Test
run: dotnet test —no-restore –verbosity normal

I’m not presuming you know everything there is to know about this process, and even though it’s only thirty lines long, there’s still a lot to unpack. I created a Mermaid-powered flow chart to explain how a programmer may perceive this procedure.

visualize-this-workflow

Here’s the identical workflow document, but with explicit remarks to add background (if you’re familiar with the workflow terminology, you can skip to another stage).

# The name of the workflow.
# This is the name that’s displayed for status
# badges (commonly embedded in README.md files).
name: build and test
# Trigger this workflow on a push, or pull request to
# the main branch, when either C# or project files changed
on:
push:
pull_request:
branches: [ main ] paths-ignore:
‘README.md’
# Create an environment variable named DOTNET_VERSION
# and set it as “6.0.x”
env:
  DOTNET_VERSION: ‘6.0.x’ # The .NET SDK version to use
# Defines a single job named “build-and-test”
jobs:
build-and-test
# When the workflow runs, this is the name that is logged
# This job will run three times, once for each “os” defined
name: build-and-test-${{matrix.os}}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest] # Each job run contains these five steps
steps:
# 1) Check out the source code so that the workflow can access it.
– uses: actions/checkout@v2
# 2) Set up the .NET CLI environment for the workflow to use.
#    The .NET version is specified by the environment variable.
– name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
# 3) Restore the dependencies and tools of a project or solution.
– name: Install dependencies
run: dotnet restore
 # 4) Build a project or solution and all of its dependencies.
 – name: Build
run: dotnet build –configuration Releaseno-restore
# 5) Test a project or solution.
– name: Test
run: dotnet test —no-restore –verbosity normal

The following workflow file has multiple comments that assist in understanding each step of the process. You’ll see that the instructions cover a variety of GitHub Actions and basic run instructions. The connection here between devouring GitHub workflow and a GitHub Action is that workflows consume actions. The consumption workflow determines how effective a GitHub Action is. Workflows can be used to specify anything from simple chores to complex creations, and almost anything within. See the .NET docs pages below for more information on how to create GitHub processes for .NET apps:

Checking the progress of GitHub

One of the most important advantages of workflows is that they allow you to design conditional status checks that can algorithmically reject a deployment. A workflow could be set up to verify the state of a pull request (PR), and if the workflow rejects — for example, because the PR’s source code doesn’t generate — the PR can be denied from merging. Take a look at the image below, which indicates that two tests ended in failure, preventing the PR from being integrated.

failing-github-status-checks

As the programmer is responsible for evaluating a PR, you’d notice that the pull request has failed state tests right away. To have all of the status tests to clear, you’d collaborate with the developer who submitted the PR. A “green build,” or one that has passed all of its status inspections, is depicted in the image below.

passing-github-status-checks

.NET developers should be familiar with the following GitHub actions

You’re probably acquainted with the .NET CLI if you’re a .NET developer. With the .NET SDK, you get the .NET CLI. You can get the .NET 6 SDK if you don’t currently have the .NET SDK. 

There are 5 phases, each of which contains the run or uses syntax, using the prior workflow file as a guide:

Action or command Description
uses: actions/checkout@v2 This action checks-out your repository under $GITHUB_WORKSPACE, so your workflow can access it. For more information, see actions/checkout
uses: actions/setup-dotnet@v1 This action sets up a .NET CLI environment for use in actions. For more information, see actions/setup-dotnet
run: dotnet restore Restores the dependencies and tools of a project or solution. For more information, see dotnet restore
run: dotnet build Builds the project or solution. For more information, see dotnet build
run: dotnet test Runs the tests for the project or solution. For more information, see dotnet test

Several stages employ GitHub Actions, which are referenced using the user’s terminology, while others execute instructions. Check Workflow syntax for GitHub Actions: uses and runs for extra info on the distinctions.

NuGet bundles are used by .NET apps. Various dependencies that change infrequently, such as NuGet packages, might be cached to improve workflows. You may use actions/cache to cache NuGet packages, for example:

steps:
– uses: actions/checkout@v2
– name: Setup dotnet
uses: actions/setup-dotnet@v1
with:
dotnet-version: ‘6.0.x’
– uses: actions/cache@v2
with:
path: ~/.nuget/packages
# Look to see if there is a cache hit for the corresponding requirements file
key: ${{ runner.os }}-nuget-${{ hashFiles(‘**/packages.lock.json’) }}
restore-keys: |
${{ runner.os }}-nuget
– name: Install dependencies
run: dotnet add package Newtonsoft.Json –version 12.0.1

See GitHub Docs: Building and Testing .NET – Cache Requirements for further details.

You might be curious to learn about some extra GitHub Actions in contrast to using the normal GitHub Actions or citing CLI commands using the launch syntax.

GitHub actions not listed above

Several .NET frameworks are available. The dot net GitHub organisation hosts GitHub Actions:

.NET GitHub Action Description
dotnet/versionsweeper This action sweeps .NET repos for out-of-support target versions of .NET. The .NET docs team uses the .NET version sweeper GitHub Action to automate issue creation. The action runs as a cron job (or on a schedule). When it detects that .NET projects target out-of-support versions, it creates issues to report its findings. The output is configurable and helpful for tracking .NET version support concerns.
dotnet/code-analysis This action runs the code analysis rules that are included in the .NET SDK as part of continuous integration (CI). The action runs both code-quality (CAXXXX) rules and code-style (IDEXXXX) rules.

The .NET developers are creating GitHub Actions which you might find valuable in your company. Check out zyborg/dotnet-tests-report, a GitHub Action that allows you to run .NET testing and produce results and labels. Give their repo a star if you use this GitHub Action.

A few words about .NET workloads

.NET operates on every platform and may be used to create everything. When constructing from a GitHub workflow, there are a few additional tasks that may have to be added. There are numerous tasks accessible; for instance, consider the result of the dot net workflow searching orders: 

dotnet workload search

Workload ID         Description

—————————————————————————————–

android             .NET SDK Workload for building Android applications.

android-aot      .NET SDK Workload for building Android applications with AOT support.

ios                      .NET SDK Workload for building iOS applications.

mac catalyst     .NET SDK Workload for building macOS applications with MacCatalyst.

macos                .NET SDK Workload for building macOS applications.

maui                  .NET MAUI SDK for all platforms

maui-android  .NET MAUI SDK for Android

maui-desktop  .NET MAUI SDK for Desktop

maui-ios           .NET MAUI SDK for iOS

maui-macc catalyst    .NET MAUI SDK for Mac Catalyst

maui-mobile    .NET MAUI SDK for Mobile

maui-windows    .NET MAUI SDK for Windows

tvos                   .NET SDK Workload for building tvOS applications.

wasm-tools     .NET WebAssembly build tools

Synopsis

I discussed the key differences between GitHub Actions and GitHub workflows in this post. In an example workflow file, I described and inspected each line. Then I showed you how a developer could use a sequence diagram to monitor the execution of a GitHub workflow. I mentioned a few extra resources that you may not be aware of. See .NET Docs: GitHub Actions and.NET for further details.

The post GitHub Actions For .NET: An Overview appeared first on PowerD365.

]]>
https://powerd365.net/github-actions-for-net-an-overview/feed/ 0
Using GitHub Actions To Automate Code Metrics And Class Diagrams https://powerd365.net/using-github-actions-to-automate-code-metrics-and-class-diagrams/ https://powerd365.net/using-github-actions-to-automate-code-metrics-and-class-diagrams/#respond Wed, 23 Mar 2022 17:09:00 +0000 https://powerd365.net/?p=3672 We will be summarising an established GitHub Action built in .NET that could be applied to manage a code metrics html file in this article. Then a demonstration on how to use .NET to develop your custom GitHub Actions. I'll teach you ways to create meta - data that identifies a GitHub repository as [...]

The post Using GitHub Actions To Automate Code Metrics And Class Diagrams appeared first on PowerD365.

]]>

We will be summarising an established GitHub Action built in .NET that could be applied to manage a code metrics html file in this article. Then a demonstration on how to use .NET to develop your custom GitHub Actions. I’ll teach you ways to create meta – data that identifies a GitHub repository as an activity. Lastly, I’ll tie everything up with a super awesome illustration: upgrading an action on the .NET demos repository to incorporate data model support with GitHub’s newly designed Mermaid diagram feature, so it builds upgraded class diagrams with every edit. 

Using .NET to create a custom GitHub Action

Various types of developing apps are supported by actions:

Action type Metadata specifier Description
Docker runs.using: ‘docker’ Any app that can run as a Docker container.
JavaScript runs.using: ‘javascript’ Any Node.js app (includes the benefit of using actions/toolkit).
Composite runs.using: ‘composite’ Composes multiple run commands and uses actions.

Because .NET can operate in Microservices, you’ll need to containerize your project if you want a fully functional .NET app to operate as a GitHub Action. See .NET Docs: Containerize a .NET App for more information on .NET with Docker.

Rather than containerizing a .NET project, you could construct a .NET worldwide utility that can be downloaded and invoked using the run terminology rather than the uses. This method is valuable for constructing a .NET CLI software which can be exploited as an universal solution, but it’s outside the subject of this article. See .NET Docs: Global Tools for more information on .NET global tools

The goal of the instructional

A guide on building a GitHub Action with .NET may be found on the .NET Docs. It explains methods to containerize a .NET application, as well as how to compose the action.yml file that contains the action’s information and receive it from a pipeline. Instead of duplicating the whole guide, I’ll outline the act’s purpose and then discuss how it was modified. 

The tutorial application analyses code metrics by doing the following:

  • In a source repository, screening and identifying *.csproj and *.vbproj project files.
  • Examining the identified source code in these projects for the following:

Complexity of cyclomatic structure

Index of maintainability

Inheritance levels

coupling by class

Number of source code lines

Lines of executable code estimated

  • Making a CODE METRICS.md file (or modifying one).

When the CODE METRICS.md document updates, a pull proposal is generated dynamically (and immediately) as an element of the receiving pipeline architecture. To put it another way, when you publish modifications to your Repo, the cycle executes and utilises the .NET code metrics action to update the markdown form of the coding measures. The CODE METRICS.md file is accessible, with automated connections and parts that may be collapsed. Images are used to emphasize code metrics at a peek; for example, when a module has a high cyclomatic complexity, an emoji comes to the surface to the design stage, leading the markup. You can then go deeper into the class and look at the performance measures for each technique. 

Microsoft.CodeAnalysis is a library that analyses code. The Code Analysis Metric Data class in the Code Metrics library provides the Cyclomatic Complexity attribute. This characteristic is a gauge of the code’s morphology. It’s made by calculating the amount of various code routes in the project’s cycle. A system with a complex control flow will require more testing to obtain high code quality and will be more difficult to sustain. When the program is inspected and the CODE METRICS.md file is updated, the GitHub Action adds an emoji to the header using the following syntax: 

internal static string ToCyclomaticComplexityEmoji(
this CodeAnalysisMetricData metric) =>
    metric.CyclomaticComplexity switch
    {
>= 0 and <= 7 => “:heavy_check_mark:”//
8 or 9 => “:warning:”,                  //
10 or 11 => “:radioactive:”,            //
        >= 12 and <= 14 => “:x:”,               //
        _ => “:exploding_head:”//
    };

This action’s code is available in the .NET freebies repo, as well as in the .NET documentation code samples web interface. The action is auto as an example of usage (or dogfooding). The operation continues as the code changes, and it keeps track of CODE METRICS.md in a CODE METRICS.md file via periodic pull submissions. Take a look at the screencaps below, which demonstrate some of the most important portions of the html folder:

Heading CODE METRICS.md

code-metrics-markdown

Project File Reference pipe heading CODE METRICS.md

code-metrics-markdown-drill-down

The coding statistics html file offers the succeeding structure to describe the code it analyses:

Project ➡ Namespace ➡ Named Type ➡ Members table

When you dig deeper into a specified class, there is a hyperlink to the auto-generated diagram at the bottom of the table. This is covered in the chapter on adding features. See .NET samples to navigate the example file on your own. CODE METRICS.md. 

Metadata for actions

A GitHub repository must define metadata in an action.yml file in order to be identified as a GitHub Action.

# Name, description, and branding. All of which are used for
# displaying the action in the GitHub Action marketplace.
name: ‘.NET code metric analyzer’
description: ‘A GitHub action that maintains a CODE_METRICS.md file,
reporting cyclomatic complexity, maintainability index, etc.’
branding:
icon: sliders
colour: purple
# Specify inputs, some are required and some are not.
inputs:
owner:
description: ‘The owner of the repo. Assign from github.repository_owner. Example: “dotnet”.’
required: true
name:
description: ‘The repository name. Example: “samples”.’
required: true
branch:
description: ‘The branch name. Assign from github.ref. Example: “refs/heads/main”.’
required: true
dir:
description: ‘The root directory to work from. Example: “path/to/code”.’
required: true
workspace:
description: ‘The workspace directory.’
required: false
default: ‘/github/workspace’
# The action outputs the following values.
outputs:
summary-title:
description: ‘The title of the code metrics action.’
summary-details:
description: ‘A detailed summary of all the projects that were flagged.’
updated-metrics:
description: ‘A boolean value, indicating whether or not the CODE_METRICS.md
was updated as a result of running this action.’
# The action runs using docker and accepts the following arguments.
runs:
using: ‘docker’
image: ‘Dockerfile’
args:
– ‘-o’
– ${{ inputs.owner }}
– ‘-n’
– ${{ inputs.name }}
– ‘-b’
– ${{ inputs.branch }}
– ‘-d’
– ${{ inputs.dir }}
– ‘-w’
– ${{ inputs.workspace }}

The .NET sampling code statistics action’s metadata is nested within a subdirectory, therefore it isn’t recognised as an action that may be presented in the GitHub Action marketplace. It can, however, still be used as an action.

See GitHub Docs: Metadata syntax for GitHub Actions for additional information about metadata.

Workflow efficiency

A workflow file must exist in the.github/workflows directory from the root of the GitHub repository to consume the .NET code metrics action. Take a look at the following workflow file:

name: ‘.NET code metrics’
on:
push:
branches: [ main ] paths-ignore:
# Ignore CODE_METRICS.md and README.md files
– ‘**.md’
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
– uses: actions/checkout@v2
# Analyse repositories source metrics:
# Create (or update) CODE_METRICS.md file.
– name: .NET code metrics
id: dotnet-code-metrics
uses: dotnet/samples/github-actions/DotNet.GitHubAction@main
with:
owner: ${{ github.repository_owner }}
name: ${{ github.repository }}
branch: ${{ github.ref }}
dir: ${{ ‘./github-actions/DotNet.GitHubAction’ }}
# Create a pull request if there are changes.
– name: Create pull request
uses: peter-evans/create-pull-request@v3.4.1
if: ${{ steps.dotnet-code-metrics.outputs.updated-metrics }} == ‘true’
with:
title: ‘${{ steps.dotnet-code-metrics.outputs.summary-title }}’
body: ‘${{ steps.dotnet-code-metrics.outputs.summary-details }}’
commit-message: ‘.NET code metrics, automated pull request.’

To create, this workflow uses jobs.job id>.permissions, setting contents, and pull-requests. This is necessary for the process of updating the repo’s data and creating a request form based on those modifications. Watch GitHub Docs: Workflow syntax for GitHub Actions – permissions for more information on permits.

The following sequence diagram can be used to illustrate how this procedure works:

code-metrics-action-workflow-sequence-diagram

  • When a programmer uploads code to the GitHub repository.
  • The workflow is started after it has been triggered.
  • The code written is saved in the $GITHUB WORKSPACE directory.
  • The action .NET code metrics are used.
  • The CODE METRICS.md file is updated once the source code is analysed.
  • The create-pull-request action is triggered if the .NET code metrics step (dotnet-code-metrics) outputs that metrics were changed.
  • The file CODE METRICS.md has been added to the repository.
  • A pull request is created automatically. See .NET examples / pull requests for an example of pull requests made by the app/github-actions bot.

Incorporating more features

GitHub has introduced Mermaid-powered Latex diagram capability. Our customised method has a conceptual grasp of the types it’s evaluating because it can analyse C# as part of its execution. In the CODE METRICS.md file, this is used to generate Mermaid class diagrams programmatically.

Metrics for .NET code Mermaid support has been added to the GitHub Action example code.

static void AppendMermaidClassDiagrams(
MarkdownDocument document,
List<(string Id, string Class, string MermaidCode)> diagrams)
{
document.AppendHeader(“Mermaid class diagrams”, 2);
foreach (var (id, className, code) in diagrams)
{
document.AppendParagraph($”
{id}”>
“);
document.AppendHeader($”`{className}` class diagram”, 5);
document.AppendCode(“mermaid”, code);
}

The ToMermaidClassDiagram extension function can be used to inspect the code that generates the diagrams parameter. See the following diagram for an example of how this looks in the CODE METRICS.mdMarkdown file:
mermaid-class-diagram

Synopsis

You learnt about the many sorts of GitHub Actions in this blog, with a focus on Containers and .NET. I described how the GitHub Action for .NET code statistics was upgraded to incorporate Mermaid data model functionality. You also viewed a sample action.yml document, which acts as GitHub Action information. The ingesting pipeline was then shown, as well as how the code metrics action is ingested. I also showed you how to extend the code metrics action with new features.

What are you going to develop, and how will it benefit others? Create and share your own .NET GitHub Actions, and I encourage you to do so.

The post Using GitHub Actions To Automate Code Metrics And Class Diagrams appeared first on PowerD365.

]]>
https://powerd365.net/using-github-actions-to-automate-code-metrics-and-class-diagrams/feed/ 0
Microsoft Has Launched .NET Tech Community Forums https://powerd365.net/microsoft-has-launched-net-tech-community-forums/ https://powerd365.net/microsoft-has-launched-net-tech-community-forums/#respond Tue, 22 Mar 2022 13:55:07 +0000 https://powerd365.net/?p=3585 .NET is a single platform that allows developers to create world-class apps that run on a variety of operating systems and platforms. There is a global community of millions of developers who use.NET to build apps and support new developers who just started developing. We began our quest last year to unify.NET communities in [...]

The post Microsoft Has Launched .NET Tech Community Forums appeared first on PowerD365.

]]>

.NET is a single platform that allows developers to create world-class apps that run on a variety of operating systems and platforms. There is a global community of millions of developers who use.NET to build apps and support new developers who just started developing. We began our quest last year to unify.NET communities in terms of conversations and technical assistance. First, we introduced Microsoft Q&A for.NET, a repository for.NET technical questions and answers. Month after month, the number of visitors, queries, and replies from the community and Microsoft staff has increased dramatically. We’d like to thank everyone for their participation in Q&A, which has resulted in over 80% of questions being addressed each month!

We’re not done yet, since we’ve heard from our developer community that a space for further interactions beyond Q&A is required. You have indicated that you are searching for a dedicated forum where you can conduct technical conversations, debate best practises, discuss new releases, and offer how-to instruction. That is why we are excited to unveil the.NET Tech Community Forums, which will cover all.NET developer issues and conversations!

select-a-discussion-space

Features of the Tech Community

There is a conversation place for you whether you are a web developer, mobile & desktop developer, interested in microservices, data, machine learning, or are just getting started! Join the.NET tech community, choose a discussion space, start a new conversation, and engage with other.NET developers!

start-a-discussion

Topics to Follow

Every subject on the.NET Tech Community may be followed, allowing you to get updates through e-mail, RSS feeds, or your tech community home page.

Engage in more communities

The nicest thing about the.NET Tech Community is that it is a part of the greater Microsoft Tech Community. You may join, follow, and create discussions in a variety of product and special subject community hubs.

join-more-communities

Establish your profile and gain achievements.

Who doesn’t appreciate achieving milestones and praises for helping out the community and discussing their favourite topics?

build-your-profile

The new.NET Tech Community will coexist with Microsoft Q&A:

  • Microsoft Q&A for.NET – for technical help and questions.NET
  • Tech Community – for technical discussions, how-tos, and more.

The debut of both Tech Community and Q&A helps integrate with all Microsoft products for developers, including Azure, Teams, Office, and more, which are available on both platforms.

The post Microsoft Has Launched .NET Tech Community Forums appeared first on PowerD365.

]]>
https://powerd365.net/microsoft-has-launched-net-tech-community-forums/feed/ 0
ASP.NET And ASP.NET Core. How To Share Code? https://powerd365.net/asp-net-and-asp-net-core-how-to-share-code/ https://powerd365.net/asp-net-and-asp-net-core-how-to-share-code/#respond Tue, 22 Mar 2022 13:30:26 +0000 https://powerd365.net/?p=3581 There are even more incentives to use ASP.NET Core now that.NET 6 has been released. However, moving old code to ASP.NET Core might appear to be a major expenditure. Today, we'll show you how to make the migration to ASP.NET Core go smoother. There are some simple modifications you can make today to make [...]

The post ASP.NET And ASP.NET Core. How To Share Code? appeared first on PowerD365.

]]>

There are even more incentives to use ASP.NET Core now that.NET 6 has been released. However, moving old code to ASP.NET Core might appear to be a major expenditure. Today, we’ll show you how to make the migration to ASP.NET Core go smoother. There are some simple modifications you can make today to make the transition to ASP.NET Core simpler tomorrow.

Let’s start with a hypothetical situation. Let’s look at how to update code in a 10-year-old programme to make it compatible with ASP.NET Core. The ShoppingCartController.cs from the MVC Music Store project that was used to demonstrate ASP.NET MVC3 will be migrated in the following parts.

Controllers can always be shared.

Controllers are the first item you may share between the two projects. Many groups want the new website to function in the same way as the old one. And we mean “the same” when we say “the same.” If you solve an issue in one project, the identical solution must be applied to both sites. Sharing the same file in different projects is one of the simplest ways to ensure this functionality. Fortunately, ASP.NET Core makes advantage of the new SDK project files. Because the files are fairly readable, it’s simple to access the csproj file and make modifications.

To begin sharing a Controller class, build an ItemGroup> and include a reference to the existing class in it. Here’s an example of how to share the ShoppingCartController.cs by modifying the ASP.NET Core project’s csproj file.

<ItemGroup> <Compile Include=”..MvcMusicStoreControllersShoppingCartController.cs”

LinkBase=”Controllers” /> </ItemGroup>

Okay, the file is now included in the project, but as you may expect, the ASP.NET Core project no longer compiles. The Controller class in ASP.NET Core utilises Microsoft.AspNetCore.Mvc instead of System.Web.Mvc.

Here’s an example of how the ShoppingCartController.cs may fix the compiler problem by using both namespaces.

#if NET using Microsoft.AspNetCore.Mvc; #else using System.Web.Mvc; #endif

There are a few more locations in the ShoppingCartController that need to be modified, but the procedure is the same. We can make the class flexible enough to compile for both projects by using C# preprocessing directives.

YOU MAY WISH TO DEVELOP IMPLEMENTATION SPECIFIC FILES FOR SCENARIOS WITH SIGNIFICANT CHUNKS OF CODE THAT FUNCTION DIFFERENTLY FOR ASP.NET CORE. CREATE A PARTIAL CLASS AND EXTRACT THOSE CODE BLOCKS TO NEW METHOD(S) THAT DIFFER BETWEEN THE TWO WEB APP TARGETS, THEN USE CSPROJ TO CONTROL WHICH FILES ARE INCLUDED WHEN CREATING THE PROJECT.

Models can be shared.

We’ll want to share the Models they return now that we can share Controllers. In many cases, this will simply start functioning after we include them in the csproj file by adding another <ItemGroup>. However, if your models also utilize System. Web, we may apply the same method as we did for Controllers. To begin, change the namespaces so that the same class file may be used in both projects. To add ASP.NET Core support, keep utilising the C# precompiler directives.

Here’s an example of how you may change the [Bind] property.

#if !NET [Bind(Exclude=”OrderId”)] #endif public partial class Order { [ScaffoldColumn(false)] #if NET

[BindNever] #endif publicintOrderId{ get; set; } … …

Views can be shared.

We can even discuss our points of view. We can use the similar way to share files like _Layout.cshtml by editing the csproj file. You may also use C# precompiler directives inside the view to make the file flexible enough to be utilised by both projects.

Here’s how a master page with mixed support for ASP.NET Child Actions and ASP.NET Core View Components appears to render the section of the page that knows how many things are in the shopping cart looks.

@{ #if NET <text>@awaitComponent.InvokeAsync(“CartSummary”)</text> #else @Html.RenderAction(“CartSummary”, “ShoppingCart”); #endif }

Bringing everything to a conclusion

Static data like as CSS, JavaScript, and image are also included in the ability to exchange code. You can add flexibility to your web app today, step by step, to make the transition to ASP.NET Core easier.

You can find a complete tutorial with samples at MvcMusicStoreMigration if you want more extensive instructions on how to migrate the whole ShoppingCartController.cs file. The tour will also show you how to migrate your web project one controller at a time by running both ASP.NET and ASP.NET Core from the same IIS Application Pool.

We’ll give you a few more pointers if you’re ready to start working on your ASP.NET Core conversion.

  • To enable netstandard, you’ll need to upgrade your NuGet packages.
  • To exchange code across ASP.NET and ASP.NET Core, change your class libraries to netstandard.
  • Find references to System. Web in your class libraries and replace them with new interfaces. You may quickly transition between ASP.NET and ASP.NET Core capabilities by using dependency injection.

The post ASP.NET And ASP.NET Core. How To Share Code? appeared first on PowerD365.

]]>
https://powerd365.net/asp-net-and-asp-net-core-how-to-share-code/feed/ 0