Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions core/whats-new/whats-new-in-30/cs/Cipher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// <SnippetAesGcm>
using System;
using System.Linq;
using System.Security.Cryptography;

namespace whats_new
{
public static class Cipher
{
public static void Run()
{
// key should be: pre-known, derived, or transported via another channel, such as RSA encryption
byte[] key = new byte[16];
RandomNumberGenerator.Fill(key);

byte[] nonce = new byte[12];
RandomNumberGenerator.Fill(nonce);

// normally this would be your data
byte[] dataToEncrypt = new byte[1234];
byte[] associatedData = new byte[333];
RandomNumberGenerator.Fill(dataToEncrypt);
RandomNumberGenerator.Fill(associatedData);

// these will be filled during the encryption
byte[] tag = new byte[16];
byte[] ciphertext = new byte[dataToEncrypt.Length];

using (AesGcm aesGcm = new AesGcm(key))
{
aesGcm.Encrypt(nonce, dataToEncrypt, ciphertext, tag, associatedData);
}

// tag, nonce, ciphertext, associatedData should be sent to the other part

byte[] decryptedData = new byte[ciphertext.Length];

using (AesGcm aesGcm = new AesGcm(key))
{
aesGcm.Decrypt(nonce, ciphertext, tag, decryptedData, associatedData);
}

// do something with the data
// this should always print that data is the same
Console.WriteLine($"AES-GCM: Decrypted data is {(dataToEncrypt.SequenceEqual(decryptedData) ? "the same as" : "different than")} original data.");
}
}
}
// </SnippetAesGcm>
94 changes: 94 additions & 0 deletions core/whats-new/whats-new-in-30/cs/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

namespace whats_new
{
class Program
{

static async Task Main(string[] args)
{
// <SnippetPrintJsonCall>
// Calling code
Console.WriteLine("Read with Utf8JsonReader");
PrintJson(File.ReadAllBytes("launch.json").AsSpan());
// </SnippetPrintJsonCall>

// <SnippetReadJsonCall>
// Calling code
Console.WriteLine("Read with JsonDocument");
ReadJson(File.ReadAllText("launch.json"));
// </SnippetReadJsonCall>

//await TLS.ConnectCloudFlare();

//Cipher.Run();

}

// <SnippetPrintJson>
public static void PrintJson(ReadOnlySpan<byte> dataUtf8)
{
var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default);

while (json.Read())
{
JsonTokenType tokenType = json.TokenType;
ReadOnlySpan<byte> valueSpan = json.ValueSpan;
switch (tokenType)
{
case JsonTokenType.StartObject:
case JsonTokenType.EndObject:
break;
case JsonTokenType.StartArray:
case JsonTokenType.EndArray:
break;
case JsonTokenType.PropertyName:
break;
case JsonTokenType.String:
Console.WriteLine($"STRING: {json.GetString()}");
break;
case JsonTokenType.Number:
if (!json.TryGetInt32(out int valueInteger))
{
throw new FormatException();
}
break;
case JsonTokenType.True:
case JsonTokenType.False:
Console.WriteLine($"BOOL: {json.GetBoolean()}");
break;
case JsonTokenType.Null:
break;
default:
throw new ArgumentException();
}
}

dataUtf8 = dataUtf8.Slice((int)json.BytesConsumed);
JsonReaderState state = json.CurrentState;
}
// </SnippetPrintJson>

// <SnippetReadJson>
public static void ReadJson(string jsonString)
{
using var document = JsonDocument.Parse(jsonString);

var root = document.RootElement;
var version = root.GetProperty("version").GetString();
var configurations = root.GetProperty("configurations");

Console.WriteLine($"Launch Version: {version}");

foreach (var config in configurations.EnumerateArray())
{
var name = config.GetProperty("name").GetString();
Console.WriteLine($"Config: {name}");
}
}
// </SnippetReadJson>
}
}
22 changes: 22 additions & 0 deletions core/whats-new/whats-new-in-30/cs/RSA.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// <SnippetRsa>
using System;
using System.Security.Cryptography;

namespace whats_new
{
public static class RSATest
{
public static void Run(string keyFile)
{
using var rsa = RSA.Create();

byte[] keyBytes = System.IO.File.ReadAllBytes(keyFile);
rsa.ImportRSAPrivateKey(keyBytes, out int bytesRead);

Console.WriteLine($"Read {bytesRead} bytes, {keyBytes.Length - bytesRead} extra byte(s) in file.");
RSAParameters rsaParameters = rsa.ExportParameters(true);
Console.WriteLine(BitConverter.ToString(rsaParameters.D));
}
}
}
// </SnippetRsa>
26 changes: 26 additions & 0 deletions core/whats-new/whats-new-in-30/cs/TLS.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// <SnippetTLS>
using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace whats_new
{
public static class TLS
{
public static async Task ConnectCloudFlare()
{
var targetHost = "www.cloudflare.com";

using TcpClient tcpClient = new TcpClient();

await tcpClient.ConnectAsync(targetHost, 443);

using SslStream sslStream = new SslStream(tcpClient.GetStream());

await sslStream.AuthenticateAsClientAsync(targetHost);
await Console.Out.WriteLineAsync($"Connected to {targetHost} with {sslStream.SslProtocol}");
}
}
}
// </SnippetTLS>
23 changes: 23 additions & 0 deletions core/whats-new/whats-new-in-30/cs/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/whats-new.dll",
"args": [],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
16 changes: 16 additions & 0 deletions core/whats-new/whats-new-in-30/cs/whats-new.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<RootNamespace>whats_new</RootNamespace>
<LangVersion>8.0</LangVersion>
</PropertyGroup>

