### Definição do método Start
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.timers.timer.start
Assinaturas do método Start em diferentes linguagens .NET.
```cpp
public:
void Start();
```
```csharp
public void Start();
```
```fsharp
member this.Start : unit -> unit
```
```vb
Public Sub Start ()
```
--------------------------------
### Group By Query Examples
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/expressions
Examples showing how to group data and perform aggregate calculations.
```vb
Dim averageAges = _
From cust In Customers _
Group By cust.State _
Into Count(), Average(cust.Age)
```
```vb
Dim averageAges = _
From cust In Customers _
Group cust.Age By cust.State _
Into Count(), Average(Age)
```
--------------------------------
### Closure Output Examples
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/expressions
Expected and incorrect output examples for the closure loop demonstration.
```console
1 2 3 4 5 6 7 8 9 10
```
```console
9 9 9 9 9 9 9 9 9 9
```
--------------------------------
### Storyboard Seek Example
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.windows.media.animation.storyboard.seek
Example demonstrating how to control a storyboard after it has started using Seek.
```csharp
/*
This example shows how to control
a storyboard after it has started.
*/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Windows.Documents;
namespace Microsoft.Samples.Animation.AnimatingWithStoryboards
{
public partial class FrameworkContentElementSeekExample : FlowDocument
{
private Storyboard myStoryboard;
private TextBlock currentTimeIndicator;
private TextBox seekDestination;
private TextBlock rectangleWidthIndicator;
private Rectangle myRectangle;
public FrameworkContentElementSeekExample()
{
// Create a name scope for the page.
NameScope.SetNameScope(this, new NameScope());
this.Background = Brushes.White;
BlockUIContainer controlsContainer = new BlockUIContainer();
```
--------------------------------
### Complete app.config Example
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/developing-apps/programming/log-info/walkthrough-changing-where-my-application-log-writes-information
A full example of how the app.config file should look after configuring the listeners for My.Application.Log.
```xml
```
--------------------------------
### Order By Query Examples
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/expressions
Examples demonstrating basic sorting, descending order, and multi-key sorting in Visual Basic queries.
```vb
Dim productsByPrice = _
From p In Products _
Order By p.Price _
Select p.Name
```
```vb
Dim productsByPriceDesc = _
From p In Products _
Order By p.Price Descending _
Select p.Name
```
```vb
Dim customersByLocation = _
From c In Customers _
Order By c.State, c.City, c.ZIP _
Select c.Name, c.State, c.City, c.ZIP
```
--------------------------------
### Install template package legacy syntax
Source: https://learn.microsoft.com/pt-br/dotnet/core/tools/dotnet-new-install
Example of the legacy syntax for installing a template package.
```bash
dotnet new --install Microsoft.Azure.WebJobs.ProjectTemplates
```
--------------------------------
### Order By Translation Example
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/expressions
Demonstrates how a complex Order By query is translated into method calls.
```vb
Dim xs() As Integer = ...
Dim zs = From x In xs _
Order By x Ascending, x Mod 2 Descending _
...
```
```vb
Dim xs() As Integer = ...
Dim zs = _
xs.OrderBy(Function(x) x).ThenByDescending(Function(x) x Mod 2)...
```
--------------------------------
### Configure Host with HostApplicationBuilderSettings
Source: https://learn.microsoft.com/pt-br/dotnet/core/extensions/generic-host
Demonstrates how to initialize a host with custom settings, including JSON files, environment variables, and command-line arguments.
```csharp
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
HostApplicationBuilderSettings settings = new()
{
Args = args,
Configuration = new ConfigurationManager(),
ContentRootPath = Directory.GetCurrentDirectory(),
};
settings.Configuration.AddJsonFile("hostsettings.json", optional: true);
settings.Configuration.AddEnvironmentVariables(prefix: "PREFIX_");
settings.Configuration.AddCommandLine(args);
HostApplicationBuilder builder = Host.CreateApplicationBuilder(settings);
using IHost host = builder.Build();
// Application code should start here.
await host.RunAsync();
```
--------------------------------
### Parsing GUIDs with Specific Formats
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.guid.parseexact
Examples demonstrating how to parse GUID strings using the 'B' format specifier.
```csharp
// Define an array of all format specifiers.
string[] formats = { "N", "D", "B", "P", "X" };
Guid guid = Guid.NewGuid();
// Create an array of valid Guid string representations.
var stringGuids = new string[formats.Length];
for (int ctr = 0; ctr < formats.Length; ctr++)
stringGuids[ctr] = guid.ToString(formats[ctr]);
// Parse the strings in the array using the "B" format specifier.
foreach (var stringGuid in stringGuids)
{
try
{
Guid newGuid = Guid.ParseExact(stringGuid, "B");
Console.WriteLine($"Successfully parsed {stringGuid}");
}
catch (ArgumentNullException)
{
Console.WriteLine("The string to be parsed is null.");
}
catch (FormatException)
{
Console.WriteLine($"Bad Format: {stringGuid}");
}
}
// The example displays output similar to the following:
//
// Bad Format: eb5c8c7d187a44e68afb81e854c39457
// Bad Format: eb5c8c7d-187a-44e6-8afb-81e854c39457
// Successfully parsed {eb5c8c7d-187a-44e6-8afb-81e854c39457}
// Bad Format: (eb5c8c7d-187a-44e6-8afb-81e854c39457)
// Bad Format: {0xeb5c8c7d,0x187a,0x44e6,{0x8a,0xfb,0x81,0xe8,0x54,0xc3,0x94,0x57}}
```
```fsharp
open System
// Define an array of all format specifiers.
let formats =
[| "N"; "D"; "B"; "P"; "X" |]
let guid = Guid.NewGuid()
// Create an array of valid Guid string representations.
let stringGuids =
Array.map guid.ToString formats
// Parse the strings in the array using the "B" format specifier.
for stringGuid in stringGuids do
try
let newGuid = Guid.ParseExact(stringGuid, "B")
printfn $"Successfully parsed {stringGuid}"
with
| :? ArgumentNullException ->
printfn "The string to be parsed is null."
| :? FormatException ->
printfn $"Bad Format: {stringGuid}"
// The example displays output similar to the following:
//
// Bad Format: eb5c8c7d187a44e68afb81e854c39457
// Bad Format: eb5c8c7d-187a-44e6-8afb-81e854c39457
// Successfully parsed {eb5c8c7d-187a-44e6-8afb-81e854c39457}
// Bad Format: (eb5c8c7d-187a-44e6-8afb-81e854c39457)
// Bad Format: {0xeb5c8c7d,0x187a,0x44e6,{0x8a,0xfb,0x81,0xe8,0x54,0xc3,0x94,0x57}}
```
```vb
Module Example
Public Sub Main()
' Define an array of all format specifiers.
Dim formats() As String = { "N", "D", "B", "P", "X" }
Dim guid As Guid = Guid.NewGuid()
' Create an array of valid Guid string representations.
Dim stringGuids(formats.Length - 1) As String
For ctr As Integer = 0 To formats.Length - 1
stringGuids(ctr) = guid.ToString(formats(ctr))
Next
' Parse the strings in the array using the "B" format specifier.
For Each stringGuid In stringGuids
Try
Dim newGuid As Guid = Guid.ParseExact(stringGuid, "B")
Console.WriteLine("Successfully parsed {0}", stringGuid)
Catch e As ArgumentNullException
Console.WriteLine("The string to be parsed is null.")
Catch e As FormatException
Console.WriteLine("Bad Format: {0}", stringGuid)
End Try
Next
End Sub
End Module
' The example displays the following output:
' Bad Format: 3351d3f0006747089ff928b5179b2051
' Bad Format: 3351d3f0-0067-4708-9ff9-28b5179b2051
' Successfully parsed {3351d3f0-0067-4708-9ff9-28b5179b2051}
' Bad Format: (3351d3f0-0067-4708-9ff9-28b5179b2051)
' Bad Format: {0x3351d3f0,0x0067,0x4708,{0x9f,0xf9,0x28,0xb5,0x17,0x9b,0x20,0x51}}
```
--------------------------------
### Implementar o método OnStart
Source: https://learn.microsoft.com/pt-br/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer
Define a lógica executada quando o serviço é iniciado, registrando uma entrada no log de eventos.
```C#
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart.");
}
```
```VB.NET
' To access the OnStart in Visual Basic, select OnStart from the
' method name drop-down list.
Protected Overrides Sub OnStart(ByVal args() As String)
EventLog1.WriteEntry("In OnStart")
End Sub
```
--------------------------------
### Defining a Get procedure in a property
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/language-reference/statements/get-statement
This example demonstrates how to implement a Get procedure within a read-only property to return a string value.
```vb
Class propClass
' Define a private local variable to store the property value.
Private currentTime As String
' Define the read-only property.
Public ReadOnly Property DateAndTime() As String
Get
' The Get procedure is called automatically when the
' value of the property is retrieved.
currentTime = CStr(Now)
' Return the date and time As a string.
Return currentTime
End Get
End Property
End Class
```
--------------------------------
### Instalar o SDK do .NET 8 ou anterior via Snap
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-snap-sdk
Utilize o pacote genérico dotnet-sdk especificando o canal da versão desejada.
```bash
sudo snap install dotnet-sdk --classic --channel 8.0/stable
```
--------------------------------
### Partition Query Operator Translation
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/expressions
Example showing how multiple partition operators are translated into method chains.
```vb
Dim xs() As Integer = ...
Dim zs = From x In xs _
Skip 10 _
Take 5 _
Skip While x < 10 _
Take While x > 5 _
...
```
```vb
Dim xs() As Integer = ...
Dim zs = _
xs.Skip(10). _
Take(5). _
SkipWhile(Function(x) x < 10). _
TakeWhile(Function(x) x > 5)...
```
--------------------------------
### Set TraceId in client
Source: https://learn.microsoft.com/pt-br/dotnet/orleans/grains/request-context
Example of setting a Guid as a trace ID in the client.
```C#
RequestContext.Set("TraceId", Guid.NewGuid());
```
--------------------------------
### Install the .NET package
Source: https://learn.microsoft.com/pt-br/dotnet/api/overview/azure/AI.Language.QuestionAnswering.Inference-readme
Use the .NET CLI to add the required preview package to your project.
```bash
dotnet add package Azure.AI.Language.QuestionAnswering.Inference --prerelease
```
--------------------------------
### Initialize Array Literals
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/expressions
Examples of creating arrays using literals with various types and ranks.
```vb
' array of integers
Dim a = {1, 2, 3}
' array of shorts
Dim b = {1S, 2S, 3S}
' array of shorts whose type is taken from the context
Dim c As Short() = {1, 2, 3}
' array of type Integer(,)
Dim d = {{1, 0}, {0, 1}}
' jagged array of rank ()()
Dim e = {({1, 0}), ({0, 1})}
' error: inconsistent rank
Dim f = {{1}, {2, 3}}
' error: inconsistent rank
Dim g = {1, {2}}
```
--------------------------------
### Instalação manual do .NET no Debian 12 ou superior
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-debian
Configura o repositório Microsoft manualmente para versões do Debian 12 ou mais recentes.
```bash
# Get OS version info which adds the $ID and $VERSION_ID variables
source /etc/os-release
# Download the Microsoft keys
sudo apt-get install -y gpg wget
wget https://packages.microsoft.com/keys/microsoft.asc
cat microsoft.asc | gpg --dearmor -o microsoft.asc.gpg
# Add the Microsoft repository to the system's sources list
wget https://packages.microsoft.com/config/$ID/$VERSION_ID/prod.list
sudo mv prod.list /etc/apt/sources.list.d/microsoft-prod.list
# Move the key to the appropriate place
sudo mv microsoft.asc.gpg $(cat /etc/apt/sources.list.d/microsoft-prod.list | grep -oP "(?<=signed-by=).*(?=\])")
# Update packages and install .NET
sudo apt-get update && \
sudo apt-get install -y {dotnet-package}
```
--------------------------------
### Using a Property
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/type-members
Example demonstrating how to invoke the Get and Set accessors of a property.
```vb
Dim okButton As Button = New Button()
okButton.Caption = "OK" ' Invokes Set accessor.
Dim s As String = okButton.Caption ' Invokes Get accessor.
```
--------------------------------
### CommonItemDialog.ClientGuid Property
Source: https://learn.microsoft.com/pt-br/dotnet/api/microsoft.win32.commonitemdialog.clientguid
Gets or sets a GUID to be associated with the persistent state of the dialog.
```APIDOC
## Property: ClientGuid
### Description
Gets or sets a GUID to be associated with the persistent state of the dialog. This allows the dialog to remember its state across different sessions.
### Signature
`public Guid? ClientGuid { get; set; }`
### Property Value
- **Type**: `Nullable`
### Applies to
- **Product**: Windows Desktop
- **Versions**: 8, 9, 10, 11
```
--------------------------------
### Instalar o SDK do .NET via WinGet
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/windows
Utilize este comando para instalar o SDK do .NET 10.0. Instalar o SDK inclui automaticamente o runtime correspondente.
```bash
winget install Microsoft.DotNet.SDK.10
```
--------------------------------
### Instalar versão mais recente
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-scripted-manual
Instala a versão mais recente do SDK, que pode não ser uma versão LTS.
```bash
./dotnet-install.sh --version latest
```
--------------------------------
### Defining a Property in a Class
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/type-members
Example of a class defining a property with Get and Set accessors.
```vb
Public Class Button
Private captionValue As String
Public Property Caption() As String
Get
Return captionValue
End Get
Set (Value As String)
captionValue = value
Repaint()
End Set
End Property
...
End Class
```
--------------------------------
### Illegal Method Declaration Formatting
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/type-members
Examples of invalid method declarations where statements do not start at the beginning of a logical line.
```VB
Module Test
' Illegal: Subroutine doesn't start the line
Public x As Integer : Sub F() : End Sub
' Illegal: First statement doesn't start the line
Sub G() : Console.WriteLine("G")
End Sub
' Illegal: End Sub doesn't start the line
Sub H() : End Sub
End Module
```
--------------------------------
### Instalar .NET SDK 9.0
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-debian
Instala o SDK do .NET 9.0.
```bash
sudo apt-get update && \
sudo apt-get install -y dotnet-sdk-9.0
```
--------------------------------
### Example Class and Serialization Setup
Source: https://learn.microsoft.com/pt-br/dotnet/core/compatibility/serialization/10/xmlserializer-obsolete-properties
Defines a class with normal, obsolete, and ignored properties, and demonstrates the serialization process.
```csharp
public class Example
{
public string NormalProperty { get; set; } = "normal";
[Obsolete("This property is deprecated")]
public string ObsoleteProperty { get; set; } = "obsolete";
[XmlIgnore]
public string IgnoredProperty { get; set; } = "ignored";
}
var obj = new Example();
var serializer = new XmlSerializer(typeof(Example));
using var writer = new StringWriter();
serializer.Serialize(writer, obj);
Console.WriteLine(writer.ToString());
```
--------------------------------
### Instalar o runtime do .NET 9 via Snap
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-snap-runtime
Comando para instalar o pacote snap do runtime do .NET 9 no terminal.
```bash
sudo snap install dotnet-runtime-90
```
--------------------------------
### Atualizar pacotes .NET via APT
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-debian
Utilize estes comandos para atualizar o .NET quando uma nova versão de patch estiver disponível.
```bash
sudo apt-get update
sudo apt-get upgrade
```
--------------------------------
### Do While...Loop Example
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/language-reference/statements/do-loop-statement
Executes the loop while the index variable is less than or equal to 10, with the condition evaluated at the start of the loop.
```vb
Dim index As Integer = 0
Do While index <= 10
Debug.Write(index.ToString & " ")
index += 1
Loop
Debug.WriteLine("")
' Output: 0 1 2 3 4 5 6 7 8 9 10
```
--------------------------------
### Listar runtimes instalados com CLI do .NET
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/how-to-detect-installed-versions
Execute este comando no terminal para exibir todas as versões do runtime do .NET instaladas.
```bash
dotnet --list-runtimes
```
--------------------------------
### Silo Lifecycle Timing Logs
Source: https://learn.microsoft.com/pt-br/dotnet/orleans/host/silo-lifecycle
Example output showing the time taken for individual components to start within a lifecycle stage.
```text
Information, Orleans.Runtime.SiloLifecycleSubject, "Lifecycle observer Orleans.Runtime.InsideRuntimeClient started in stage 2000 which took 33 Milliseconds."
Information, Orleans.Runtime.SiloLifecycleSubject, "Lifecycle observer Orleans.Statistics.PerfCounterEnvironmentStatistics started in stage 2000 which took 17 Milliseconds."
```
--------------------------------
### New SLNX file format example
Source: https://learn.microsoft.com/pt-br/dotnet/core/compatibility/sdk/10.0/dotnet-new-sln-slnx-default
The structure of a solution file generated by 'dotnet new sln' starting from .NET 10.
```xml
```
--------------------------------
### Accessing Configuration Settings
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.web.configuration.webconfigurationmanager.openwebconfiguration
Examples demonstrating how to retrieve and iterate through appSettings using the OpenWebConfiguration method.
```csharp
// Show how to use OpenWebConfiguration(string).
// It gets he appSettings section of a Web application
// runnig on the local server.
static void OpenWebConfiguration1()
{
// Get the configuration object for a Web application
// running on the local server.
System.Configuration.Configuration config =
WebConfigurationManager.OpenWebConfiguration("/configTest")
as System.Configuration.Configuration;
// Get the appSettings.
KeyValueConfigurationCollection appSettings =
config.AppSettings.Settings;
// Loop through the collection and
// display the appSettings key, value pairs.
Console.WriteLine("[appSettings for app at: {0}]", "/configTest");
foreach (string key in appSettings.AllKeys)
{
Console.WriteLine("Name: {0} Value: {1}",
key, appSettings[key].Value);
}
Console.WriteLine();
}
```
```vb
' Show how to use OpenWebConfiguration(string).
' It gets he appSettings section of a Web application
' runnig on the local server.
Shared Sub OpenWebConfiguration1()
' Get the configuration object for a Web application
' running on the local server.
Dim config As System.Configuration.Configuration = _
WebConfigurationManager.OpenWebConfiguration("/configTest")
' Get the appSettings.
Dim appSettings As KeyValueConfigurationCollection = _
config.AppSettings.Settings
' Loop through the collection and
' display the appSettings key, value pairs.
Console.WriteLine("[appSettings for app at: {0}]", "/configTest")
Dim key As String
For Each key In appSettings.AllKeys
Console.WriteLine("Name: {0} Value: {1}", _
key, appSettings(key).Value)
Next key
Console.WriteLine()
End Sub
```
--------------------------------
### CollectionView.CurrentItem Property
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.windows.data.collectionview.currentitem
The CurrentItem property gets the current item in the view. By default, the first item in the collection starts as the current item.
```APIDOC
## Property: CurrentItem
### Description
Gets the current item in the collection view. This property represents the current record pointer, which can be used to retrieve the object at the current location in the collection.
### Signature
`public virtual object CurrentItem { get; }`
### Property Value
- **Type**: Object
- **Description**: The current item of the view.
### Remarks
- Moving the current record pointer interacts with sorting and filtering applied to the collection.
- If the target of a binding is an ItemsControl, the current item is synchronized with the selected item.
- Classes inheriting from CollectionView should use the `SetCurrent(Object, Int32)` method to update current values rather than overriding this property.
```
--------------------------------
### Accessing Configuration Settings
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.web.configuration.webconfigurationmanager.openwebconfiguration
Examples demonstrating how to retrieve and iterate through appSettings using the OpenWebConfiguration method.
```csharp
// Show how to use OpenWebConfiguration(string, string).
// It gets he appSettings section of a Web application
// runnig on the local server.
static void OpenWebConfiguration2()
{
// Get the configuration object for a Web application
// running on the local server.
System.Configuration.Configuration config =
WebConfigurationManager.OpenWebConfiguration("/configTest",
"Default Web Site")
as System.Configuration.Configuration;
// Get the appSettings.
KeyValueConfigurationCollection appSettings =
config.AppSettings.Settings;
// Loop through the collection and
// display the appSettings key, value pairs.
Console.WriteLine(
"[appSettings for app at: /configTest");
Console.WriteLine(" and site: Default Web Site]");
foreach (string key in appSettings.AllKeys)
{
Console.WriteLine("Name: {0} Value: {1}",
key, appSettings[key].Value);
}
Console.WriteLine();
}
```
```vb
' Show how to use OpenWebConfiguration(string, string).
' It gets he appSettings section of a Web application
' runnig on the local server.
Shared Sub OpenWebConfiguration2()
' Get the configuration object for a Web application
' running on the local server.
Dim config As System.Configuration.Configuration = _
WebConfigurationManager.OpenWebConfiguration( _
"/configTest", "Default Web Site")
' Get the appSettings.
Dim appSettings As KeyValueConfigurationCollection = _
config.AppSettings.Settings
' Loop through the collection and
' display the appSettings key, value pairs.
Console.WriteLine("[appSettings for app at: /configTest")
Console.WriteLine(" and site: Default Web Site]")
Dim key As String
For Each key In appSettings.AllKeys
Console.WriteLine("Name: {0} Value: {1}", _
key, appSettings(key).Value)
Next key
Console.WriteLine()
End Sub
```
--------------------------------
### WPF Reflection Page Initialization
Source: https://learn.microsoft.com/pt-br/dotnet/desktop/wpf/graphics-multimedia/painting-with-images-drawings-and-visuals
Setup code for a WPF Page class, including namespace imports and constructor initialization for the reflection example.
```vbnet
Imports System.Windows
Imports System.Windows.Data
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Media.Effects
Imports System.Windows.Media.Imaging
Imports System.IO
Imports System.Collections.ObjectModel
Imports System.Windows.Shapes
Namespace SDKSample
Partial Public Class ReflectionExample
Inherits Page
Public Sub New()
' Create a name scope for the page.
NameScope.SetNameScope(Me, New NameScope())
Me.Background = Brushes.Black
Dim myStackPanel As New StackPanel()
myStackPanel.Margin = New Thickness(50)
```
--------------------------------
### Instalar .NET SDK 10.0
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-debian
Instala o SDK do .NET 10.0, que inclui as ferramentas necessárias para desenvolvimento.
```bash
sudo apt-get update && \
sudo apt-get install -y dotnet-sdk-10.0
```
--------------------------------
### Property Get Accessor with Side Effects
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/reference/language-specification/type-members
An example of a property getter that modifies object state, which is discouraged as it produces observable side effects.
```vb
Class Counter
Private Value As Integer
Public ReadOnly Property NextValue() As Integer
Get
Value += 1
Return Value
End Get
End Property
End Class
```
--------------------------------
### Instalar pacotes do SDK do Azure via CLI do .NET
Source: https://learn.microsoft.com/pt-br/dotnet/azure/sdk/authentication/system-assigned-managed-identity
Comandos para adicionar as dependências necessárias ao projeto via terminal.
```bash
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.Azure
```
--------------------------------
### Defining a Property with a Set Procedure in Visual Basic
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/language-reference/statements/set-statement
This example demonstrates how to implement a property with both Get and Set procedures to manage a private integer field.
```vb
Class propClass
Private propVal As Integer
Property Prop1() As Integer
Get
Return propVal
End Get
Set(ByVal value As Integer)
propVal = value
End Set
End Property
End Class
```
--------------------------------
### Get object generation in F# and VB.NET
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.gc.getgeneration
Examples demonstrating the use of GC.GetGeneration to track object generations and the impact of garbage collection on strong and weak references.
```fsharp
open System
let maxGarbage = 1000
[]
type MyGCCollectClass() =
member _.MakeSomeGarbage() =
for i = 1 to maxGarbage do
// Create objects and release them to fill up memory
// with unused objects.
Version() |> ignore
// Create a strong reference to an object.
let mutable myGCCol = MyGCCollectClass()
// Put some objects in memory.
myGCCol.MakeSomeGarbage()
// Get the generation of managed memory where myGCCol is stored.
printfn $"The object is in generation: {GC.GetGeneration myGCCol}"
// Perform a full garbage collection.
// Because there is a strong reference to myGCCol, it will
// not be garbage collected.
GC.Collect()
// Get the generation of managed memory where myGCCol is stored.
printfn $"The object is in generation: {GC.GetGeneration myGCCol}"
// Create a WeakReference to myGCCol.
let wkref = WeakReference myGCCol
// Remove the strong reference to myGCCol.
myGCCol <- null
// Get the generation of managed memory where wkref is stored.
printfn $"The WeakReference to the object is in generation: {GC.GetGeneration wkref}"
// Perform another full garbage collection.
// A WeakReference will not survive a garbage collection.
GC.Collect()
// Try to get the generation of managed memory where wkref is stored.
// Because it has been collected, an exception will be thrown.
try
printfn $"The WeakReference to the object is in generation: {GC.GetGeneration wkref}"
stdin.Read() |> ignore
with e ->
printfn $"The WeakReference to the object has been garbage collected: '{e}'"
stdin.Read() |> ignore
```
```vbnet
Namespace GCGetGenerationWeakExample
Class MyGCCollectClass
Private maxGarbage As Long = 1000
Public Shared Sub Main()
' Create a strong reference to an object.
Dim myGCCol As New MyGCCollectClass
' Put some objects in memory.
myGCCol.MakeSomeGarbage()
' Get the generation of managed memory where myGCCol is stored.
Console.WriteLine("The object is in generation: {0}", _
GC.GetGeneration(myGCCol))
' Perform a full garbage collection.
' Because there is a strong reference to myGCCol, it will
' not be garbage collected.
GC.Collect()
' Get the generation of managed memory where myGCCol is stored.
Console.WriteLine("The object is in generation: {0}", _
GC.GetGeneration(myGCCol))
' Create a WeakReference to myGCCol.
Dim wkref As New WeakReference(myGCCol)
' Remove the strong reference to myGCCol.
myGCCol = Nothing
' Get the generation of managed memory where wkref is stored.
Console.WriteLine("The WeakReference to the object is in generation: {0}", _
GC.GetGeneration(wkref))
' Perform another full garbage collection.
' A WeakReference will not survive a garbage collection.
GC.Collect()
' Try to get the generation of managed memory where wkref is stored.
' Because it has been collected, an exception will be thrown.
Try
Console.WriteLine("The WeakReference to the object is in generation: {0}", _
GC.GetGeneration(wkref))
Console.Read()
Catch e As Exception
Console.WriteLine("The WeakReference to the object " & _
"has been garbage collected: '{0}'", e)
Console.Read()
End Try
End Sub
Sub MakeSomeGarbage()
Dim vt As Version
Dim i As Integer
For i = 0 To maxGarbage - 1
' Create objects and release them to fill up memory
' with unused objects.
vt = New Version
Next i
End Sub
End Class
End Namespace
```
--------------------------------
### Instalar .NET Runtime 9.0
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-debian
Instala o runtime básico do .NET sem suporte a ASP.NET Core.
```bash
sudo apt-get install -y dotnet-runtime-9.0
```
--------------------------------
### List Installed Plugins
Source: https://learn.microsoft.com/pt-br/dotnet/azure/migration/appmod/copilot-cli-support
Verify the installation by listing all currently installed plugins.
```text
/plugin list
```
--------------------------------
### Configurar StartupUri para navegar até uma página
Source: https://learn.microsoft.com/pt-br/dotnet/desktop/wpf/app-development/application-management-overview
Uso do atributo StartupUri no XAML para navegar automaticamente para uma página em um XBAP.
```xml
```
--------------------------------
### Install the .NET package
Source: https://learn.microsoft.com/pt-br/dotnet/api/overview/azure/AI.Language.Text.Authoring-readme
Use the .NET CLI to add the required client library package to your project.
```bash
dotnet add package Azure.AI.Language.Text.Authoring --prerelease
```
--------------------------------
### Installer.Committing Event
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.configuration.install.installer.committing
The Committing event occurs before the installers in the Installers property commit their installations. It uses the InstallEventHandler delegate.
```APIDOC
## Installer.Committing Event
### Description
Occurs before the installers in the Installers property commit their installations.
### Signature
public event System.Configuration.Install.InstallEventHandler Committing;
### Event Type
InstallEventHandler
### Usage Example (C#)
```csharp
public MyInstallerClass() :base()
{
// Attach the 'Committing' event.
this.Committing += new InstallEventHandler(MyInstaller_Committing);
}
// Event handler for 'Committing' event.
private void MyInstaller_Committing(object sender, InstallEventArgs e)
{
Console.WriteLine("Committing Event occurred.");
}
```
```
--------------------------------
### dotnet tool install
Source: https://learn.microsoft.com/pt-br/dotnet/core/tools/dotnet-tool-install
Installs the specified .NET tool on the machine. Supports global, custom path, and local installation modes.
```APIDOC
## dotnet tool install
### Description
Installs the specified .NET tool on the machine. This command can be used to install tools globally, at a specific path, or locally within a project.
### Syntax
- `dotnet tool install -g|--global [options]`
- `dotnet tool install --tool-path [options]`
- `dotnet tool install [--local] [options]`
### Parameters
- **PACKAGE_NAME** (string) - Required - The name/ID of the NuGet package to install.
- **-g, --global** (flag) - Optional - Installs the tool in the user's global tools directory.
- **--tool-path** (path) - Optional - Specifies the location where the tool should be installed.
- **--local** (flag) - Optional - Installs the tool as a local tool in the current directory.
- **--version** (string) - Optional - The version of the tool package to install.
- **--framework** (string) - Optional - The target framework to install the tool for.
- **--source** (string) - Optional - Specifies a NuGet package source to use during installation.
- **--prerelease** (flag) - Optional - Allows the installation of prerelease packages.
```
--------------------------------
### Instalar o SDK do .NET
Source: https://learn.microsoft.com/pt-br/dotnet/core/install/linux-fedora
Comandos para instalar o SDK do .NET, que inclui as ferramentas necessárias para desenvolvimento.
```bash
sudo dnf install dotnet-sdk-10.0
```
```bash
sudo dnf install dotnet-sdk-9.0
```
```bash
sudo dnf install dotnet-sdk-8.0
```
--------------------------------
### Sample Configuration File
Source: https://learn.microsoft.com/pt-br/dotnet/api/overview/azure/Microsoft.Extensions.Azure-readme
Example JSON configuration structure for Azure client settings.
```json
{
"Logging": {
"LogLevel": {
"Default": "Debug"
}
},
"AllowedHosts": "*",
"Default": {
"ClientId": "",
"ClientSecret": "",
"TenantId": "",
"TelemetryPolicy": {
"ApplicationId": "AppId"
}
},
"KeyVault": {
"VaultUri": ""
},
"Storage": {
"serviceUri": "",
"credential": {
"accountName": "",
"accountKey": ""
}
}
}
```
--------------------------------
### Using in Visual Basic
Source: https://learn.microsoft.com/pt-br/dotnet/visual-basic/language-reference/xmldoc/example
An example of how to document a class member using the and tags within XML comments.
```VB
Public Class Employee
'''
''' This sample shows how to set the ID field.
'''
''' Dim alice As New Employee
''' alice.ID = 1234
'''
'''
'''
Public ID As Integer
End Class
```
--------------------------------
### dotnet tool install
Source: https://learn.microsoft.com/pt-br/dotnet/core/tools/dotnet-tool-install
Installs a specified .NET tool. This command supports global installation, custom tool paths, and version selection.
```APIDOC
## dotnet tool install
### Description
Installs a .NET tool on your machine. Tools can be installed as global tools or local tools depending on the flags provided.
### Parameters
- **--tool-path ** (string) - Optional - Specifies the location to install the Global Tool. If the path does not exist, the command attempts to create it.
- **-g|--global** (flag) - Optional - Installs the tool as a global tool.
- **-v|--verbosity ** (string) - Optional - Sets the verbosity level of the command. Allowed values: q[uiet], m[inimal], n[ormal], d[etailed], diag[nostic].
- **--version ** (string) - Optional - The version of the tool to install. Defaults to the latest stable version.
- **--allow-roll-forward** (flag) - Optional - Allows the tool to run on newer versions of .NET if the target runtime is unavailable.
### Usage Examples
- `dotnet tool install -g dotnetsay` (Install globally)
- `dotnet tool install dotnetsay --tool-path c:\global-tools` (Install to specific path)
- `dotnet tool install -g dotnetsay --version 2.0.0` (Install specific version)
- `dotnet tool install dotnetsay` (Install locally)
```
--------------------------------
### Publicar um aplicativo .pkg não assinado
Source: https://learn.microsoft.com/pt-br/dotnet/maui/mac-catalyst/deployment/publish-unsigned
Utilize este comando para gerar um pacote instalador .pkg. A configuração Release é o padrão no .NET 8 e pode ser omitida.
```bash
dotnet publish -f net8.0-maccatalyst -c Release
```
--------------------------------
### Adicionar diretivas using ao Startup.cs
Source: https://learn.microsoft.com/pt-br/dotnet/machine-learning/how-to-guides/serve-model-serverless-azure-functions-ml-net
Inclui os namespaces necessários para configurar a injeção de dependência e o serviço de ML.NET no Azure Functions.
```C#
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.ML;
using SentimentAnalysisFunctionsApp;
using SentimentAnalysisFunctionsApp.DataModels;
using System.IO;
using System;"
```
--------------------------------
### Example Output
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.xml.linq.extensions.ancestors
The output produced by the ancestor retrieval examples.
```text
Great Grand Children Elements
----
GreatGrandChild1
GreatGrandChild2
Ancestors
----
GrandChild1
Child1
Root
GrandChild2
Child2
```
--------------------------------
### Configurar StartupObject no arquivo de projeto
Source: https://learn.microsoft.com/pt-br/dotnet/csharp/language-reference/compiler-options/advanced
Define a classe que contém o método Main quando existem múltiplos pontos de entrada no projeto.
```xml
MyNamespace.Program
```
--------------------------------
### XmlConvert.ToString(Guid)
Source: https://learn.microsoft.com/pt-br/dotnet/api/system.xml.xmlconvert.tostring
Converts a Guid value to its string representation.
```APIDOC
## public static string ToString(Guid value)
### Description
Converts a Guid value to a string representation.
### Parameters
- **value** (Guid) - Required - The Guid value to convert.
### Returns
- **String** - A string representation of the Guid.
```
--------------------------------
### Translate group clause example
Source: https://learn.microsoft.com/pt-br/dotnet/csharp/language-reference/language-specification/expressions
Example of grouping names by country.
```csharp
from c in customers
group c.Name by c.Country
```
```csharp
(customers).GroupBy(c => c.Country, c => c.Name)
```
--------------------------------
### Install the Azure Monitor Live Metrics package
Source: https://learn.microsoft.com/pt-br/dotnet/api/overview/azure/Monitor.OpenTelemetry.LiveMetrics-readme
Use the .NET CLI to add the prerelease version of the Live Metrics client library to your project.
```bash
dotnet add package Azure.Monitor.OpenTelemetry.LiveMetrics --prerelease
```
--------------------------------
### Instalar SDK de pré-lançamento via comando tudo-em-um
Source: https://learn.microsoft.com/pt-br/dotnet/core/tools/test-prerelease-sdk-locally
Executa a instalação do SDK, atualização do .gitignore e criação do arquivo global.json em uma única operação.
```Bash
curl -sSL https://dot.net/v1/dotnet-install.sh -o /tmp/dotnet-install.sh \
&& bash /tmp/dotnet-install.sh --channel 11.0 --quality preview --install-dir .dotnet \
&& rm /tmp/dotnet-install.sh \
&& echo '.dotnet/' >> .gitignore \
&& cat > global.json << 'EOF'
{
"sdk": {
"paths": [".dotnet", "$host$"]
}
}
EOF
echo "Installed: $(.dotnet/dotnet --version)"
```
```PowerShell
Invoke-WebRequest 'https://dot.net/v1/dotnet-install.ps1' -OutFile "$env:TEMP\dotnet-install.ps1"
& "$env:TEMP\dotnet-install.ps1" -Channel 11.0 -Quality preview -InstallDir .dotnet
Remove-Item "$env:TEMP\dotnet-install.ps1"
Add-Content -Path .gitignore -Value '.dotnet/'
@'
{
"sdk": {
"paths": [".dotnet", "$host$"]
}
}
'@ | Set-Content -Path global.json
Write-Host "Installed: $(& .\.dotnet\dotnet.exe --version)"
```