Skip to content

Commit f7bc9cf

Browse files
authored
Merge pull request #844 from dotnet/master
Update live with current master
2 parents ce904d0 + ab9e534 commit f7bc9cf

File tree

9 files changed

+245
-18
lines changed

9 files changed

+245
-18
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// <SnippetAesGcm>
2+
using System;
3+
using System.Linq;
4+
using System.Security.Cryptography;
5+
6+
namespace whats_new
7+
{
8+
public static class Cipher
9+
{
10+
public static void Run()
11+
{
12+
// key should be: pre-known, derived, or transported via another channel, such as RSA encryption
13+
byte[] key = new byte[16];
14+
RandomNumberGenerator.Fill(key);
15+
16+
byte[] nonce = new byte[12];
17+
RandomNumberGenerator.Fill(nonce);
18+
19+
// normally this would be your data
20+
byte[] dataToEncrypt = new byte[1234];
21+
byte[] associatedData = new byte[333];
22+
RandomNumberGenerator.Fill(dataToEncrypt);
23+
RandomNumberGenerator.Fill(associatedData);
24+
25+
// these will be filled during the encryption
26+
byte[] tag = new byte[16];
27+
byte[] ciphertext = new byte[dataToEncrypt.Length];
28+
29+
using (AesGcm aesGcm = new AesGcm(key))
30+
{
31+
aesGcm.Encrypt(nonce, dataToEncrypt, ciphertext, tag, associatedData);
32+
}
33+
34+
// tag, nonce, ciphertext, associatedData should be sent to the other part
35+
36+
byte[] decryptedData = new byte[ciphertext.Length];
37+
38+
using (AesGcm aesGcm = new AesGcm(key))
39+
{
40+
aesGcm.Decrypt(nonce, ciphertext, tag, decryptedData, associatedData);
41+
}
42+
43+
// do something with the data
44+
// this should always print that data is the same
45+
Console.WriteLine($"AES-GCM: Decrypted data is {(dataToEncrypt.SequenceEqual(decryptedData) ? "the same as" : "different than")} original data.");
46+
}
47+
}
48+
}
49+
// </SnippetAesGcm>
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
using System;
2+
using System.IO;
3+
using System.Text.Json;
4+
using System.Threading.Tasks;
5+
6+
namespace whats_new
7+
{
8+
class Program
9+
{
10+
11+
static async Task Main(string[] args)
12+
{
13+
// <SnippetPrintJsonCall>
14+
// Calling code
15+
Console.WriteLine("Read with Utf8JsonReader");
16+
PrintJson(File.ReadAllBytes("launch.json").AsSpan());
17+
// </SnippetPrintJsonCall>
18+
19+
// <SnippetReadJsonCall>
20+
// Calling code
21+
Console.WriteLine("Read with JsonDocument");
22+
ReadJson(File.ReadAllText("launch.json"));
23+
// </SnippetReadJsonCall>
24+
25+
//await TLS.ConnectCloudFlare();
26+
27+
//Cipher.Run();
28+
29+
}
30+
31+
// <SnippetPrintJson>
32+
public static void PrintJson(ReadOnlySpan<byte> dataUtf8)
33+
{
34+
var json = new Utf8JsonReader(dataUtf8, isFinalBlock: true, state: default);
35+
36+
while (json.Read())
37+
{
38+
JsonTokenType tokenType = json.TokenType;
39+
ReadOnlySpan<byte> valueSpan = json.ValueSpan;
40+
switch (tokenType)
41+
{
42+
case JsonTokenType.StartObject:
43+
case JsonTokenType.EndObject:
44+
break;
45+
case JsonTokenType.StartArray:
46+
case JsonTokenType.EndArray:
47+
break;
48+
case JsonTokenType.PropertyName:
49+
break;
50+
case JsonTokenType.String:
51+
Console.WriteLine($"STRING: {json.GetString()}");
52+
break;
53+
case JsonTokenType.Number:
54+
if (!json.TryGetInt32(out int valueInteger))
55+
{
56+
throw new FormatException();
57+
}
58+
break;
59+
case JsonTokenType.True:
60+
case JsonTokenType.False:
61+
Console.WriteLine($"BOOL: {json.GetBoolean()}");
62+
break;
63+
case JsonTokenType.Null:
64+
break;
65+
default:
66+
throw new ArgumentException();
67+
}
68+
}
69+
70+
dataUtf8 = dataUtf8.Slice((int)json.BytesConsumed);
71+
JsonReaderState state = json.CurrentState;
72+
}
73+
// </SnippetPrintJson>
74+
75+
// <SnippetReadJson>
76+
public static void ReadJson(string jsonString)
77+
{
78+
using var document = JsonDocument.Parse(jsonString);
79+
80+
var root = document.RootElement;
81+
var version = root.GetProperty("version").GetString();
82+
var configurations = root.GetProperty("configurations");
83+
84+
Console.WriteLine($"Launch Version: {version}");
85+
86+
foreach (var config in configurations.EnumerateArray())
87+
{
88+
var name = config.GetProperty("name").GetString();
89+
Console.WriteLine($"Config: {name}");
90+
}
91+
}
92+
// </SnippetReadJson>
93+
}
94+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// <SnippetRsa>
2+
using System;
3+
using System.Security.Cryptography;
4+
5+
namespace whats_new
6+
{
7+
public static class RSATest
8+
{
9+
public static void Run(string keyFile)
10+
{
11+
using var rsa = RSA.Create();
12+
13+
byte[] keyBytes = System.IO.File.ReadAllBytes(keyFile);
14+
rsa.ImportRSAPrivateKey(keyBytes, out int bytesRead);
15+
16+
Console.WriteLine($"Read {bytesRead} bytes, {keyBytes.Length - bytesRead} extra byte(s) in file.");
17+
RSAParameters rsaParameters = rsa.ExportParameters(true);
18+
Console.WriteLine(BitConverter.ToString(rsaParameters.D));
19+
}
20+
}
21+
}
22+
// </SnippetRsa>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// <SnippetTLS>
2+
using System;
3+
using System.Net.Security;
4+
using System.Net.Sockets;
5+
using System.Threading.Tasks;
6+
7+
namespace whats_new
8+
{
9+
public static class TLS
10+
{
11+
public static async Task ConnectCloudFlare()
12+
{
13+
var targetHost = "www.cloudflare.com";
14+
15+
using TcpClient tcpClient = new TcpClient();
16+
17+
await tcpClient.ConnectAsync(targetHost, 443);
18+
19+
using SslStream sslStream = new SslStream(tcpClient.GetStream());
20+
21+
await sslStream.AuthenticateAsClientAsync(targetHost);
22+
await Console.Out.WriteLineAsync($"Connected to {targetHost} with {sslStream.SslProtocol}");
23+
}
24+
}
25+
}
26+
// </SnippetTLS>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"version": "0.2.0",
3+
"configurations": [
4+
{
5+
"name": ".NET Core Launch (console)",
6+
"type": "coreclr",
7+
"request": "launch",
8+
"preLaunchTask": "build",
9+
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/whats-new.dll",
10+
"args": [],
11+
"cwd": "${workspaceFolder}",
12+
"console": "internalConsole",
13+
"stopAtEntry": false,
14+
"internalConsoleOptions": "openOnSessionStart"
15+
},
16+
{
17+
"name": ".NET Core Attach",
18+
"type": "coreclr",
19+
"request": "attach",
20+
"processId": "${command:pickProcess}"
21+
}
22+
]
23+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>netcoreapp3.0</TargetFramework>
6+
<RootNamespace>whats_new</RootNamespace>
7+
<LangVersion>8.0</LangVersion>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<None Update="launch.json">
12+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
13+
</None>
14+
</ItemGroup>
15+
16+
</Project>

machine-learning/tutorials/SentimentAnalysis/Program.cs

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -119,20 +119,21 @@ public static void Evaluate(MLContext mlContext, ITransformer model, IDataView s
119119
// The Accuracy metric gets the accuracy of a model, which is the proportion
120120
// of correct predictions in the test set.
121121

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

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

129130
// <SnippetDisplayMetrics>
130131
Console.WriteLine();
131132
Console.WriteLine("Model quality metrics evaluation");
132133
Console.WriteLine("--------------------------------");
133-
Console.WriteLine($" Accuracy: {metrics.Accuracy:P2}");
134-
Console.WriteLine($"Area Under Roc Curve: {metrics.AreaUnderRocCurve:P2}");
135-
Console.WriteLine($" F1Score: {metrics.F1Score:P2}");
134+
Console.WriteLine($"Accuracy: {metrics.Accuracy:P2}");
135+
Console.WriteLine($"Auc: {metrics.AreaUnderRocCurve:P2}");
136+
Console.WriteLine($"F1Score: {metrics.F1Score:P2}");
136137
Console.WriteLine("=============== End of model evaluation ===============");
137138
//</SnippetDisplayMetrics>
138139

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

161162
Console.WriteLine();
162-
Console.WriteLine($"Sentiment: {sampleStatement.SentimentText} | Prediction: {(Convert.ToBoolean(resultprediction.Prediction) ? "Positive" : "Negative")} | Probability: {resultprediction.Probability} ");
163+
Console.WriteLine($"Sentiment: {resultprediction.SentimentText} | Prediction: {(Convert.ToBoolean(resultprediction.Prediction) ? "Positive" : "Negative")} | Probability: {resultprediction.Probability} ");
163164

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

202203
Console.WriteLine();
203-
204-
// Builds pairs of (sentiment, prediction)
205-
// <SnippetBuildSentimentPredictionPairs>
206-
IEnumerable<(SentimentData sentiment, SentimentPrediction prediction)> sentimentsAndPredictions = sentiments.Zip(predictedResults, (sentiment, prediction) => (sentiment, prediction));
207-
// </SnippetBuildSentimentPredictionPairs>
208-
204+
209205
// <SnippetDisplayResults>
210-
foreach ((SentimentData sentiment, SentimentPrediction prediction) item in sentimentsAndPredictions)
206+
foreach (SentimentPrediction prediction in predictedResults)
211207
{
212-
Console.WriteLine($"Sentiment: {item.sentiment.SentimentText} | Prediction: {(Convert.ToBoolean(item.prediction.Prediction) ? "Positive" : "Negative")} | Probability: {item.prediction.Probability} ");
208+
Console.WriteLine($"Sentiment: {prediction.SentimentText} | Prediction: {(Convert.ToBoolean(prediction.Prediction) ? "Positive" : "Negative")} | Probability: {prediction.Probability} ");
213209

214210
}
215211
Console.WriteLine("=============== End of predictions ===============");
216-
// </SnippetDisplayResults>
212+
// </SnippetDisplayResults>
217213
}
218214

219215
}

machine-learning/tutorials/SentimentAnalysis/SentimentData.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@ public class SentimentData
1414
public bool Sentiment;
1515
}
1616

17-
public class SentimentPrediction
17+
public class SentimentPrediction : SentimentData
1818
{
19+
1920
[ColumnName("PredictedLabel")]
2021
public bool Prediction { get; set; }
2122

snippets/csharp/new-in-7/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ static void Main(string[] args)
5454
Console.WriteLine(item);
5555
item = 24;
5656
Console.WriteLine(matrix[4, 2]);
57-
// <SnippetAssignRefReturn>
57+
// </SnippetAssignRefReturn>
5858

5959
Iterator.IteratorTest();
6060
Iterator.IteratorTestLocal();

0 commit comments

Comments
 (0)