<ItemGroup>
<None Update="launch.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
28 changes: 12 additions & 16 deletions machine-learning/tutorials/SentimentAnalysis/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,20 +119,21 @@ public static void Evaluate(MLContext mlContext, ITransformer model, IDataView s
// The Accuracy metric gets the accuracy of a model, which is the proportion
// of correct predictions in the test set.

// The AreaUnderRocCurve metric is an indicator of how confident the model is
// correctly classifying the positive and negative classes as such.
// The AreaUnderROCCurve metric is equal to the probability that the algorithm ranks
// a randomly chosen positive instance higher than a randomly chosen negative one
// (assuming 'positive' ranks higher than 'negative').

// The F1Score metric gets the model's F1 score.
// F1 is a measure of tradeoff between precision and recall.
// The F1 score is the harmonic mean of precision and recall:
// 2 * precision * recall / (precision + recall).

// <SnippetDisplayMetrics>
Console.WriteLine();
Console.WriteLine("Model quality metrics evaluation");
Console.WriteLine("--------------------------------");
Console.WriteLine($" Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Area Under Roc Curve: {metrics.AreaUnderRocCurve:P2}");
Console.WriteLine($" F1Score: {metrics.F1Score:P2}");
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
Console.WriteLine($"Auc: {metrics.AreaUnderRocCurve:P2}");
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
Console.WriteLine("=============== End of model evaluation ===============");
//</SnippetDisplayMetrics>

Expand All @@ -159,7 +160,7 @@ private static void UseModelWithSingleItem(MLContext mlContext, ITransformer mod
Console.WriteLine("=============== Prediction Test of model with a single sample and test dataset ===============");

Console.WriteLine();
Console.WriteLine($"Sentiment: {sampleStatement.SentimentText} | Prediction: {(Convert.ToBoolean(resultprediction.Prediction) ? "Positive" : "Negative")} | Probability: {resultprediction.Probability} ");
Console.WriteLine($"Sentiment: {resultprediction.SentimentText} | Prediction: {(Convert.ToBoolean(resultprediction.Prediction) ? "Positive" : "Negative")} | Probability: {resultprediction.Probability} ");

Console.WriteLine("=============== End of Predictions ===============");
Console.WriteLine();
Expand Down Expand Up @@ -200,20 +201,15 @@ public static void UseModelWithBatchItems(MLContext mlContext, ITransformer mode
// </SnippetAddInfoMessage>

Console.WriteLine();

// Builds pairs of (sentiment, prediction)
// <SnippetBuildSentimentPredictionPairs>
IEnumerable<(SentimentData sentiment, SentimentPrediction prediction)> sentimentsAndPredictions = sentiments.Zip(predictedResults, (sentiment, prediction) => (sentiment, prediction));
// </SnippetBuildSentimentPredictionPairs>


// <SnippetDisplayResults>
foreach ((SentimentData sentiment, SentimentPrediction prediction) item in sentimentsAndPredictions)
foreach (SentimentPrediction prediction in predictedResults)
{
Console.WriteLine($"Sentiment: {item.sentiment.SentimentText} | Prediction: {(Convert.ToBoolean(item.prediction.Prediction) ? "Positive" : "Negative")} | Probability: {item.prediction.Probability} ");
Console.WriteLine($"Sentiment: {prediction.SentimentText} | Prediction: {(Convert.ToBoolean(prediction.Prediction) ? "Positive" : "Negative")} | Probability: {prediction.Probability} ");

}
Console.WriteLine("=============== End of predictions ===============");
// </SnippetDisplayResults>
// </SnippetDisplayResults>
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ public class SentimentData
public bool Sentiment;
}

public class SentimentPrediction
public class SentimentPrediction : SentimentData
{

[ColumnName("PredictedLabel")]
public bool Prediction { get; set; }

Expand Down
2 changes: 1 addition & 1 deletion snippets/csharp/new-in-7/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ static void Main(string[] args)
Console.WriteLine(item);
item = 24;
Console.WriteLine(matrix[4, 2]);
// <SnippetAssignRefReturn>
// </SnippetAssignRefReturn>

Iterator.IteratorTest();
Iterator.IteratorTestLocal();
Expand Down