content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TeamLab.Distributore.ConsoleApp.Models.SlotSelector;
namespace TeamLab.Distributore.ConsoleApp.Models.Interfaces
{
interface ISlotSelector
{
//Use case: 1 selezione prodotto
event Action<string, int> SlotSelected;
void InsertCode(string code);
void ProdottoErogato(string slotid);
}
}
| 21.136364 | 65 | 0.733333 | [
"MIT"
] | ncarandini/Distributore | TeamLab.Distributore.ConsoleApp/Models/Interfaces/ISlotSelector.cs | 467 | C# |
namespace ImageSharp.Tests.Drawing.Paths
{
using System;
using System.IO;
using ImageSharp;
using ImageSharp.Drawing.Brushes;
using Processing;
using System.Collections.Generic;
using Xunit;
using ImageSharp.Drawing;
using System.Numerics;
using SixLabors.Shapes;
using ImageSharp.Drawing.Processors;
using ImageSharp.Drawing.Pens;
using Moq;
using System.Collections.Immutable;
public class ShapePathTests
{
private readonly Mock<IPath> pathMock1;
private readonly Mock<IPath> pathMock2;
private readonly SixLabors.Shapes.Rectangle bounds1;
public ShapePathTests()
{
this.pathMock2 = new Mock<IPath>();
this.pathMock1 = new Mock<IPath>();
this.bounds1 = new SixLabors.Shapes.Rectangle(10.5f, 10, 10, 10);
pathMock1.Setup(x => x.Bounds).Returns(this.bounds1);
pathMock2.Setup(x => x.Bounds).Returns(this.bounds1);
// wire up the 2 mocks to reference eachother
pathMock1.Setup(x => x.AsClosedPath()).Returns(() => pathMock2.Object);
}
[Fact]
public void ShapePathFromPathConvertsBoundsDoesNotProxyToShape()
{
ShapePath region = new ShapePath(pathMock1.Object);
Assert.Equal(Math.Floor(bounds1.Left), region.Bounds.Left);
Assert.Equal(Math.Ceiling(bounds1.Right), region.Bounds.Right);
pathMock1.Verify(x => x.Bounds);
}
[Fact]
public void ShapePathFromPathMaxIntersectionsProxyToShape()
{
ShapePath region = new ShapePath(pathMock1.Object);
int i = region.MaxIntersections;
pathMock1.Verify(x => x.MaxIntersections);
}
[Fact]
public void ShapePathFromPathScanXProxyToShape()
{
int xToScan = 10;
ShapePath region = new ShapePath(pathMock1.Object);
pathMock1.Setup(x => x.FindIntersections(It.IsAny<Vector2>(), It.IsAny<Vector2>(), It.IsAny<Vector2[]>(), It.IsAny<int>(), It.IsAny<int>()))
.Callback<Vector2, Vector2, Vector2[], int, int>((s, e, b, c, o) => {
Assert.Equal(xToScan, s.X);
Assert.Equal(xToScan, e.X);
Assert.True(s.Y < bounds1.Top);
Assert.True(e.Y > bounds1.Bottom);
}).Returns(0);
int i = region.ScanX(xToScan, new float[0], 0, 0);
pathMock1.Verify(x => x.FindIntersections(It.IsAny<Vector2>(), It.IsAny<Vector2>(), It.IsAny<Vector2[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
}
[Fact]
public void ShapePathFromPathScanYProxyToShape()
{
int yToScan = 10;
ShapePath region = new ShapePath(pathMock1.Object);
pathMock1.Setup(x => x.FindIntersections(It.IsAny<Vector2>(), It.IsAny<Vector2>(), It.IsAny<Vector2[]>(), It.IsAny<int>(), It.IsAny<int>()))
.Callback<Vector2, Vector2, Vector2[], int, int>((s, e, b, c, o) => {
Assert.Equal(yToScan, s.Y);
Assert.Equal(yToScan, e.Y);
Assert.True(s.X < bounds1.Left);
Assert.True(e.X > bounds1.Right);
}).Returns(0);
int i = region.ScanY(yToScan, new float[0], 0, 0);
pathMock1.Verify(x => x.FindIntersections(It.IsAny<Vector2>(), It.IsAny<Vector2>(), It.IsAny<Vector2[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
}
[Fact]
public void ShapePathFromShapeScanXProxyToShape()
{
int xToScan = 10;
ShapePath region = new ShapePath(pathMock1.Object);
pathMock1.Setup(x => x.FindIntersections(It.IsAny<Vector2>(), It.IsAny<Vector2>(), It.IsAny<Vector2[]>(), It.IsAny<int>(), It.IsAny<int>()))
.Callback<Vector2, Vector2, Vector2[], int, int>((s, e, b, c, o) => {
Assert.Equal(xToScan, s.X);
Assert.Equal(xToScan, e.X);
Assert.True(s.Y < bounds1.Top);
Assert.True(e.Y > bounds1.Bottom);
}).Returns(0);
int i = region.ScanX(xToScan, new float[0], 0, 0);
pathMock1.Verify(x => x.FindIntersections(It.IsAny<Vector2>(), It.IsAny<Vector2>(), It.IsAny<Vector2[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
}
[Fact]
public void GetPointInfoCallSinglePathForPath()
{
ShapePath region = new ShapePath(pathMock1.Object);
ImageSharp.Drawing.PointInfo info = region.GetPointInfo(10, 1);
pathMock1.Verify(x => x.Distance(new Vector2(10, 1)), Times.Once);
pathMock2.Verify(x => x.Distance(new Vector2(10, 1)), Times.Never);
}
}
}
| 38.283465 | 166 | 0.569519 | [
"Apache-2.0"
] | ststeiger/ImageSharpTestApplication | tests/ImageSharp.Tests/Drawing/Paths/ShapePathTests.cs | 4,864 | C# |
using Commons.Domain;
using System;
namespace FileMicroservice.Domain
{
public class File : BaseEntity
{
public int id { get; set; }
public string filePath { get; set; }
}
}
| 17 | 44 | 0.627451 | [
"MIT"
] | sebamed/saup-microservices | FileMicroservice/Domain/File.cs | 206 | C# |
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using NDG.Helpers.Classes;
using NDG.DataAccessModels.Repositories;
namespace NDG.DataAccessModels.DataModels
{
public class ImageQuestionData : QuestionData
{
public static PhotoResolution CurrentResolution { get; set; }
public ImageQuestionData()
{
if (CurrentResolution == null)
{
using (var settingsRepository = new SettingsRepository())
{
CurrentResolution = settingsRepository.GetCurrentSettings().PhotoResolution;
}
}
}
private string _answerBase64;
public string AnswerBase64
{
get { return _answerBase64; }
set
{
_answerBase64 = value;
if (!string.IsNullOrEmpty(value))
{
Answer = new ImageStringBase64Converter().GetImageFromStringBase64(value);
}
else
Answer = null;
}
}
public override void SetResult(string answer)
{
AnswerBase64 = answer;
}
private BitmapImage _answer;
[XmlIgnore]
public BitmapImage Answer
{
get
{
return _answer;
}
set
{
_answer = value;
_answerBase64 = new ImageStringBase64Converter().GetStringBase64FromImage(value, CurrentResolution.Width, CurrentResolution.Height);
NotifyPropertyChanged("Answer");
}
}
public override string GetResult()
{
if (Answer != null)
{
return new ImageStringBase64Converter().GetStringBase64FromImage(Answer, CurrentResolution.Width, CurrentResolution.Height);
}
return string.Empty;
}
public bool Required { get; set; }
public override bool Validate()
{
if(Required)
return !IsEnabled || Answer != null && Required;
//return !IsEnabled || Answer != null;
return true;
}
public override string InvalidMessage
{
get
{
return "Please select an image!";
}
}
}
}
| 28.474747 | 149 | 0.520043 | [
"BSD-3-Clause"
] | nokiadatagathering/WP7-Official | NDG.DataAccessModels/DataModels/QuestionDataModels/ImageQuestionData.cs | 2,821 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using Azure.Base;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.ApplicationModel.Configuration
{
public class ConfigurationWatcher
{
readonly ConfigurationClient _client;
readonly List<string> _keysToWatch = new List<string>();
readonly Dictionary<string, ConfigurationSetting> _lastPolled = new Dictionary<string, ConfigurationSetting>();
Task _watching;
CancellationTokenSource _cancel;
object _sync = new object();
// TODO (pri 2): should we be using passed in client? the retry policy and logging is pretty bad for watching
public ConfigurationWatcher(ConfigurationClient client, params string[] keysToWatch)
{
if (client == null) throw new ArgumentNullException(nameof(client));
_keysToWatch.AddRange(keysToWatch);
_client = client;
}
public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(1);
public Task Task => _watching;
public void Start(CancellationToken token = default)
{
lock (_sync) {
if (_watching != null) throw new InvalidOperationException("watcher already started");
_cancel = (token == default) ? new CancellationTokenSource() : CancellationTokenSource.CreateLinkedTokenSource(token);
_watching = WatchChangesAsync(_cancel.Token);
}
}
public async Task Stop()
{
Task watching;
lock (_sync) {
if (_watching == null) throw new InvalidOperationException("watcher has not been started");
watching = _watching;
_cancel.Cancel();
_cancel = null;
_watching = null;
}
Debug.Assert(watching != null);
await watching.ConfigureAwait(false);
}
public event EventHandler<SettingChangedEventArgs> SettingChanged;
public event EventHandler<Exception> Error;
protected virtual bool HasChanged(ConfigurationSetting left, ConfigurationSetting right)
{
if (left == null && right != null) return true;
return !left.Equals(right);
}
private async Task WatchChangesAsync(CancellationToken cancellationToken)
{
// record current values
await Snapshot(cancellationToken).ConfigureAwait(false);
while (!cancellationToken.IsCancellationRequested) {
try {
await PollAsync(cancellationToken).ConfigureAwait(false);
await Task.Delay(Interval, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) {
if (e is OperationCanceledException) return;
Error?.Invoke(this, e);
}
}
}
private async Task Snapshot(CancellationToken cancellationToken)
{
try {
for (int i = 0; i < _keysToWatch.Count; i++) {
var response = await _client.GetAsync(_keysToWatch[i], null, default, cancellationToken).ConfigureAwait(false);
if (response.Status == 200) {
var setting = response.Result;
_lastPolled[setting.Key] = setting;
}
// TODO (pri 2): what should we do when the request fails?
}
}
catch (Exception e) {
if (e is OperationCanceledException) return;
Error?.Invoke(this, e);
}
}
private async Task PollAsync(CancellationToken cancellationToken)
{
var callback = SettingChanged;
if (callback == null) return;
var tasks = new Task<Response<ConfigurationSetting>>[_keysToWatch.Count];
for (int i = 0; i < _keysToWatch.Count; i++) {
tasks[i] = _client.GetAsync(_keysToWatch[i], null, default, cancellationToken);
}
await Task.WhenAll(tasks);
foreach(var task in tasks) {
var response = task.Result;
if (response.Status == 200) {
ConfigurationSetting current = response.Result;
_lastPolled.TryGetValue(current.Key, out var previous);
if (HasChanged(current, previous)) {
if (current == null) _lastPolled.Remove(current.Key);
else _lastPolled[current.Key] = current;
var e = new SettingChangedEventArgs(previous, current);
callback(this, e); // TODO (pri 2): should this be synchronized to the UI thread?
}
}
// TODO (pri 2): should we return for some error status codes?
}
}
public struct SettingChangedEventArgs
{
public SettingChangedEventArgs(ConfigurationSetting older, ConfigurationSetting newer)
{
Older = older;
Newer = newer;
}
public ConfigurationSetting Older { get; }
public ConfigurationSetting Newer { get; }
}
}
}
| 38.957746 | 134 | 0.572849 | [
"MIT"
] | jitendriyag2/azure-sdk-for-net | src/SDKs/Azure.ApplicationModel.Configuration/data-plane/Azure.ApplicationModel.Configuration/ConfigurationWatcher.cs | 5,534 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Http.Authentication;
namespace Microsoft.AspNetCore.Authentication.Tests.OpenIdConnect
{
/// <summary>
/// This formatter creates an easy to read string of the format: "'key1' 'value1' ..."
/// </summary>
public class AuthenticationPropertiesFormaterKeyValue : ISecureDataFormat<AuthenticationProperties>
{
string _protectedString = Guid.NewGuid().ToString();
public string Protect(AuthenticationProperties data)
{
if (data == null || data.Items.Count == 0)
{
return "null";
}
var encoder = UrlEncoder.Default;
var sb = new StringBuilder();
foreach(var item in data.Items)
{
sb.Append(encoder.Encode(item.Key) + " " + encoder.Encode(item.Value) + " ");
}
return sb.ToString();
}
public string Protect(AuthenticationProperties data, string purpose)
{
return Protect(data);
}
public AuthenticationProperties Unprotect(string protectedText)
{
if (string.IsNullOrEmpty(protectedText))
{
return null;
}
if (protectedText == "null")
{
return new AuthenticationProperties();
}
string[] items = protectedText.Split(' ');
if (items.Length % 2 != 0)
{
return null;
}
var propeties = new AuthenticationProperties();
for (int i = 0; i < items.Length - 1; i+=2)
{
propeties.Items.Add(items[i], items[i + 1]);
}
return propeties;
}
public AuthenticationProperties Unprotect(string protectedText, string purpose)
{
return Unprotect(protectedText);
}
}
}
| 30.041667 | 111 | 0.562182 | [
"Apache-2.0"
] | KroneckerX/Security | test/Microsoft.AspNetCore.Authentication.Test/OpenIdConnect/AuthenticationPropertiesFormaterKeyValue.cs | 2,163 | C# |
using DNA.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace DNA.CastleMinerZ.GraphicsProfileSupport
{
public class GraphicsProfileManager
{
private static GraphicsProfileManager _instance;
private GraphicsProfile _profile;
public static GraphicsProfileManager Instance
{
get
{
return _instance;
}
}
public GraphicsProfile Profile
{
get
{
return _profile;
}
}
public bool IsHiDef
{
get
{
return Profile == GraphicsProfile.HiDef;
}
}
public bool IsReach
{
get
{
return Profile == GraphicsProfile.Reach;
}
}
static GraphicsProfileManager()
{
_instance = new GraphicsProfileManager();
}
public void ExamineGraphicsDevices(object sender, PreparingDeviceSettingsEventArgs args)
{
bool forceReachProfile = CommandLineArgs.Get<CastleMinerZArgs>().ForceReachProfile;
GraphicsAdapter graphicsAdapter = args.GraphicsDeviceInformation.Adapter;
if (graphicsAdapter == null)
{
graphicsAdapter = GraphicsAdapter.DefaultAdapter;
}
if (graphicsAdapter != null)
{
if (!forceReachProfile && graphicsAdapter.IsProfileSupported(GraphicsProfile.HiDef))
{
_profile = GraphicsProfile.HiDef;
}
else
{
_profile = GraphicsProfile.Reach;
}
args.GraphicsDeviceInformation.Adapter = graphicsAdapter;
args.GraphicsDeviceInformation.GraphicsProfile = _profile;
return;
}
if (!forceReachProfile)
{
for (int i = 0; i < GraphicsAdapter.Adapters.Count; i++)
{
if (GraphicsAdapter.Adapters[i].IsProfileSupported(GraphicsProfile.HiDef))
{
args.GraphicsDeviceInformation.Adapter = GraphicsAdapter.Adapters[i];
args.GraphicsDeviceInformation.GraphicsProfile = GraphicsProfile.HiDef;
_profile = GraphicsProfile.HiDef;
return;
}
}
}
int num = 0;
while (true)
{
if (num < GraphicsAdapter.Adapters.Count)
{
if (GraphicsAdapter.Adapters[num].IsProfileSupported(GraphicsProfile.Reach))
{
break;
}
num++;
continue;
}
return;
}
args.GraphicsDeviceInformation.Adapter = GraphicsAdapter.Adapters[num];
args.GraphicsDeviceInformation.GraphicsProfile = GraphicsProfile.Reach;
_profile = GraphicsProfile.Reach;
}
}
}
| 21.990476 | 90 | 0.698571 | [
"MIT"
] | JettSettie/CastleMinerZsrc | DNA.CastleMinerZ.GraphicsProfileSupport/GraphicsProfileManager.cs | 2,309 | C# |
using System.Linq;
namespace Overmind.Solitaire.UnityClient
{
/// <summary>The stock is the pile with the leftover cards from the setup, from which the player can draw.</summary>
public class StockCardPile : CardPile
{
public WasteCardPile Waste;
public void OnMouseUp()
{
if (Cards.Any())
{
Draw();
}
else
{
ResetFromWaste();
}
}
private void Draw()
{
Waste.Push(Cards.Peek());
}
private void ResetFromWaste()
{
Card card = Waste.Peek();
while (card != null)
{
Push(card);
card = Waste.Peek();
}
}
protected override void DoPush(Card card)
{
base.DoPush(card);
card.Visible = false;
card.Collider.enabled = false;
}
}
}
| 15.255319 | 117 | 0.620642 | [
"MIT"
] | BenjaminHamon/Overmind.Solitaire | UnityClient/Assets/StockCardPile.cs | 719 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Analytics.Synapse.Artifacts.Models;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.Analytics.Synapse.Artifacts
{
internal partial class SparkJobDefinitionRestClient
{
private string endpoint;
private string apiVersion;
private ClientDiagnostics _clientDiagnostics;
private HttpPipeline _pipeline;
/// <summary> Initializes a new instance of SparkJobDefinitionRestClient. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> or <paramref name="apiVersion"/> is null. </exception>
public SparkJobDefinitionRestClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string endpoint, string apiVersion = "2019-06-01-preview")
{
if (endpoint == null)
{
throw new ArgumentNullException(nameof(endpoint));
}
if (apiVersion == null)
{
throw new ArgumentNullException(nameof(apiVersion));
}
this.endpoint = endpoint;
this.apiVersion = apiVersion;
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
}
internal HttpMessage CreateGetSparkJobDefinitionsByWorkspaceRequest()
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendPath("/sparkJobDefinitions", false);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
return message;
}
/// <summary> Lists spark job definitions. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public async Task<Response<SparkJobDefinitionsListResponse>> GetSparkJobDefinitionsByWorkspaceAsync(CancellationToken cancellationToken = default)
{
using var message = CreateGetSparkJobDefinitionsByWorkspaceRequest();
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionsListResponse value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SparkJobDefinitionsListResponse.DeserializeSparkJobDefinitionsListResponse(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists spark job definitions. </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
public Response<SparkJobDefinitionsListResponse> GetSparkJobDefinitionsByWorkspace(CancellationToken cancellationToken = default)
{
using var message = CreateGetSparkJobDefinitionsByWorkspaceRequest();
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionsListResponse value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SparkJobDefinitionsListResponse.DeserializeSparkJobDefinitionsListResponse(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateCreateOrUpdateSparkJobDefinitionRequest(string sparkJobDefinitionName, SparkJobDefinitionResource sparkJobDefinition, string ifMatch)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendPath("/sparkJobDefinitions/", false);
uri.AppendPath(sparkJobDefinitionName, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
if (ifMatch != null)
{
request.Headers.Add("If-Match", ifMatch);
}
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(sparkJobDefinition);
request.Content = content;
return message;
}
/// <summary> Creates or updates a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="sparkJobDefinition"> Spark Job Definition resource definition. </param>
/// <param name="ifMatch"> ETag of the Spark Job Definition entity. Should only be specified for update, for which it should match existing entity or can be * for unconditional update. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> or <paramref name="sparkJobDefinition"/> is null. </exception>
public async Task<Response<SparkJobDefinitionResource>> CreateOrUpdateSparkJobDefinitionAsync(string sparkJobDefinitionName, SparkJobDefinitionResource sparkJobDefinition, string ifMatch = null, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
if (sparkJobDefinition == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinition));
}
using var message = CreateCreateOrUpdateSparkJobDefinitionRequest(sparkJobDefinitionName, sparkJobDefinition, ifMatch);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionResource value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SparkJobDefinitionResource.DeserializeSparkJobDefinitionResource(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Creates or updates a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="sparkJobDefinition"> Spark Job Definition resource definition. </param>
/// <param name="ifMatch"> ETag of the Spark Job Definition entity. Should only be specified for update, for which it should match existing entity or can be * for unconditional update. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> or <paramref name="sparkJobDefinition"/> is null. </exception>
public Response<SparkJobDefinitionResource> CreateOrUpdateSparkJobDefinition(string sparkJobDefinitionName, SparkJobDefinitionResource sparkJobDefinition, string ifMatch = null, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
if (sparkJobDefinition == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinition));
}
using var message = CreateCreateOrUpdateSparkJobDefinitionRequest(sparkJobDefinitionName, sparkJobDefinition, ifMatch);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionResource value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SparkJobDefinitionResource.DeserializeSparkJobDefinitionResource(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetSparkJobDefinitionRequest(string sparkJobDefinitionName, string ifNoneMatch)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendPath("/sparkJobDefinitions/", false);
uri.AppendPath(sparkJobDefinitionName, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
if (ifNoneMatch != null)
{
request.Headers.Add("If-None-Match", ifNoneMatch);
}
return message;
}
/// <summary> Gets a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="ifNoneMatch"> ETag of the Spark Job Definition entity. Should only be specified for get. If the ETag matches the existing entity tag, or if * was provided, then no content will be returned. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public async Task<Response<SparkJobDefinitionResource>> GetSparkJobDefinitionAsync(string sparkJobDefinitionName, string ifNoneMatch = null, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var message = CreateGetSparkJobDefinitionRequest(sparkJobDefinitionName, ifNoneMatch);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionResource value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SparkJobDefinitionResource.DeserializeSparkJobDefinitionResource(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 304:
return Response.FromValue<SparkJobDefinitionResource>(null, message.Response);
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="ifNoneMatch"> ETag of the Spark Job Definition entity. Should only be specified for get. If the ETag matches the existing entity tag, or if * was provided, then no content will be returned. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public Response<SparkJobDefinitionResource> GetSparkJobDefinition(string sparkJobDefinitionName, string ifNoneMatch = null, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var message = CreateGetSparkJobDefinitionRequest(sparkJobDefinitionName, ifNoneMatch);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionResource value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SparkJobDefinitionResource.DeserializeSparkJobDefinitionResource(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 304:
return Response.FromValue<SparkJobDefinitionResource>(null, message.Response);
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateDeleteSparkJobDefinitionRequest(string sparkJobDefinitionName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Delete;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendPath("/sparkJobDefinitions/", false);
uri.AppendPath(sparkJobDefinitionName, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
return message;
}
/// <summary> Deletes a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public async Task<Response> DeleteSparkJobDefinitionAsync(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var message = CreateDeleteSparkJobDefinitionRequest(sparkJobDefinitionName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 204:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Deletes a Spark Job Definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public Response DeleteSparkJobDefinition(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var message = CreateDeleteSparkJobDefinitionRequest(sparkJobDefinitionName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 204:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateExecuteSparkJobDefinitionRequest(string sparkJobDefinitionName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendPath("/sparkJobDefinitions/", false);
uri.AppendPath(sparkJobDefinitionName, true);
uri.AppendPath("/execute", false);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
return message;
}
/// <summary> Executes the spark job definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public async Task<Response> ExecuteSparkJobDefinitionAsync(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var message = CreateExecuteSparkJobDefinitionRequest(sparkJobDefinitionName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Executes the spark job definition. </summary>
/// <param name="sparkJobDefinitionName"> The spark job definition name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionName"/> is null. </exception>
public Response ExecuteSparkJobDefinition(string sparkJobDefinitionName, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionName == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionName));
}
using var message = CreateExecuteSparkJobDefinitionRequest(sparkJobDefinitionName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateDebugSparkJobDefinitionRequest(SparkJobDefinitionResource sparkJobDefinitionAzureResource)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendPath("/debugSparkJobDefinition", false);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(sparkJobDefinitionAzureResource);
request.Content = content;
return message;
}
/// <summary> Debug the spark job definition. </summary>
/// <param name="sparkJobDefinitionAzureResource"> Spark Job Definition resource definition. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionAzureResource"/> is null. </exception>
public async Task<Response> DebugSparkJobDefinitionAsync(SparkJobDefinitionResource sparkJobDefinitionAzureResource, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionAzureResource == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionAzureResource));
}
using var message = CreateDebugSparkJobDefinitionRequest(sparkJobDefinitionAzureResource);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Debug the spark job definition. </summary>
/// <param name="sparkJobDefinitionAzureResource"> Spark Job Definition resource definition. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="sparkJobDefinitionAzureResource"/> is null. </exception>
public Response DebugSparkJobDefinition(SparkJobDefinitionResource sparkJobDefinitionAzureResource, CancellationToken cancellationToken = default)
{
if (sparkJobDefinitionAzureResource == null)
{
throw new ArgumentNullException(nameof(sparkJobDefinitionAzureResource));
}
using var message = CreateDebugSparkJobDefinitionRequest(sparkJobDefinitionAzureResource);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetSparkJobDefinitionsByWorkspaceNextPageRequest(string nextLink)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.AppendRaw(endpoint, false);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
return message;
}
/// <summary> Lists spark job definitions. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public async Task<Response<SparkJobDefinitionsListResponse>> GetSparkJobDefinitionsByWorkspaceNextPageAsync(string nextLink, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateGetSparkJobDefinitionsByWorkspaceNextPageRequest(nextLink);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionsListResponse value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SparkJobDefinitionsListResponse.DeserializeSparkJobDefinitionsListResponse(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Lists spark job definitions. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception>
public Response<SparkJobDefinitionsListResponse> GetSparkJobDefinitionsByWorkspaceNextPage(string nextLink, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
using var message = CreateGetSparkJobDefinitionsByWorkspaceNextPageRequest(nextLink);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
SparkJobDefinitionsListResponse value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SparkJobDefinitionsListResponse.DeserializeSparkJobDefinitionsListResponse(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 52.379576 | 249 | 0.633805 | [
"MIT"
] | AbelHu/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/SparkJobDefinitionRestClient.cs | 27,185 | C# |
using UnityEngine;
// Pistol weapon
public class Pistol : Weapon {
public new void Shoot(Camera playerCam)
{
base.Shoot(playerCam);
}
}
| 14.818182 | 43 | 0.625767 | [
"MIT"
] | AdrianKrige/GamesCapstoneProject | Neo Divitias/Assets/Scripts/Combat/Equipment/Weapons/Pistol.cs | 165 | C# |
// Copyright (c) SDV Code Project. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SdvCode.Areas.Administration.ViewModels.AddEmoji.InputModels
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using SdvCode.Areas.PrivateChat.Models.Enums;
public class AddEmojiInputModel
{
[Required]
[MaxLength(120)]
[Display(Name = "Emoji Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Emoji Image")]
public IFormFile Image { get; set; }
[Required]
public int Position { get; set; }
[Required]
[EnumDataType(typeof(EmojiType))]
[Display(Name = "Emoji Type")]
public EmojiType EmojiType { get; set; }
}
} | 29.484848 | 101 | 0.652621 | [
"MIT"
] | biproberkay/SdvCodeWebsite | SdvCode/SdvCode/Areas/Administration/ViewModels/AddEmoji/InputModels/AddEmojiInputModel.cs | 975 | C# |
namespace CrudeObservatory.Abstractions.Interfaces
{
public interface IDataValue
{
public string Name { get; set; }
public object Value { get; set; }
}
}
| 20.333333 | 51 | 0.639344 | [
"MPL-2.0"
] | jkoplo/CrudeObservatory | src/Libraries/CrudeObservatory.Abstractions/Interfaces/IDataValue.cs | 185 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 05:00:06 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static go.builtin;
using bytes = go.bytes_package;
using encoding = go.encoding_package;
using base64 = go.encoding.base64_package;
using fmt = go.fmt_package;
using math = go.math_package;
using reflect = go.reflect_package;
using sort = go.sort_package;
using strconv = go.strconv_package;
using strings = go.strings_package;
using sync = go.sync_package;
using unicode = go.unicode_package;
using utf8 = go.unicode.utf8_package;
using go;
#nullable enable
namespace go {
namespace encoding
{
public static partial class json_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
public partial struct InvalidUTF8Error
{
// Constructors
public InvalidUTF8Error(NilType _)
{
this.S = default;
}
public InvalidUTF8Error(@string S = default)
{
this.S = S;
}
// Enable comparisons between nil and InvalidUTF8Error struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(InvalidUTF8Error value, NilType nil) => value.Equals(default(InvalidUTF8Error));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(InvalidUTF8Error value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, InvalidUTF8Error value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, InvalidUTF8Error value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator InvalidUTF8Error(NilType nil) => default(InvalidUTF8Error);
}
[GeneratedCode("go2cs", "0.1.0.0")]
public static InvalidUTF8Error InvalidUTF8Error_cast(dynamic value)
{
return new InvalidUTF8Error(value.S);
}
}
}} | 34.189189 | 123 | 0.635573 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/encoding/json/encode_InvalidUTF8ErrorStruct.cs | 2,530 | C# |
namespace BashSoft.IO.Commands
{
using Attributes;
using Contracts;
using Exceptions;
[Alias("cdabs")]
public class ChangeAbsolutePathCommand : Command
{
[Inject]
private IDirectoryManager inputOutputManager;
public ChangeAbsolutePathCommand(string input, string[] data)
: base(input, data)
{
}
public IDirectoryManager InputOutputManager
{
get => this.inputOutputManager;
private set => this.inputOutputManager = value;
}
public override void Execute()
{
if (this.Data.Length != 2)
{
throw new InvalidCommandException(this.Input);
}
string absolutePath = this.Data[1];
this.InputOutputManager.ChangeCurrentDirectoryAbsolute(absolutePath);
}
}
}
| 23.810811 | 81 | 0.582293 | [
"MIT"
] | BorislavBarov/OOP-Advanced-With-C-Sharp | BashSoft Third Stage/StoryMode/BashSoft/IO/Commands/ChangeAbsolutePathCommand.cs | 883 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BeerViewer.Libraries;
using CefSharp;
using CefSharp.Handler;
namespace BeerViewer.Framework
{
internal class FrameworkRequestHandler : DefaultRequestHandler
{
public override IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
if (request.Url.Contains("/login/")) return new FrameworkWelcomeFilter();
return base.GetResourceResponseFilter(browserControl, browser, frame, request, response);
}
}
internal class FrameworkWelcomeFilter : FindReplaceResponseFilter
{
public override string findString => "<div id=\"translate_welcome_div\"></div>";
public override string replacementString => "<div id=\"translate_welcome_div\"></div><style>#welcome{display:none!important}</style>";
}
}
| 30.354839 | 157 | 0.78746 | [
"MIT"
] | WolfgangKurz/BeerViewer | BeerViewer/Framework/FrameworkRequestHandler.cs | 943 | C# |
#nullable enable
namespace FitsCs.Keys
{
public class KeyUpdater
{
public string? Name { get; set; }
public string? Comment { get; set; }
public object? Value { get; set; }
public KeyType Type { get; set; }
}
}
| 21.333333 | 44 | 0.574219 | [
"MIT"
] | Ilia-Kosenkov/Fits-Cs | Fits-Cs/Keys/KeyUpdater.cs | 258 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the clouddirectory-2017-01-11.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CloudDirectory.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CloudDirectory.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpgradeAppliedSchema Request Marshaller
/// </summary>
public class UpgradeAppliedSchemaRequestMarshaller : IMarshaller<IRequest, UpgradeAppliedSchemaRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((UpgradeAppliedSchemaRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpgradeAppliedSchemaRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CloudDirectory");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-01-11";
request.HttpMethod = "PUT";
request.ResourcePath = "/amazonclouddirectory/2017-01-11/schema/upgradeapplied";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetDirectoryArn())
{
context.Writer.WritePropertyName("DirectoryArn");
context.Writer.Write(publicRequest.DirectoryArn);
}
if(publicRequest.IsSetDryRun())
{
context.Writer.WritePropertyName("DryRun");
context.Writer.Write(publicRequest.DryRun);
}
if(publicRequest.IsSetPublishedSchemaArn())
{
context.Writer.WritePropertyName("PublishedSchemaArn");
context.Writer.Write(publicRequest.PublishedSchemaArn);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static UpgradeAppliedSchemaRequestMarshaller _instance = new UpgradeAppliedSchemaRequestMarshaller();
internal static UpgradeAppliedSchemaRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpgradeAppliedSchemaRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.123894 | 155 | 0.630083 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/Internal/MarshallTransformations/UpgradeAppliedSchemaRequestMarshaller.cs | 4,082 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SecurityHub.Model
{
/// <summary>
/// Contains details about an IAM group.
/// </summary>
public partial class AwsIamGroupDetails
{
private List<AwsIamAttachedManagedPolicy> _attachedManagedPolicies = new List<AwsIamAttachedManagedPolicy>();
private string _createDate;
private string _groupId;
private string _groupName;
private List<AwsIamGroupPolicy> _groupPolicyList = new List<AwsIamGroupPolicy>();
private string _path;
/// <summary>
/// Gets and sets the property AttachedManagedPolicies.
/// <para>
/// A list of the managed policies that are attached to the IAM group.
/// </para>
/// </summary>
public List<AwsIamAttachedManagedPolicy> AttachedManagedPolicies
{
get { return this._attachedManagedPolicies; }
set { this._attachedManagedPolicies = value; }
}
// Check to see if AttachedManagedPolicies property is set
internal bool IsSetAttachedManagedPolicies()
{
return this._attachedManagedPolicies != null && this._attachedManagedPolicies.Count > 0;
}
/// <summary>
/// Gets and sets the property CreateDate.
/// <para>
/// Indicates when the IAM group was created.
/// </para>
///
/// <para>
/// Uses the <code>date-time</code> format specified in <a href="https://tools.ietf.org/html/rfc3339#section-5.6">RFC
/// 3339 section 5.6, Internet Date/Time Format</a>. The value cannot contain spaces.
/// For example, <code>2020-03-22T13:22:13.933Z</code>.
/// </para>
/// </summary>
public string CreateDate
{
get { return this._createDate; }
set { this._createDate = value; }
}
// Check to see if CreateDate property is set
internal bool IsSetCreateDate()
{
return this._createDate != null;
}
/// <summary>
/// Gets and sets the property GroupId.
/// <para>
/// The identifier of the IAM group.
/// </para>
/// </summary>
public string GroupId
{
get { return this._groupId; }
set { this._groupId = value; }
}
// Check to see if GroupId property is set
internal bool IsSetGroupId()
{
return this._groupId != null;
}
/// <summary>
/// Gets and sets the property GroupName.
/// <para>
/// The name of the IAM group.
/// </para>
/// </summary>
public string GroupName
{
get { return this._groupName; }
set { this._groupName = value; }
}
// Check to see if GroupName property is set
internal bool IsSetGroupName()
{
return this._groupName != null;
}
/// <summary>
/// Gets and sets the property GroupPolicyList.
/// <para>
/// The list of inline policies that are embedded in the group.
/// </para>
/// </summary>
public List<AwsIamGroupPolicy> GroupPolicyList
{
get { return this._groupPolicyList; }
set { this._groupPolicyList = value; }
}
// Check to see if GroupPolicyList property is set
internal bool IsSetGroupPolicyList()
{
return this._groupPolicyList != null && this._groupPolicyList.Count > 0;
}
/// <summary>
/// Gets and sets the property Path.
/// <para>
/// The path to the group.
/// </para>
/// </summary>
public string Path
{
get { return this._path; }
set { this._path = value; }
}
// Check to see if Path property is set
internal bool IsSetPath()
{
return this._path != null;
}
}
} | 31.949367 | 126 | 0.560222 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SecurityHub/Generated/Model/AwsIamGroupDetails.cs | 5,048 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Json
{
using System;
using System.Collections.Generic;
using Microsoft.Azure.Cosmos.Query.Core;
/// <summary>
/// Partial class that wraps the private JsonTextNavigator
/// </summary>
#if INTERNAL
public
#else
internal
#endif
abstract partial class JsonNavigator : IJsonNavigator
{
/// <summary>
/// JsonNavigator that know how to navigate JSONs in text serialization.
/// Internally the navigator uses a <see cref="Parser"/> to from an AST of the JSON and the rest of the methods are just letting you traverse the materialized tree.
/// </summary>
private sealed class JsonTextNavigator : JsonNavigator
{
private readonly JsonTextNode rootNode;
/// <summary>
/// Initializes a new instance of the <see cref="JsonTextNavigator"/> class.
/// </summary>
/// <param name="buffer">The (UTF-8) buffer to navigate.</param>
/// <param name="skipValidation">whether to skip validation or not.</param>
public JsonTextNavigator(
ReadOnlyMemory<byte> buffer,
bool skipValidation = false)
{
IJsonReader jsonTextReader = JsonReader.Create(
buffer: buffer,
jsonStringDictionary: null,
skipValidation: skipValidation);
if (jsonTextReader.SerializationFormat != JsonSerializationFormat.Text)
{
throw new ArgumentException("jsonTextReader's serialization format must actually be text");
}
this.rootNode = Parser.Parse(jsonTextReader);
}
/// <inheritdoc />
public override JsonSerializationFormat SerializationFormat
{
get
{
return JsonSerializationFormat.Text;
}
}
/// <inheritdoc />
public override IJsonNavigatorNode GetRootNode()
{
return this.rootNode;
}
/// <inheritdoc />
public override JsonNodeType GetNodeType(IJsonNavigatorNode node)
{
if (node == null)
{
throw new ArgumentNullException("node");
}
JsonTextNode jsonTextNode = node as JsonTextNode;
if (jsonTextNode == null)
{
throw new ArgumentException("node must actually be a text node.");
}
return jsonTextNode.JsonNodeType;
}
/// <inheritdoc />
public override Number64 GetNumber64Value(IJsonNavigatorNode numberNavigatorNode)
{
if (numberNavigatorNode == null)
{
throw new ArgumentNullException("numberNavigatorNode");
}
NumberNode numberNode = numberNavigatorNode as NumberNode;
if (numberNode == null)
{
throw new ArgumentException("numberNavigatorNode must actually be a number node.");
}
return numberNode.Value;
}
/// <inheritdoc />
public override bool TryGetBufferedUtf8StringValue(
IJsonNavigatorNode navigatorNode,
out ReadOnlyMemory<byte> bufferedStringValue)
{
if (navigatorNode == null)
{
throw new ArgumentNullException(nameof(navigatorNode));
}
if (!(navigatorNode is StringNodeBase stringNode))
{
throw new ArgumentException($"{nameof(navigatorNode)} must actually be a number node.");
}
// For text we materialize the strings into UTF-16, so we can't get the buffered UTF-8 string.
bufferedStringValue = default;
return false;
}
/// <inheritdoc />
public override string GetStringValue(IJsonNavigatorNode stringNode)
{
if (stringNode == null)
{
throw new ArgumentNullException("stringNode");
}
StringNodeBase stringValueNode = stringNode as StringNodeBase;
if (stringValueNode == null)
{
throw new ArgumentException("stringNode must actually be a number node.");
}
return stringValueNode.Value;
}
/// <inheritdoc />
public override sbyte GetInt8Value(IJsonNavigatorNode numberNode)
{
if (numberNode == null)
{
throw new ArgumentNullException(nameof(numberNode));
}
if (!(numberNode is Int8Node int8Node))
{
throw new ArgumentException($"{nameof(numberNode)} must actually be a {nameof(Int8Node)} node.");
}
return int8Node.Value;
}
/// <inheritdoc />
public override short GetInt16Value(IJsonNavigatorNode numberNode)
{
if (numberNode == null)
{
throw new ArgumentNullException(nameof(numberNode));
}
if (!(numberNode is Int16Node int16Node))
{
throw new ArgumentException($"{nameof(numberNode)} must actually be a {nameof(Int16Node)} node.");
}
return int16Node.Value;
}
/// <inheritdoc />
public override int GetInt32Value(IJsonNavigatorNode numberNode)
{
if (numberNode == null)
{
throw new ArgumentNullException(nameof(numberNode));
}
if (!(numberNode is Int32Node int32Node))
{
throw new ArgumentException($"{nameof(numberNode)} must actually be a {nameof(Int32Node)} node.");
}
return int32Node.Value;
}
/// <inheritdoc />
public override long GetInt64Value(IJsonNavigatorNode numberNode)
{
if (numberNode == null)
{
throw new ArgumentNullException(nameof(numberNode));
}
if (!(numberNode is Int64Node int64Node))
{
throw new ArgumentException($"{nameof(numberNode)} must actually be a {nameof(Int64Node)} node.");
}
return int64Node.Value;
}
/// <inheritdoc />
public override float GetFloat32Value(IJsonNavigatorNode numberNode)
{
if (numberNode == null)
{
throw new ArgumentNullException(nameof(numberNode));
}
if (!(numberNode is Float32Node float32Node))
{
throw new ArgumentException($"{nameof(numberNode)} must actually be a {nameof(float32Node)} node.");
}
return float32Node.Value;
}
/// <inheritdoc />
public override double GetFloat64Value(IJsonNavigatorNode numberNode)
{
if (numberNode == null)
{
throw new ArgumentNullException(nameof(numberNode));
}
if (!(numberNode is Float64Node float64Node))
{
throw new ArgumentException($"{nameof(numberNode)} must actually be a {nameof(float64Node)} node.");
}
return float64Node.Value;
}
/// <inheritdoc />
public override uint GetUInt32Value(IJsonNavigatorNode numberNode)
{
if (numberNode == null)
{
throw new ArgumentNullException(nameof(numberNode));
}
if (!(numberNode is UInt32Node uInt32Node))
{
throw new ArgumentException($"{nameof(numberNode)} must actually be a {nameof(uInt32Node)} node.");
}
return uInt32Node.Value;
}
/// <inheritdoc />
public override Guid GetGuidValue(IJsonNavigatorNode node)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
if (!(node is GuidNode guidNode))
{
throw new ArgumentException($"{nameof(node)} must actually be a {nameof(GuidNode)} node.");
}
return guidNode.Value;
}
/// <inheritdoc />
public override ReadOnlyMemory<byte> GetBinaryValue(IJsonNavigatorNode node)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
if (!(node is BinaryNode binaryNode))
{
throw new ArgumentException($"{nameof(node)} must actually be a {nameof(BinaryNode)} node.");
}
return binaryNode.Value;
}
/// <inheritdoc />
public override bool TryGetBufferedBinaryValue(
IJsonNavigatorNode binaryNode,
out ReadOnlyMemory<byte> bufferedBinaryValue)
{
bufferedBinaryValue = default;
return false;
}
/// <inheritdoc />
public override int GetArrayItemCount(IJsonNavigatorNode arrayNavigatorNode)
{
if (arrayNavigatorNode == null)
{
throw new ArgumentNullException("arrayNavigatorNode");
}
ArrayNode arrayNode = arrayNavigatorNode as ArrayNode;
if (arrayNode == null)
{
throw new ArgumentException("arrayNavigatorNode must actually be an array node");
}
return arrayNode.Items.Count;
}
/// <inheritdoc />
public override IJsonNavigatorNode GetArrayItemAt(IJsonNavigatorNode arrayNavigatorNode, int index)
{
if (arrayNavigatorNode == null)
{
throw new ArgumentNullException("arrayNode");
}
ArrayNode arrayNode = arrayNavigatorNode as ArrayNode;
if (arrayNode == null)
{
throw new ArgumentException("arrayNavigatorNode must actually be an array node");
}
return arrayNode.Items[index];
}
/// <inheritdoc />
public override IEnumerable<IJsonNavigatorNode> GetArrayItems(IJsonNavigatorNode arrayNavigatorNode)
{
if (arrayNavigatorNode == null)
{
throw new ArgumentNullException("arrayNode");
}
ArrayNode arrayNode = arrayNavigatorNode as ArrayNode;
if (arrayNode == null)
{
throw new ArgumentException("arrayNavigatorNode must actually be an array node");
}
return arrayNode.Items;
}
/// <inheritdoc />
public override int GetObjectPropertyCount(IJsonNavigatorNode objectNavigatorNode)
{
if (objectNavigatorNode == null)
{
throw new ArgumentNullException("objectNode");
}
ObjectNode objectNode = objectNavigatorNode as ObjectNode;
if (objectNode == null)
{
throw new ArgumentException("objectNavigatorNode must actually be an array node");
}
return objectNode.Properties.Count;
}
/// <inheritdoc />
public override bool TryGetObjectProperty(IJsonNavigatorNode objectNavigatorNode, string propertyName, out ObjectProperty objectProperty)
{
if (objectNavigatorNode == null)
{
throw new ArgumentNullException("objectNavigatorNode");
}
if (propertyName == null)
{
throw new ArgumentNullException("propertyName");
}
if (!(objectNavigatorNode is ObjectNode objectNode))
{
throw new ArgumentException("objectNavigatorNode must actually be an array node");
}
IReadOnlyList<ObjectProperty> properties = ((ObjectNode)objectNode).Properties;
foreach (ObjectProperty property in properties)
{
if (this.GetStringValue(property.NameNode) == propertyName)
{
objectProperty = property;
return true;
}
}
objectProperty = default;
return false;
}
/// <inheritdoc />
public override IEnumerable<ObjectProperty> GetObjectProperties(IJsonNavigatorNode objectNavigatorNode)
{
if (objectNavigatorNode == null)
{
throw new ArgumentNullException("objectNode");
}
ObjectNode objectNode = objectNavigatorNode as ObjectNode;
if (objectNode == null)
{
throw new ArgumentException("objectNavigatorNode must actually be an array node");
}
return objectNode.Properties;
}
/// <inheritdoc />
public override bool TryGetBufferedRawJson(
IJsonNavigatorNode jsonNode,
out ReadOnlyMemory<byte> bufferedRawJson)
{
bufferedRawJson = default;
return false;
}
#region JsonTextParser
/// <summary>
/// The JsonTextParser class is used to get a JSON AST / DOM from plaintext using a JsonTextReader as a lexer / tokenizer.
/// Internally the parser is implemented as an LL(1) parser, since JSON is unambiguous and we can just parse it using recursive decent.
/// </summary>
private static class Parser
{
/// <summary>
/// Gets the root node of a JSON AST from a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>The root node of a JSON AST from a jsonTextReader.</returns>
public static JsonTextNode Parse(IJsonReader jsonTextReader)
{
if (jsonTextReader.SerializationFormat != JsonSerializationFormat.Text)
{
throw new ArgumentException("jsonTextReader's serialization format must actually be text");
}
// Read past the json object not started state.
jsonTextReader.Read();
JsonTextNode rootNode = Parser.ParseNode(jsonTextReader);
// Make sure that we are at the end of the file.
if (jsonTextReader.Read())
{
throw new ArgumentException("Did not fully parse json");
}
return rootNode;
}
/// <summary>
/// Parses out a JSON array AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON array AST node</returns>
private static ArrayNode ParseArrayNode(IJsonReader jsonTextReader)
{
List<JsonTextNode> items = new List<JsonTextNode>();
// consume the begin array token
jsonTextReader.Read();
while (jsonTextReader.CurrentTokenType != JsonTokenType.EndArray)
{
items.Add(Parser.ParseNode(jsonTextReader));
}
// consume the end array token
jsonTextReader.Read();
return ArrayNode.Create(items);
}
/// <summary>
/// Parses out a JSON object AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON object AST node</returns>
private static ObjectNode ParseObjectNode(IJsonReader jsonTextReader)
{
List<ObjectProperty> properties = new List<ObjectProperty>();
// consume the begin object token
jsonTextReader.Read();
while (jsonTextReader.CurrentTokenType != JsonTokenType.EndObject)
{
ObjectProperty property = Parser.ParsePropertyNode(jsonTextReader);
properties.Add(property);
}
// consume the end object token
jsonTextReader.Read();
return ObjectNode.Create(properties);
}
/// <summary>
/// Parses out a JSON string AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON string AST node</returns>
private static StringNode ParseStringNode(IJsonReader jsonTextReader)
{
if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory<byte> bufferedRawJsonToken))
{
throw new InvalidOperationException("Failed to get the buffered raw json token.");
}
StringNode stringNode = StringNode.Create(bufferedRawJsonToken);
// consume the string from the reader
jsonTextReader.Read();
return stringNode;
}
/// <summary>
/// Parses out a JSON number AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON number AST node</returns>
private static NumberNode ParseNumberNode(IJsonReader jsonTextReader)
{
if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory<byte> bufferedRawJsonToken))
{
throw new InvalidOperationException("Failed to get the buffered raw json token.");
}
NumberNode numberNode = NumberNode.Create(bufferedRawJsonToken);
// consume the number from the reader
jsonTextReader.Read();
return numberNode;
}
private static IntegerNode ParseIntegerNode(IJsonReader jsonTextReader, JsonTokenType jsonTokenType)
{
if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory<byte> bufferedRawJsonToken))
{
throw new InvalidOperationException("Failed to get the buffered raw json token.");
}
IntegerNode integerNode;
switch (jsonTokenType)
{
case JsonTokenType.Int8:
integerNode = Int8Node.Create(bufferedRawJsonToken);
break;
case JsonTokenType.Int16:
integerNode = Int16Node.Create(bufferedRawJsonToken);
break;
case JsonTokenType.Int32:
integerNode = Int32Node.Create(bufferedRawJsonToken);
break;
case JsonTokenType.Int64:
integerNode = Int64Node.Create(bufferedRawJsonToken);
break;
case JsonTokenType.UInt32:
integerNode = UInt32Node.Create(bufferedRawJsonToken);
break;
default:
throw new ArgumentException($"Unknown {nameof(JsonTokenType)}: {jsonTokenType}");
}
// consume the integer from the reader
jsonTextReader.Read();
return integerNode;
}
private static FloatNode ParseFloatNode(IJsonReader jsonTextReader, JsonTokenType jsonTokenType)
{
if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory<byte> bufferedRawJsonToken))
{
throw new InvalidOperationException("Failed to get the buffered raw json token.");
}
FloatNode floatNode;
switch (jsonTokenType)
{
case JsonTokenType.Float32:
floatNode = Float32Node.Create(bufferedRawJsonToken);
break;
case JsonTokenType.Float64:
floatNode = Float64Node.Create(bufferedRawJsonToken);
break;
default:
throw new ArgumentException($"Unknown {nameof(JsonTokenType)}: {jsonTokenType}");
}
// consume the float from the reader
jsonTextReader.Read();
return floatNode;
}
/// <summary>
/// Parses out a JSON true AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON true AST node</returns>
private static TrueNode ParseTrueNode(IJsonReader jsonTextReader)
{
// consume the true token from the reader
jsonTextReader.Read();
return TrueNode.Create();
}
/// <summary>
/// Parses out a JSON false AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON true AST node</returns>
private static FalseNode ParseFalseNode(IJsonReader jsonTextReader)
{
// consume the false token from the reader
jsonTextReader.Read();
return FalseNode.Create();
}
/// <summary>
/// Parses out a JSON null AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON null AST node</returns>
private static NullNode ParseNullNode(IJsonReader jsonTextReader)
{
// consume the null token from the reader
jsonTextReader.Read();
return NullNode.Create();
}
/// <summary>
/// Parses out a JSON property AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON property AST node</returns>
private static ObjectProperty ParsePropertyNode(IJsonReader jsonTextReader)
{
if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory<byte> bufferedRawJsonToken))
{
throw new InvalidOperationException("Failed to get the buffered raw json token.");
}
FieldNameNode fieldName = FieldNameNode.Create(bufferedRawJsonToken);
// Consume the fieldname from the jsonreader
jsonTextReader.Read();
JsonTextNode value = Parser.ParseNode(jsonTextReader);
return new ObjectProperty(fieldName, value);
}
private static GuidNode ParseGuidNode(IJsonReader jsonTextReader)
{
if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory<byte> bufferedRawJsonToken))
{
throw new InvalidOperationException("Failed to get the buffered raw json token.");
}
GuidNode node = GuidNode.Create(bufferedRawJsonToken);
// advance the reader forward.
jsonTextReader.Read();
return node;
}
private static BinaryNode ParseBinaryNode(IJsonReader jsonTextReader)
{
if (!jsonTextReader.TryGetBufferedRawJsonToken(out ReadOnlyMemory<byte> bufferedRawJsonToken))
{
throw new InvalidOperationException("Failed to get the buffered raw json token.");
}
BinaryNode node = BinaryNode.Create(bufferedRawJsonToken);
// advance the reader forward.
jsonTextReader.Read();
return node;
}
/// <summary>
/// Parses out a JSON AST node with a jsonTextReader.
/// </summary>
/// <param name="jsonTextReader">The reader to use as a lexer / tokenizer</param>
/// <returns>JSON AST node (type determined by the reader)</returns>
private static JsonTextNode ParseNode(IJsonReader jsonTextReader)
{
JsonTextNode node;
switch (jsonTextReader.CurrentTokenType)
{
case JsonTokenType.BeginArray:
node = Parser.ParseArrayNode(jsonTextReader);
break;
case JsonTokenType.BeginObject:
node = Parser.ParseObjectNode(jsonTextReader);
break;
case JsonTokenType.String:
node = Parser.ParseStringNode(jsonTextReader);
break;
case JsonTokenType.Number:
node = Parser.ParseNumberNode(jsonTextReader);
break;
case JsonTokenType.Float32:
case JsonTokenType.Float64:
node = Parser.ParseFloatNode(jsonTextReader, jsonTextReader.CurrentTokenType);
break;
case JsonTokenType.Int8:
case JsonTokenType.Int16:
case JsonTokenType.Int32:
case JsonTokenType.Int64:
case JsonTokenType.UInt32:
node = Parser.ParseIntegerNode(jsonTextReader, jsonTextReader.CurrentTokenType);
break;
case JsonTokenType.True:
node = Parser.ParseTrueNode(jsonTextReader);
break;
case JsonTokenType.False:
node = Parser.ParseFalseNode(jsonTextReader);
break;
case JsonTokenType.Null:
node = Parser.ParseNullNode(jsonTextReader);
break;
case JsonTokenType.Guid:
node = Parser.ParseGuidNode(jsonTextReader);
break;
case JsonTokenType.Binary:
node = Parser.ParseBinaryNode(jsonTextReader);
break;
default:
throw new JsonInvalidTokenException();
}
return node;
}
}
#endregion
#region Nodes
private sealed class ArrayNode : JsonTextNode
{
private static readonly ArrayNode Empty = new ArrayNode(new List<JsonTextNode>());
private readonly List<JsonTextNode> items;
private ArrayNode(List<JsonTextNode> items)
: base(JsonNodeType.Array)
{
this.items = items;
}
public IReadOnlyList<JsonTextNode> Items
{
get
{
return this.items;
}
}
public static ArrayNode Create(List<JsonTextNode> items)
{
if (items.Count == 0)
{
return ArrayNode.Empty;
}
return new ArrayNode(items);
}
}
private sealed class FalseNode : JsonTextNode
{
private static readonly FalseNode Instance = new FalseNode();
private FalseNode()
: base(JsonNodeType.False)
{
}
public static FalseNode Create()
{
return FalseNode.Instance;
}
}
private sealed class FieldNameNode : StringNodeBase
{
private static readonly FieldNameNode Empty = new FieldNameNode(string.Empty);
private FieldNameNode(ReadOnlyMemory<byte> bufferedToken)
: base(bufferedToken, false)
{
}
private FieldNameNode(string value)
: base(value, true)
{
}
public static FieldNameNode Create(ReadOnlyMemory<byte> bufferedToken)
{
if (bufferedToken.Length == 0)
{
return FieldNameNode.Empty;
}
// In the future we can have a flyweight dictionary for system strings.
return new FieldNameNode(bufferedToken);
}
}
private abstract class JsonTextNode : IJsonNavigatorNode
{
protected JsonTextNode(JsonNodeType jsonNodeType)
{
this.JsonNodeType = jsonNodeType;
}
public JsonNodeType JsonNodeType
{
get;
}
}
private sealed class NullNode : JsonTextNode
{
private static readonly NullNode Instance = new NullNode();
private NullNode()
: base(JsonNodeType.Null)
{
}
public static NullNode Create()
{
return NullNode.Instance;
}
}
private sealed class NumberNode : JsonTextNode
{
private static readonly NumberNode[] LiteralNumberNodes = new NumberNode[]
{
new NumberNode(0), new NumberNode(1), new NumberNode(2), new NumberNode(3),
new NumberNode(4), new NumberNode(5), new NumberNode(6), new NumberNode(7),
new NumberNode(8), new NumberNode(9), new NumberNode(10), new NumberNode(11),
new NumberNode(12), new NumberNode(13), new NumberNode(14), new NumberNode(15),
new NumberNode(16), new NumberNode(17), new NumberNode(18), new NumberNode(19),
new NumberNode(20), new NumberNode(21), new NumberNode(22), new NumberNode(23),
new NumberNode(24), new NumberNode(25), new NumberNode(26), new NumberNode(27),
new NumberNode(28), new NumberNode(29), new NumberNode(30), new NumberNode(31),
};
private readonly Lazy<Number64> value;
private NumberNode(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Number64)
{
this.value = new Lazy<Number64>(() => JsonTextParser.GetNumberValue(bufferedToken.Span));
}
private NumberNode(Number64 value)
: base(JsonNodeType.Number64)
{
this.value = new Lazy<Number64>(() => value);
}
public Number64 Value
{
get
{
return this.value.Value;
}
}
public static NumberNode Create(ReadOnlyMemory<byte> bufferedToken)
{
ReadOnlySpan<byte> payload = bufferedToken.Span;
if (
(payload.Length == 1) &&
(payload[0] >= '0') &&
(payload[0] <= '9'))
{
// Single digit number.
return NumberNode.LiteralNumberNodes[payload[0] - '0'];
}
if (
(payload.Length == 2) &&
(payload[0] >= '0') &&
(payload[0] <= '9') &&
(payload[1] >= '0') &&
(payload[1] <= '9'))
{
// Two digit number.
int index = ((payload[0] - '0') * 10) + (payload[1] - '0');
if (index >= 0 && index < NumberNode.LiteralNumberNodes.Length)
{
return NumberNode.LiteralNumberNodes[index];
}
}
return new NumberNode(bufferedToken);
}
}
private sealed class ObjectNode : JsonTextNode
{
private static readonly ObjectNode Empty = new ObjectNode(new List<ObjectProperty>());
private readonly List<ObjectProperty> properties;
private ObjectNode(List<ObjectProperty> properties)
: base(JsonNodeType.Object)
{
this.properties = properties;
}
public IReadOnlyList<ObjectProperty> Properties
{
get { return this.properties; }
}
public static ObjectNode Create(List<ObjectProperty> properties)
{
if (properties.Count == 0)
{
return ObjectNode.Empty;
}
return new ObjectNode(properties);
}
}
private sealed class StringNode : StringNodeBase
{
private static readonly StringNode Empty = new StringNode(string.Empty);
private StringNode(ReadOnlyMemory<byte> bufferedToken)
: base(bufferedToken, true)
{
}
private StringNode(string value)
: base(value, true)
{
}
public static StringNode Create(ReadOnlyMemory<byte> bufferedToken)
{
if (bufferedToken.Length == 0)
{
return StringNode.Empty;
}
// In the future we can have a flyweight dictionary for system strings.
return new StringNode(bufferedToken);
}
}
private abstract class StringNodeBase : JsonTextNode
{
private readonly Lazy<string> value;
protected StringNodeBase(
ReadOnlyMemory<byte> bufferedToken,
bool isStringNode)
: base(isStringNode ? JsonNodeType.String : JsonNodeType.FieldName)
{
this.value = new Lazy<string>(() => JsonTextParser.GetStringValue(bufferedToken.Span));
}
protected StringNodeBase(string value, bool isStringNode)
: base(isStringNode ? JsonNodeType.String : JsonNodeType.FieldName)
{
this.value = new Lazy<string>(() => value);
}
public string Value
{
get { return this.value.Value; }
}
}
private sealed class TrueNode : JsonTextNode
{
private static readonly TrueNode Instance = new TrueNode();
private TrueNode()
: base(JsonNodeType.True)
{
}
public static TrueNode Create()
{
return TrueNode.Instance;
}
}
private abstract class IntegerNode : JsonTextNode
{
protected IntegerNode(JsonNodeType jsonNodeType)
: base(jsonNodeType)
{
}
}
private sealed class Int8Node : IntegerNode
{
private readonly Lazy<sbyte> lazyValue;
private Int8Node(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Int8)
{
this.lazyValue = new Lazy<sbyte>(() =>
{
sbyte value = JsonTextParser.GetInt8Value(bufferedToken.Span);
return value;
});
}
public sbyte Value
{
get
{
return this.lazyValue.Value;
}
}
public static Int8Node Create(ReadOnlyMemory<byte> bufferedToken)
{
return new Int8Node(bufferedToken);
}
}
private sealed class Int16Node : IntegerNode
{
private readonly Lazy<short> lazyValue;
private Int16Node(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Int16)
{
this.lazyValue = new Lazy<short>(() =>
{
short value = JsonTextParser.GetInt16Value(bufferedToken.Span);
return value;
});
}
public short Value
{
get
{
return this.lazyValue.Value;
}
}
public static Int16Node Create(ReadOnlyMemory<byte> bufferedToken)
{
return new Int16Node(bufferedToken);
}
}
private sealed class Int32Node : IntegerNode
{
private readonly Lazy<int> lazyValue;
private Int32Node(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Int32)
{
this.lazyValue = new Lazy<int>(() =>
{
int value = JsonTextParser.GetInt32Value(bufferedToken.Span);
return value;
});
}
public int Value
{
get
{
return this.lazyValue.Value;
}
}
public static Int32Node Create(ReadOnlyMemory<byte> bufferedToken)
{
return new Int32Node(bufferedToken);
}
}
private sealed class Int64Node : IntegerNode
{
private readonly Lazy<long> lazyValue;
private Int64Node(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Int64)
{
this.lazyValue = new Lazy<long>(() =>
{
long value = JsonTextParser.GetInt64Value(bufferedToken.Span);
return value;
});
}
public long Value
{
get
{
return this.lazyValue.Value;
}
}
public static Int64Node Create(ReadOnlyMemory<byte> bufferedToken)
{
return new Int64Node(bufferedToken);
}
}
private sealed class UInt32Node : IntegerNode
{
private readonly Lazy<uint> lazyValue;
private UInt32Node(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.UInt32)
{
this.lazyValue = new Lazy<uint>(() =>
{
uint value = JsonTextParser.GetUInt32Value(bufferedToken.Span);
return value;
});
}
public uint Value
{
get
{
return this.lazyValue.Value;
}
}
public static UInt32Node Create(ReadOnlyMemory<byte> bufferedToken)
{
return new UInt32Node(bufferedToken);
}
}
private abstract class FloatNode : JsonTextNode
{
protected FloatNode(JsonNodeType jsonNodeType)
: base(jsonNodeType)
{
}
}
private sealed class Float32Node : FloatNode
{
private readonly Lazy<float> lazyValue;
private Float32Node(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Float32)
{
this.lazyValue = new Lazy<float>(() =>
{
float value = JsonTextParser.GetFloat32Value(bufferedToken.Span);
return value;
});
}
public float Value
{
get
{
return this.lazyValue.Value;
}
}
public static Float32Node Create(ReadOnlyMemory<byte> bufferedToken)
{
return new Float32Node(bufferedToken);
}
}
private sealed class Float64Node : FloatNode
{
private readonly Lazy<double> lazyValue;
private Float64Node(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Float64)
{
this.lazyValue = new Lazy<double>(() =>
{
double value = JsonTextParser.GetFloat64Value(bufferedToken.Span);
return value;
});
}
public double Value
{
get
{
return this.lazyValue.Value;
}
}
public static Float64Node Create(ReadOnlyMemory<byte> bufferedToken)
{
return new Float64Node(bufferedToken);
}
}
private sealed class GuidNode : JsonTextNode
{
private readonly Lazy<Guid> lazyValue;
private GuidNode(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Guid)
{
this.lazyValue = new Lazy<Guid>(() =>
{
Guid value = JsonTextParser.GetGuidValue(bufferedToken.Span);
return value;
});
}
public Guid Value
{
get
{
return this.lazyValue.Value;
}
}
public static GuidNode Create(ReadOnlyMemory<byte> value)
{
return new GuidNode(value);
}
}
private sealed class BinaryNode : JsonTextNode
{
private readonly Lazy<ReadOnlyMemory<byte>> lazyValue;
private BinaryNode(ReadOnlyMemory<byte> bufferedToken)
: base(JsonNodeType.Binary)
{
this.lazyValue = new Lazy<ReadOnlyMemory<byte>>(() =>
{
return JsonTextParser.GetBinaryValue(bufferedToken.Span);
});
}
public ReadOnlyMemory<byte> Value
{
get
{
return this.lazyValue.Value;
}
}
public static BinaryNode Create(ReadOnlyMemory<byte> value)
{
return new BinaryNode(value);
}
}
#endregion
}
}
}
| 36.918033 | 172 | 0.468853 | [
"MIT"
] | lingdaLi/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/Json/JsonNavigator.JsonTextNavigator.cs | 47,294 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DRI.BasicDI.UnitTests.TestClasses
{
internal class TestClassA
{
public TestClassA(TestClassB testClassB, TestClassC testClassC)
{
}
}
} | 21.076923 | 71 | 0.631387 | [
"MIT"
] | ranasabih/BasicDI | DRI.BasicDI.UnitTests/TestClasses/TestClassA.cs | 276 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KeyValueStorage.Memory;
using NUnit.Framework;
namespace KeyValueStorage.Testing.Memory
{
[TestFixture]
class SimpleMemoryStoreProviderRelationalTests
{
[SetUp]
public void SetUp()
{
KVStore.Initialize(new Func<Interfaces.IStoreProvider>(() => new SimpleMemoryStoreProvider()));
}
[Test]
public void ShouldAddToSingleRelationship()
{
RelationalReusableTests.ShouldHandleSingleRelationship();
}
[Test]
public void ShouldBuildRelatedObjectFromFetchedKey()
{
RelationalReusableTests.ShouldBuildRelatedObjectFromFetchedKey();
}
[Test]
public void ShouldHandleMultipleRelationshipsIndependently()
{
RelationalReusableTests.ShouldHandleMultipleRelationshipsIndependently();
}
}
}
| 25.342105 | 107 | 0.666667 | [
"Apache-2.0"
] | Metal10k/KeyValueStorage | KeyValueStorage.Testing/Memory/SimpleMemoryStoreProviderRelationalTests.cs | 965 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using HoloToolkit.Unity;
using HoloToolkit.Unity.Buttons;
using System.Collections.Generic;
using UnityEngine;
namespace HoloToolkit.MRDL.PeriodicTable
{
public class ElementButton : Button
{
public override void OnStateChange(ButtonStateEnum newState)
{
Element element = gameObject.GetComponent<Element>();
switch (newState)
{
case ButtonStateEnum.ObservationTargeted:
case ButtonStateEnum.Targeted:
// If we're not the active element, light up
if (Element.ActiveElement != this)
{
element.Highlight();
}
break;
case ButtonStateEnum.Pressed:
// User has clicked us
// If we're the active element button, reset ourselves
if (Element.ActiveElement == element)
{
// If we're the current element, reset ourselves
Element.ActiveElement = null;
}
else
{
Element.ActiveElement = element;
element.Open();
}
break;
default:
element.Dim();
break;
}
base.OnStateChange(newState);
}
}
}
| 31.962264 | 92 | 0.474616 | [
"MIT"
] | cre8ivepark/MRDesignLabs_Unity_PeriodicTable | Assets/MRDL_PeriodicTable/Scripts/ElementButton.cs | 1,696 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutoMapper;
using DirScan.Data;
using DirScan.ErrorLogging;
using DirScan.Logging;
namespace DirScan.Service
{
public abstract class DirectoryServiceBase
{
protected readonly IErrorLogger _errorLogger;
protected readonly ILogger _logger;
protected readonly IMapper _mapper;
protected DirectoryServiceBase( IErrorLogger errorLogger, ILogger logger, IMapper mapper )
{
_errorLogger = errorLogger;
_logger = logger;
_mapper = mapper;
}
public abstract DirectoryData Scan(string path, bool logDirectories = false);
protected IEnumerable<FileType> GetFileTypes( List<FileInfo> files )
{
var fileTypes = new List<FileType>();
foreach (var fi in files)
{
if (fi.Attributes != FileAttributes.Directory)
{
var fileType = new FileType { Extension = "None", Length = fi.Length };
if (fi.Extension.Length > 0)
fileType = new FileType
{
Extension = fi.Extension.ToLower().Trim(),
Length = fi.Length
};
var ft = fileTypes.FirstOrDefault( f => f.Extension.ToLower() == fileType.Extension.ToLower() );
if (ft != null)
ft.Length += fileType.Length;
else
fileTypes.Add( fileType );
}
}
return fileTypes;
}
}
} | 32.423077 | 116 | 0.533215 | [
"MIT"
] | KentGabrys/DirScan | DirScan.Service/DirectoryServiceBase.cs | 1,688 | C# |
//
// IconNames.cs
//
// Author: endofunk
//
// Copyright (c) 2019
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Globalization;
using Endofunk.FX;
using static Endofunk.FX.Prelude;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using JP = Newtonsoft.Json.JsonPropertyAttribute;
namespace WeatherFX.Model {
public static class IconNames {
public static Result<Root> Get() => Try(() => {
var json = File.ReadAllText(Config.IconNames.filepath);
return JsonConvert.DeserializeObject<Root>(json);
});
public static Root FromJson(string json) => JsonConvert.DeserializeObject<Root>(json, Converter.Settings);
private static Func<string, Result<Root>> Create => json => FromJson(json).ToResult();
public class Root {
[JP("IconNames")] public readonly Icon[] Names;
public Root(Icon[] names) => Names = names;
public override string ToString() => $"Root: [IconNames: [{Names.Map(x => x.ToString()).Join(", ")}]]";
}
public class Icon {
[JP("Id")] public readonly string Id;
[JP("Image")] public readonly string Image;
[JP("Index")] public readonly long Index;
public Icon(string id, string image, long index) => (Id, Image, Index) = (id, image, index);
public object IconName { get; internal set; }
public override string ToString() => $"Icon: [Id: {Id}, Image: {Image}, Index: {Index}]";
}
internal static class Converter {
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings {
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
}
| 41.521739 | 110 | 0.707504 | [
"MIT"
] | endofunk/WeatherFX | Model/IconNames.cs | 2,867 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests
{
public class Http1ConnectionTests : IDisposable
{
private readonly IDuplexPipe _transport;
private readonly IDuplexPipe _application;
private readonly TestHttp1Connection _http1Connection;
private readonly ServiceContext _serviceContext;
private readonly HttpConnectionContext _http1ConnectionContext;
private readonly MemoryPool<byte> _pipelineFactory;
private SequencePosition _consumed;
private SequencePosition _examined;
private Mock<ITimeoutControl> _timeoutControl;
public Http1ConnectionTests()
{
_pipelineFactory = KestrelMemoryPool.Create();
var options = new PipeOptions(_pipelineFactory, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false);
var pair = DuplexPipe.CreateConnectionPair(options, options);
_transport = pair.Transport;
_application = pair.Application;
var connectionFeatures = new FeatureCollection();
connectionFeatures.Set(Mock.Of<IConnectionLifetimeFeature>());
_serviceContext = new TestServiceContext()
{
Scheduler = PipeScheduler.Inline
};
_timeoutControl = new Mock<ITimeoutControl>();
_http1ConnectionContext = new HttpConnectionContext
{
ServiceContext = _serviceContext,
ConnectionContext = Mock.Of<ConnectionContext>(),
ConnectionFeatures = connectionFeatures,
MemoryPool = _pipelineFactory,
TimeoutControl = _timeoutControl.Object,
Transport = pair.Transport
};
_http1Connection = new TestHttp1Connection(_http1ConnectionContext);
_http1Connection.Reset();
}
public void Dispose()
{
_transport.Input.Complete();
_transport.Output.Complete();
_application.Input.Complete();
_application.Output.Complete();
_pipelineFactory.Dispose();
}
[Fact]
public async Task TakeMessageHeadersSucceedsWhenHeaderValueContainsUTF8()
{
var headerName = "Header";
var headerValueBytes = new byte[] { 0x46, 0x72, 0x61, 0x6e, 0xc3, 0xa7, 0x6f, 0x69, 0x73 };
var headerValue = Encoding.UTF8.GetString(headerValueBytes);
_http1Connection.Reset();
await _application.Output.WriteAsync(Encoding.UTF8.GetBytes($"{headerName}: "));
await _application.Output.WriteAsync(headerValueBytes);
await _application.Output.WriteAsync(Encoding.UTF8.GetBytes("\r\n\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
_http1Connection.TakeMessageHeaders(readableBuffer, trailers: false, out _consumed, out _examined);
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(headerValue, _http1Connection.RequestHeaders[headerName]);
}
[Fact]
public async Task TakeMessageHeadersThrowsWhenHeaderValueContainsExtendedASCII()
{
var extendedAsciiEncoding = Encoding.GetEncoding("ISO-8859-1");
var headerName = "Header";
var headerValueBytes = new byte[] { 0x46, 0x72, 0x61, 0x6e, 0xe7, 0x6f, 0x69, 0x73 };
_http1Connection.Reset();
await _application.Output.WriteAsync(extendedAsciiEncoding.GetBytes($"{headerName}: "));
await _application.Output.WriteAsync(headerValueBytes);
await _application.Output.WriteAsync(extendedAsciiEncoding.GetBytes("\r\n\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<InvalidOperationException>(() => _http1Connection.TakeMessageHeaders(readableBuffer, trailers: false, out _consumed, out _examined));
}
[Fact]
public async Task TakeMessageHeadersThrowsWhenHeadersExceedTotalSizeLimit()
{
const string headerLine = "Header: value\r\n";
_serviceContext.ServerOptions.Limits.MaxRequestHeadersTotalSize = headerLine.Length - 1;
_http1Connection.Reset();
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"{headerLine}\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() => _http1Connection.TakeMessageHeaders(readableBuffer, trailers: false, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.BadRequest_HeadersExceedMaxTotalSize, exception.Message);
Assert.Equal(StatusCodes.Status431RequestHeaderFieldsTooLarge, exception.StatusCode);
}
[Fact]
public async Task TakeMessageHeadersThrowsWhenHeadersExceedCountLimit()
{
const string headerLines = "Header-1: value1\r\nHeader-2: value2\r\n";
_serviceContext.ServerOptions.Limits.MaxRequestHeaderCount = 1;
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"{headerLines}\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() => _http1Connection.TakeMessageHeaders(readableBuffer, trailers: false, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.BadRequest_TooManyHeaders, exception.Message);
Assert.Equal(StatusCodes.Status431RequestHeaderFieldsTooLarge, exception.StatusCode);
}
[Fact]
public void ResetResetsScheme()
{
_http1Connection.Scheme = "https";
// Act
_http1Connection.Reset();
// Assert
Assert.Equal("http", ((IFeatureCollection)_http1Connection).Get<IHttpRequestFeature>().Scheme);
}
[Fact]
public void ResetResetsTraceIdentifier()
{
_http1Connection.TraceIdentifier = "xyz";
_http1Connection.Reset();
var nextId = ((IFeatureCollection)_http1Connection).Get<IHttpRequestIdentifierFeature>().TraceIdentifier;
Assert.NotEqual("xyz", nextId);
_http1Connection.Reset();
var secondId = ((IFeatureCollection)_http1Connection).Get<IHttpRequestIdentifierFeature>().TraceIdentifier;
Assert.NotEqual(nextId, secondId);
}
[Fact]
public void ResetResetsMinRequestBodyDataRate()
{
_http1Connection.MinRequestBodyDataRate = new MinDataRate(bytesPerSecond: 1, gracePeriod: TimeSpan.MaxValue);
_http1Connection.Reset();
Assert.Same(_serviceContext.ServerOptions.Limits.MinRequestBodyDataRate, _http1Connection.MinRequestBodyDataRate);
}
[Fact]
public void ResetResetsMinResponseDataRate()
{
_http1Connection.MinResponseDataRate = new MinDataRate(bytesPerSecond: 1, gracePeriod: TimeSpan.MaxValue);
_http1Connection.Reset();
Assert.Same(_serviceContext.ServerOptions.Limits.MinResponseDataRate, _http1Connection.MinResponseDataRate);
}
[Fact]
public void TraceIdentifierCountsRequestsPerHttp1Connection()
{
var connectionId = _http1ConnectionContext.ConnectionId;
var feature = ((IFeatureCollection)_http1Connection).Get<IHttpRequestIdentifierFeature>();
// Reset() is called once in the test ctor
var count = 1;
void Reset()
{
_http1Connection.Reset();
count++;
}
var nextId = feature.TraceIdentifier;
Assert.Equal($"{connectionId}:00000001", nextId);
Reset();
var secondId = feature.TraceIdentifier;
Assert.Equal($"{connectionId}:00000002", secondId);
var big = 1_000_000;
while (big-- > 0) Reset();
Assert.Equal($"{connectionId}:{count:X8}", feature.TraceIdentifier);
}
[Fact]
public void TraceIdentifierGeneratesWhenNull()
{
_http1Connection.TraceIdentifier = null;
var id = _http1Connection.TraceIdentifier;
Assert.NotNull(id);
Assert.Equal(id, _http1Connection.TraceIdentifier);
_http1Connection.Reset();
Assert.NotEqual(id, _http1Connection.TraceIdentifier);
}
[Fact]
public async Task ResetResetsHeaderLimits()
{
const string headerLine1 = "Header-1: value1\r\n";
const string headerLine2 = "Header-2: value2\r\n";
var options = new KestrelServerOptions();
options.Limits.MaxRequestHeadersTotalSize = headerLine1.Length;
options.Limits.MaxRequestHeaderCount = 1;
_serviceContext.ServerOptions = options;
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"{headerLine1}\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var takeMessageHeaders = _http1Connection.TakeMessageHeaders(readableBuffer, trailers: false, out _consumed, out _examined);
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.True(takeMessageHeaders);
Assert.Equal(1, _http1Connection.RequestHeaders.Count);
Assert.Equal("value1", _http1Connection.RequestHeaders["Header-1"]);
_http1Connection.Reset();
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"{headerLine2}\r\n"));
readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
takeMessageHeaders = _http1Connection.TakeMessageHeaders(readableBuffer, trailers: false, out _consumed, out _examined);
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.True(takeMessageHeaders);
Assert.Equal(1, _http1Connection.RequestHeaders.Count);
Assert.Equal("value2", _http1Connection.RequestHeaders["Header-2"]);
}
[Fact]
public async Task ThrowsWhenStatusCodeIsSetAfterResponseStarted()
{
// Act
await _http1Connection.WriteAsync(new ArraySegment<byte>(new byte[1]));
// Assert
Assert.True(_http1Connection.HasResponseStarted);
Assert.Throws<InvalidOperationException>(() => ((IHttpResponseFeature)_http1Connection).StatusCode = StatusCodes.Status404NotFound);
}
[Fact]
public async Task ThrowsWhenReasonPhraseIsSetAfterResponseStarted()
{
// Act
await _http1Connection.WriteAsync(new ArraySegment<byte>(new byte[1]));
// Assert
Assert.True(_http1Connection.HasResponseStarted);
Assert.Throws<InvalidOperationException>(() => ((IHttpResponseFeature)_http1Connection).ReasonPhrase = "Reason phrase");
}
[Fact]
public async Task ThrowsWhenOnStartingIsSetAfterResponseStarted()
{
await _http1Connection.WriteAsync(new ArraySegment<byte>(new byte[1]));
// Act/Assert
Assert.True(_http1Connection.HasResponseStarted);
Assert.Throws<InvalidOperationException>(() => ((IHttpResponseFeature)_http1Connection).OnStarting(_ => Task.CompletedTask, null));
}
[Theory]
[MemberData(nameof(MinDataRateData))]
public void ConfiguringIHttpMinRequestBodyDataRateFeatureSetsMinRequestBodyDataRate(MinDataRate minDataRate)
{
((IFeatureCollection)_http1Connection).Get<IHttpMinRequestBodyDataRateFeature>().MinDataRate = minDataRate;
Assert.Same(minDataRate, _http1Connection.MinRequestBodyDataRate);
}
[Theory]
[MemberData(nameof(MinDataRateData))]
public void ConfiguringIHttpMinResponseDataRateFeatureSetsMinResponseDataRate(MinDataRate minDataRate)
{
((IFeatureCollection)_http1Connection).Get<IHttpMinResponseDataRateFeature>().MinDataRate = minDataRate;
Assert.Same(minDataRate, _http1Connection.MinResponseDataRate);
}
[Fact]
public void ResetResetsRequestHeaders()
{
// Arrange
var originalRequestHeaders = _http1Connection.RequestHeaders;
_http1Connection.RequestHeaders = new HttpRequestHeaders();
// Act
_http1Connection.Reset();
// Assert
Assert.Same(originalRequestHeaders, _http1Connection.RequestHeaders);
}
[Fact]
public void ResetResetsResponseHeaders()
{
// Arrange
var originalResponseHeaders = _http1Connection.ResponseHeaders;
_http1Connection.ResponseHeaders = new HttpResponseHeaders();
// Act
_http1Connection.Reset();
// Assert
Assert.Same(originalResponseHeaders, _http1Connection.ResponseHeaders);
}
[Fact]
public void InitializeStreamsResetsStreams()
{
// Arrange
var messageBody = Http1MessageBody.For(Kestrel.Core.Internal.Http.HttpVersion.Http11, (HttpRequestHeaders)_http1Connection.RequestHeaders, _http1Connection);
_http1Connection.InitializeBodyControl(messageBody);
var originalRequestBody = _http1Connection.RequestBody;
var originalResponseBody = _http1Connection.ResponseBody;
_http1Connection.RequestBody = new MemoryStream();
_http1Connection.ResponseBody = new MemoryStream();
// Act
_http1Connection.InitializeBodyControl(messageBody);
// Assert
Assert.Same(originalRequestBody, _http1Connection.RequestBody);
Assert.Same(originalResponseBody, _http1Connection.ResponseBody);
}
[Theory]
[MemberData(nameof(RequestLineValidData))]
public async Task TakeStartLineSetsHttpProtocolProperties(
string requestLine,
string expectedMethod,
string expectedRawTarget,
// This warns that theory methods should use all of their parameters,
// but this method is using a shared data collection with HttpParserTests.ParsesRequestLine and others.
#pragma warning disable xUnit1026
string expectedRawPath,
#pragma warning restore xUnit1026
string expectedDecodedPath,
string expectedQueryString,
string expectedHttpVersion)
{
var requestLineBytes = Encoding.ASCII.GetBytes(requestLine);
await _application.Output.WriteAsync(requestLineBytes);
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var returnValue = _http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined);
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.True(returnValue);
Assert.Equal(expectedMethod, ((IHttpRequestFeature)_http1Connection).Method);
Assert.Equal(expectedRawTarget, _http1Connection.RawTarget);
Assert.Equal(expectedDecodedPath, _http1Connection.Path);
Assert.Equal(expectedQueryString, _http1Connection.QueryString);
Assert.Equal(expectedHttpVersion, _http1Connection.HttpVersion);
}
[Theory]
[MemberData(nameof(RequestLineDotSegmentData))]
public async Task TakeStartLineRemovesDotSegmentsFromTarget(
string requestLine,
string expectedRawTarget,
string expectedDecodedPath,
string expectedQueryString)
{
var requestLineBytes = Encoding.ASCII.GetBytes(requestLine);
await _application.Output.WriteAsync(requestLineBytes);
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var returnValue = _http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined);
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.True(returnValue);
Assert.Equal(expectedRawTarget, _http1Connection.RawTarget);
Assert.Equal(expectedDecodedPath, _http1Connection.Path);
Assert.Equal(expectedQueryString, _http1Connection.QueryString);
}
[Fact]
public async Task ParseRequestStartsRequestHeadersTimeoutOnFirstByteAvailable()
{
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes("G"));
_http1Connection.ParseRequest((await _transport.Input.ReadAsync()).Buffer, out _consumed, out _examined);
_transport.Input.AdvanceTo(_consumed, _examined);
var expectedRequestHeadersTimeout = _serviceContext.ServerOptions.Limits.RequestHeadersTimeout.Ticks;
_timeoutControl.Verify(cc => cc.ResetTimeout(expectedRequestHeadersTimeout, TimeoutReason.RequestHeaders));
}
[Fact]
public async Task TakeStartLineThrowsWhenTooLong()
{
_serviceContext.ServerOptions.Limits.MaxRequestLineSize = "GET / HTTP/1.1\r\n".Length;
var requestLineBytes = Encoding.ASCII.GetBytes("GET /a HTTP/1.1\r\n");
await _application.Output.WriteAsync(requestLineBytes);
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() => _http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.BadRequest_RequestLineTooLong, exception.Message);
Assert.Equal(StatusCodes.Status414UriTooLong, exception.StatusCode);
}
[Theory]
[MemberData(nameof(TargetWithEncodedNullCharData))]
public async Task TakeStartLineThrowsOnEncodedNullCharInTarget(string target)
{
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"GET {target} HTTP/1.1\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() =>
_http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.FormatBadRequest_InvalidRequestTarget_Detail(target), exception.Message);
}
[Theory]
[MemberData(nameof(TargetWithNullCharData))]
public async Task TakeStartLineThrowsOnNullCharInTarget(string target)
{
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"GET {target} HTTP/1.1\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() =>
_http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.FormatBadRequest_InvalidRequestTarget_Detail(target.EscapeNonPrintable()), exception.Message);
}
[Theory]
[MemberData(nameof(MethodWithNullCharData))]
public async Task TakeStartLineThrowsOnNullCharInMethod(string method)
{
var requestLine = $"{method} / HTTP/1.1\r\n";
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(requestLine));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() =>
_http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.FormatBadRequest_InvalidRequestLine_Detail(requestLine.EscapeNonPrintable()), exception.Message);
}
[Theory]
[MemberData(nameof(QueryStringWithNullCharData))]
public async Task TakeStartLineThrowsOnNullCharInQueryString(string queryString)
{
var target = $"/{queryString}";
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"GET {target} HTTP/1.1\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() =>
_http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.FormatBadRequest_InvalidRequestTarget_Detail(target.EscapeNonPrintable()), exception.Message);
}
[Theory]
[MemberData(nameof(TargetInvalidData))]
public async Task TakeStartLineThrowsWhenRequestTargetIsInvalid(string method, string target)
{
var requestLine = $"{method} {target} HTTP/1.1\r\n";
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(requestLine));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() =>
_http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.FormatBadRequest_InvalidRequestTarget_Detail(target.EscapeNonPrintable()), exception.Message);
}
[Theory]
[MemberData(nameof(MethodNotAllowedTargetData))]
public async Task TakeStartLineThrowsWhenMethodNotAllowed(string requestLine, int intAllowedMethod)
{
var allowedMethod = (HttpMethod)intAllowedMethod;
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(requestLine));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() =>
_http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(405, exception.StatusCode);
Assert.Equal(CoreStrings.BadRequest_MethodNotAllowed, exception.Message);
Assert.Equal(HttpUtilities.MethodToString(allowedMethod), exception.AllowedHeader);
}
[Fact]
public async Task ProcessRequestsAsyncEnablesKeepAliveTimeout()
{
var requestProcessingTask = _http1Connection.ProcessRequestsAsync<object>(null);
var expectedKeepAliveTimeout = _serviceContext.ServerOptions.Limits.KeepAliveTimeout.Ticks;
_timeoutControl.Verify(cc => cc.SetTimeout(expectedKeepAliveTimeout, TimeoutReason.KeepAlive));
_http1Connection.StopProcessingNextRequest();
_application.Output.Complete();
await requestProcessingTask.DefaultTimeout();
}
[Fact]
public async Task WriteThrowsForNonBodyResponse()
{
// Arrange
((IHttpResponseFeature)_http1Connection).StatusCode = StatusCodes.Status304NotModified;
// Act/Assert
await Assert.ThrowsAsync<InvalidOperationException>(() => _http1Connection.WriteAsync(new ArraySegment<byte>(new byte[1])));
}
[Fact]
public async Task WriteAsyncThrowsForNonBodyResponse()
{
// Arrange
_http1Connection.HttpVersion = "HTTP/1.1";
((IHttpResponseFeature)_http1Connection).StatusCode = StatusCodes.Status304NotModified;
// Act/Assert
await Assert.ThrowsAsync<InvalidOperationException>(() => _http1Connection.WriteAsync(new ArraySegment<byte>(new byte[1]), default(CancellationToken)));
}
[Fact]
public async Task WriteDoesNotThrowForHeadResponse()
{
// Arrange
_http1Connection.HttpVersion = "HTTP/1.1";
_http1Connection.Method = HttpMethod.Head;
// Act/Assert
await _http1Connection.WriteAsync(new ArraySegment<byte>(new byte[1]));
}
[Fact]
public async Task WriteAsyncDoesNotThrowForHeadResponse()
{
// Arrange
_http1Connection.HttpVersion = "HTTP/1.1";
_http1Connection.Method = HttpMethod.Head;
// Act/Assert
await _http1Connection.WriteAsync(new ArraySegment<byte>(new byte[1]), default(CancellationToken));
}
[Fact]
public async Task ManuallySettingTransferEncodingThrowsForHeadResponse()
{
// Arrange
_http1Connection.HttpVersion = "HTTP/1.1";
_http1Connection.Method = HttpMethod.Head;
// Act
_http1Connection.ResponseHeaders.Add("Transfer-Encoding", "chunked");
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(() => _http1Connection.FlushAsync());
}
[Fact]
public async Task ManuallySettingTransferEncodingThrowsForNoBodyResponse()
{
// Arrange
_http1Connection.HttpVersion = "HTTP/1.1";
((IHttpResponseFeature)_http1Connection).StatusCode = StatusCodes.Status304NotModified;
// Act
_http1Connection.ResponseHeaders.Add("Transfer-Encoding", "chunked");
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(() => _http1Connection.FlushAsync());
}
[Fact]
public async Task RequestProcessingTaskIsUnwrapped()
{
var requestProcessingTask = _http1Connection.ProcessRequestsAsync<object>(null);
var data = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nHost:\r\n\r\n");
await _application.Output.WriteAsync(data);
_http1Connection.StopProcessingNextRequest();
Assert.IsNotType<Task<Task>>(requestProcessingTask);
await requestProcessingTask.DefaultTimeout();
_application.Output.Complete();
}
[Fact]
public async Task RequestAbortedTokenIsResetBeforeLastWriteWithContentLength()
{
_http1Connection.ResponseHeaders["Content-Length"] = "12";
var original = _http1Connection.RequestAborted;
foreach (var ch in "hello, worl")
{
await _http1Connection.WriteAsync(new ArraySegment<byte>(new[] { (byte)ch }));
Assert.Equal(original, _http1Connection.RequestAborted);
}
await _http1Connection.WriteAsync(new ArraySegment<byte>(new[] { (byte)'d' }));
Assert.NotEqual(original, _http1Connection.RequestAborted);
_http1Connection.Abort(new ConnectionAbortedException());
Assert.False(original.IsCancellationRequested);
Assert.False(_http1Connection.RequestAborted.IsCancellationRequested);
}
[Fact]
public async Task RequestAbortedTokenIsResetBeforeLastWriteAsyncWithContentLength()
{
_http1Connection.ResponseHeaders["Content-Length"] = "12";
var original = _http1Connection.RequestAborted;
foreach (var ch in "hello, worl")
{
await _http1Connection.WriteAsync(new ArraySegment<byte>(new[] { (byte)ch }), default(CancellationToken));
Assert.Equal(original, _http1Connection.RequestAborted);
}
await _http1Connection.WriteAsync(new ArraySegment<byte>(new[] { (byte)'d' }), default(CancellationToken));
Assert.NotEqual(original, _http1Connection.RequestAborted);
_http1Connection.Abort(new ConnectionAbortedException());
Assert.False(original.IsCancellationRequested);
Assert.False(_http1Connection.RequestAborted.IsCancellationRequested);
}
[Fact]
public async Task RequestAbortedTokenIsResetBeforeLastWriteAsyncAwaitedWithContentLength()
{
_http1Connection.ResponseHeaders["Content-Length"] = "12";
var original = _http1Connection.RequestAborted;
// Only first write can be WriteAsyncAwaited
var startingTask = _http1Connection.InitializeResponseAwaited(Task.CompletedTask, 1);
await _http1Connection.WriteAsyncAwaited(startingTask, new ArraySegment<byte>(new[] { (byte)'h' }), default(CancellationToken));
Assert.Equal(original, _http1Connection.RequestAborted);
foreach (var ch in "ello, worl")
{
await _http1Connection.WriteAsync(new ArraySegment<byte>(new[] { (byte)ch }), default(CancellationToken));
Assert.Equal(original, _http1Connection.RequestAborted);
}
await _http1Connection.WriteAsync(new ArraySegment<byte>(new[] { (byte)'d' }), default(CancellationToken));
Assert.NotEqual(original, _http1Connection.RequestAborted);
_http1Connection.Abort(new ConnectionAbortedException());
Assert.False(original.IsCancellationRequested);
Assert.False(_http1Connection.RequestAborted.IsCancellationRequested);
}
[Fact]
public async Task RequestAbortedTokenIsResetBeforeLastWriteWithChunkedEncoding()
{
var original = _http1Connection.RequestAborted;
_http1Connection.HttpVersion = "HTTP/1.1";
await _http1Connection.WriteAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes("hello, world")), default(CancellationToken));
Assert.Equal(original, _http1Connection.RequestAborted);
await _http1Connection.ProduceEndAsync();
Assert.NotEqual(original, _http1Connection.RequestAborted);
_http1Connection.Abort(new ConnectionAbortedException());
Assert.False(original.IsCancellationRequested);
Assert.False(_http1Connection.RequestAborted.IsCancellationRequested);
}
[Fact]
public void RequestAbortedTokenIsFullyUsableAfterCancellation()
{
var originalToken = _http1Connection.RequestAborted;
var originalRegistration = originalToken.Register(() => { });
_http1Connection.Abort(new ConnectionAbortedException());
Assert.True(originalToken.WaitHandle.WaitOne(TestConstants.DefaultTimeout));
Assert.True(_http1Connection.RequestAborted.WaitHandle.WaitOne(TestConstants.DefaultTimeout));
Assert.Equal(originalToken, originalRegistration.Token);
}
[Fact]
public void RequestAbortedTokenIsUsableAfterCancellation()
{
var originalToken = _http1Connection.RequestAborted;
var originalRegistration = originalToken.Register(() => { });
_http1Connection.Abort(new ConnectionAbortedException());
// The following line will throw an ODE because the original CTS backing the token has been diposed.
// See https://github.com/aspnet/AspNetCore/pull/4447 for the history behind this test.
//Assert.True(originalToken.WaitHandle.WaitOne(TestConstants.DefaultTimeout));
Assert.True(_http1Connection.RequestAborted.WaitHandle.WaitOne(TestConstants.DefaultTimeout));
Assert.Equal(originalToken, originalRegistration.Token);
}
[Fact]
public async Task ExceptionDetailNotIncludedWhenLogLevelInformationNotEnabled()
{
var previousLog = _serviceContext.Log;
try
{
var mockTrace = new Mock<IKestrelTrace>();
mockTrace
.Setup(trace => trace.IsEnabled(LogLevel.Information))
.Returns(false);
_serviceContext.Log = mockTrace.Object;
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes($"GET /%00 HTTP/1.1\r\n"));
var readableBuffer = (await _transport.Input.ReadAsync()).Buffer;
var exception = Assert.Throws<BadHttpRequestException>(() =>
_http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined));
_transport.Input.AdvanceTo(_consumed, _examined);
Assert.Equal(CoreStrings.FormatBadRequest_InvalidRequestTarget_Detail(string.Empty), exception.Message);
Assert.Equal(StatusCodes.Status400BadRequest, exception.StatusCode);
}
finally
{
_serviceContext.Log = previousLog;
}
}
[Theory]
[InlineData(1, 1)]
[InlineData(5, 5)]
[InlineData(100, 100)]
[InlineData(600, 100)]
[InlineData(700, 1)]
[InlineData(1, 700)]
public async Task AcceptsHeadersAcrossSends(int header0Count, int header1Count)
{
_serviceContext.ServerOptions.Limits.MaxRequestHeaderCount = header0Count + header1Count;
var headers0 = MakeHeaders(header0Count);
var headers1 = MakeHeaders(header1Count, header0Count);
var requestProcessingTask = _http1Connection.ProcessRequestsAsync<object>(null);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n"));
await WaitForCondition(TestConstants.DefaultTimeout, () => _http1Connection.RequestHeaders != null);
Assert.Equal(0, _http1Connection.RequestHeaders.Count);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(headers0));
await WaitForCondition(TestConstants.DefaultTimeout, () => _http1Connection.RequestHeaders.Count >= header0Count);
Assert.Equal(header0Count, _http1Connection.RequestHeaders.Count);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(headers1));
await WaitForCondition(TestConstants.DefaultTimeout, () => _http1Connection.RequestHeaders.Count >= header0Count + header1Count);
Assert.Equal(header0Count + header1Count, _http1Connection.RequestHeaders.Count);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes("\r\n"));
await requestProcessingTask.DefaultTimeout();
}
[Theory]
[InlineData(1, 1)]
[InlineData(5, 5)]
[InlineData(100, 100)]
[InlineData(600, 100)]
[InlineData(700, 1)]
[InlineData(1, 700)]
public async Task KeepsSameHeaderCollectionAcrossSends(int header0Count, int header1Count)
{
_serviceContext.ServerOptions.Limits.MaxRequestHeaderCount = header0Count + header1Count;
var headers0 = MakeHeaders(header0Count);
var headers1 = MakeHeaders(header1Count, header0Count);
var requestProcessingTask = _http1Connection.ProcessRequestsAsync<object>(null);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n"));
await WaitForCondition(TestConstants.DefaultTimeout, () => _http1Connection.RequestHeaders != null);
Assert.Equal(0, _http1Connection.RequestHeaders.Count);
var newRequestHeaders = new RequestHeadersWrapper(_http1Connection.RequestHeaders);
_http1Connection.RequestHeaders = newRequestHeaders;
Assert.Same(newRequestHeaders, _http1Connection.RequestHeaders);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(headers0));
await WaitForCondition(TestConstants.DefaultTimeout, () => _http1Connection.RequestHeaders.Count >= header0Count);
Assert.Same(newRequestHeaders, _http1Connection.RequestHeaders);
Assert.Equal(header0Count, _http1Connection.RequestHeaders.Count);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(headers1));
await WaitForCondition(TestConstants.DefaultTimeout, () => _http1Connection.RequestHeaders.Count >= header0Count + header1Count);
Assert.Same(newRequestHeaders, _http1Connection.RequestHeaders);
Assert.Equal(header0Count + header1Count, _http1Connection.RequestHeaders.Count);
await _application.Output.WriteAsync(Encoding.ASCII.GetBytes("\r\n"));
await requestProcessingTask.TimeoutAfter(TimeSpan.FromSeconds(10));
}
[Fact]
public void ThrowsWhenMaxRequestBodySizeIsSetAfterReadingFromRequestBody()
{
// Act
// This would normally be set by the MessageBody during the first read.
_http1Connection.HasStartedConsumingRequestBody = true;
// Assert
Assert.True(((IHttpMaxRequestBodySizeFeature)_http1Connection).IsReadOnly);
var ex = Assert.Throws<InvalidOperationException>(() => ((IHttpMaxRequestBodySizeFeature)_http1Connection).MaxRequestBodySize = 1);
Assert.Equal(CoreStrings.MaxRequestBodySizeCannotBeModifiedAfterRead, ex.Message);
}
[Fact]
public void ThrowsWhenMaxRequestBodySizeIsSetToANegativeValue()
{
// Assert
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => ((IHttpMaxRequestBodySizeFeature)_http1Connection).MaxRequestBodySize = -1);
Assert.StartsWith(CoreStrings.NonNegativeNumberOrNullRequired, ex.Message);
}
[Fact]
public async Task ConsumesRequestWhenApplicationDoesNotConsumeIt()
{
var httpApplication = new DummyApplication(async context =>
{
var buffer = new byte[10];
await context.Response.Body.WriteAsync(buffer, 0, 10);
});
var mockMessageBody = new Mock<MessageBody>(null);
_http1Connection.NextMessageBody = mockMessageBody.Object;
var requestProcessingTask = _http1Connection.ProcessRequestsAsync(httpApplication);
var data = Encoding.ASCII.GetBytes("POST / HTTP/1.1\r\nHost:\r\nConnection: close\r\ncontent-length: 1\r\n\r\n");
await _application.Output.WriteAsync(data);
await requestProcessingTask.DefaultTimeout();
mockMessageBody.Verify(body => body.ConsumeAsync(), Times.Once);
}
[Fact]
public void Http10HostHeaderNotRequired()
{
_http1Connection.HttpVersion = "HTTP/1.0";
_http1Connection.EnsureHostHeaderExists();
}
[Fact]
public void Http10HostHeaderAllowed()
{
_http1Connection.HttpVersion = "HTTP/1.0";
_http1Connection.RequestHeaders[HeaderNames.Host] = "localhost:5000";
_http1Connection.EnsureHostHeaderExists();
}
[Fact]
public void Http11EmptyHostHeaderAccepted()
{
_http1Connection.HttpVersion = "HTTP/1.1";
_http1Connection.RequestHeaders[HeaderNames.Host] = "";
_http1Connection.EnsureHostHeaderExists();
}
[Fact]
public void Http11ValidHostHeadersAccepted()
{
_http1Connection.HttpVersion = "HTTP/1.1";
_http1Connection.RequestHeaders[HeaderNames.Host] = "localhost:5000";
_http1Connection.EnsureHostHeaderExists();
}
[Fact]
public void BadRequestFor10BadHostHeaderFormat()
{
_http1Connection.HttpVersion = "HTTP/1.0";
_http1Connection.RequestHeaders[HeaderNames.Host] = "a=b";
var ex = Assert.Throws<BadHttpRequestException>(() => _http1Connection.EnsureHostHeaderExists());
Assert.Equal(CoreStrings.FormatBadRequest_InvalidHostHeader_Detail("a=b"), ex.Message);
}
[Fact]
public void BadRequestFor11BadHostHeaderFormat()
{
_http1Connection.HttpVersion = "HTTP/1.1";
_http1Connection.RequestHeaders[HeaderNames.Host] = "a=b";
var ex = Assert.Throws<BadHttpRequestException>(() => _http1Connection.EnsureHostHeaderExists());
Assert.Equal(CoreStrings.FormatBadRequest_InvalidHostHeader_Detail("a=b"), ex.Message);
}
private static async Task WaitForCondition(TimeSpan timeout, Func<bool> condition)
{
const int MaxWaitLoop = 150;
var delay = (int)Math.Ceiling(timeout.TotalMilliseconds / MaxWaitLoop);
var waitLoop = 0;
while (waitLoop < MaxWaitLoop && !condition())
{
// Wait for parsing condition to trigger
await Task.Delay(delay);
waitLoop++;
}
}
private static string MakeHeaders(int count, int startAt = 0)
{
return string.Join("", Enumerable
.Range(0, count)
.Select(i => $"Header-{startAt + i}: value{startAt + i}\r\n"));
}
public static IEnumerable<object[]> RequestLineValidData => HttpParsingData.RequestLineValidData;
public static IEnumerable<object[]> RequestLineDotSegmentData => HttpParsingData.RequestLineDotSegmentData;
public static TheoryData<string> TargetWithEncodedNullCharData
{
get
{
var data = new TheoryData<string>();
foreach (var target in HttpParsingData.TargetWithEncodedNullCharData)
{
data.Add(target);
}
return data;
}
}
public static TheoryData<string, string> TargetInvalidData
=> HttpParsingData.TargetInvalidData;
public static TheoryData<string, int> MethodNotAllowedTargetData
=> HttpParsingData.MethodNotAllowedRequestLine;
public static TheoryData<string> TargetWithNullCharData
{
get
{
var data = new TheoryData<string>();
foreach (var target in HttpParsingData.TargetWithNullCharData)
{
data.Add(target);
}
return data;
}
}
public static TheoryData<string> MethodWithNullCharData
{
get
{
var data = new TheoryData<string>();
foreach (var target in HttpParsingData.MethodWithNullCharData)
{
data.Add(target);
}
return data;
}
}
public static TheoryData<string> QueryStringWithNullCharData
{
get
{
var data = new TheoryData<string>();
foreach (var target in HttpParsingData.QueryStringWithNullCharData)
{
data.Add(target);
}
return data;
}
}
public static TheoryData<MinDataRate> MinDataRateData => new TheoryData<MinDataRate>
{
null,
new MinDataRate(bytesPerSecond: 1, gracePeriod: TimeSpan.MaxValue)
};
private class RequestHeadersWrapper : IHeaderDictionary
{
IHeaderDictionary _innerHeaders;
public RequestHeadersWrapper(IHeaderDictionary headers)
{
_innerHeaders = headers;
}
public StringValues this[string key] { get => _innerHeaders[key]; set => _innerHeaders[key] = value; }
public long? ContentLength { get => _innerHeaders.ContentLength; set => _innerHeaders.ContentLength = value; }
public ICollection<string> Keys => _innerHeaders.Keys;
public ICollection<StringValues> Values => _innerHeaders.Values;
public int Count => _innerHeaders.Count;
public bool IsReadOnly => _innerHeaders.IsReadOnly;
public void Add(string key, StringValues value) => _innerHeaders.Add(key, value);
public void Add(KeyValuePair<string, StringValues> item) => _innerHeaders.Add(item);
public void Clear() => _innerHeaders.Clear();
public bool Contains(KeyValuePair<string, StringValues> item) => _innerHeaders.Contains(item);
public bool ContainsKey(string key) => _innerHeaders.ContainsKey(key);
public void CopyTo(KeyValuePair<string, StringValues>[] array, int arrayIndex) => _innerHeaders.CopyTo(array, arrayIndex);
public IEnumerator<KeyValuePair<string, StringValues>> GetEnumerator() => _innerHeaders.GetEnumerator();
public bool Remove(string key) => _innerHeaders.Remove(key);
public bool Remove(KeyValuePair<string, StringValues> item) => _innerHeaders.Remove(item);
public bool TryGetValue(string key, out StringValues value) => _innerHeaders.TryGetValue(key, out value);
IEnumerator IEnumerable.GetEnumerator() => _innerHeaders.GetEnumerator();
}
}
}
| 42.834106 | 175 | 0.656649 | [
"Apache-2.0"
] | MichalStrehovsky/AspNetCore | src/Servers/Kestrel/Core/test/Http1ConnectionTests.cs | 46,218 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace IdsPlusContext
{
public class Tenant
{
[Required]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public string Notes { get; set; }
}
} | 17.75 | 44 | 0.598592 | [
"MIT"
] | Code-Inside/Samples | 2017/IdsPlusContext/IdsPlusContext/Tenant.cs | 284 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace LanguageServer.Json
{
/// <nodoc />
public sealed class StringOrObject<TObject> : Either<string, TObject>
{
/// <nodoc />
public static implicit operator StringOrObject<TObject>(string left)
=> new StringOrObject<TObject>(left);
/// <nodoc />
public static implicit operator StringOrObject<TObject>(TObject right)
=> new StringOrObject<TObject>(right);
/// <nodoc />
public StringOrObject()
{
}
/// <nodoc />
public StringOrObject(string left)
: base(left)
{
}
/// <nodoc />
public StringOrObject(TObject right)
: base(right)
{
}
/// <nodoc />
protected override EitherTag OnDeserializing(JsonDataType jsonType)
{
return
(jsonType == JsonDataType.String) ? EitherTag.Left :
(jsonType == JsonDataType.Object) ? EitherTag.Right :
EitherTag.None;
}
}
}
| 28.272727 | 102 | 0.539389 | [
"MIT"
] | AzureMentor/BuildXL | Public/Src/IDE/LanguageServerProtocol/LanguageServer/Json/StringOrObject.cs | 1,244 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using AutoMapper;
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute
{
[Cmdlet("Remove", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMAccessExtension",SupportsShouldProcess = true)]
[OutputType(typeof(PSAzureOperationResponse))]
public class RemoveAzureVMAccessExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ResourceGroupCompleter]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The virtual machine name.")]
[ResourceNameCompleter("Microsoft.Compute/virtualMachines", "ResourceGroupName")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Alias("ExtensionName")]
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The extension name.")]
[ResourceNameCompleter("Microsoft.Compute/virtualMachines/extensions", "ResourceGroupName", "VMName")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(HelpMessage = "To force the removal.")]
[ValidateNotNullOrEmpty]
public SwitchParameter Force { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Starts the operation and returns immediately, before the operation is completed. In order to determine if the operation has successfully been completed, use some other mechanism.")]
public SwitchParameter NoWait { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (this.ShouldProcess(VMName, Properties.Resources.RemoveAccessExtensionAction)
&& (this.Force.IsPresent
|| this.ShouldContinue(Properties.Resources.VirtualMachineExtensionRemovalConfirmation, Properties.Resources.VirtualMachineExtensionRemovalCaption)))
{
if (NoWait.IsPresent)
{
var op = this.VirtualMachineExtensionClient.BeginDeleteWithHttpMessagesAsync(this.ResourceGroupName,
this.VMName,
this.Name).GetAwaiter().GetResult();
var result = ComputeAutoMapperProfile.Mapper.Map<PSAzureOperationResponse>(op);
WriteObject(result);
}
else
{
var op = this.VirtualMachineExtensionClient.DeleteWithHttpMessagesAsync(this.ResourceGroupName,
this.VMName,
this.Name).GetAwaiter().GetResult();
var result = ComputeAutoMapperProfile.Mapper.Map<PSAzureOperationResponse>(op);
WriteObject(result);
}
}
});
}
}
}
| 46.159574 | 235 | 0.595529 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Compute/Compute/Extension/VMAccess/RemoveAzureVMAccessExtension.cs | 4,248 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Semmle.Util
{
/// <summary>
/// Utility to temporarily rename a set of files.
/// </summary>
public sealed class FileRenamer : IDisposable
{
private readonly string[] files;
private const string suffix = ".codeqlhidden";
public FileRenamer(IEnumerable<FileInfo> oldFiles)
{
files = oldFiles.Select(f => f.FullName).ToArray();
foreach (var file in files)
{
File.Move(file, file + suffix);
}
}
public void Dispose()
{
foreach (var file in files)
{
File.Move(file + suffix, file);
}
}
}
}
| 22.542857 | 63 | 0.534854 | [
"MIT"
] | 00mjk/codeql | csharp/extractor/Semmle.Util/FileRenamer.cs | 791 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Razor.ProjectSystem;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.AspNetCore.Razor.LanguageServer
{
internal abstract class GeneratedDocumentPublisher : ProjectSnapshotChangeTrigger
{
public abstract void PublishCSharp(string filePath, SourceText sourceText, int hostDocumentVersion);
public abstract void PublishHtml(string filePath, SourceText sourceText, int hostDocumentVersion);
}
}
| 38.125 | 108 | 0.793443 | [
"MIT"
] | dougbu/razor-tooling | src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs | 612 | C# |
using System.Collections.Generic;
using Sample.Concrete.Repository.Entities;
namespace Sample.Concrete.Repository
{
public interface IBaseRepository<T> where T : BaseEntity
{
IEnumerable<T> Get();
T Get(long id);
void Create(T entity);
void Update(T entity);
void Delete(T entity);
}
} | 19.944444 | 61 | 0.618384 | [
"MIT"
] | rdyc/sample | src/Sample.Concrete.Repository/IBaseRepository.cs | 359 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace UMA
{
/// <summary>
/// This ScriptableObject class is used for advanced mesh hiding with UMA and the DCS.
/// </summary>
/// <remarks>
/// This class simply stores a link to a SlotDataAsset (the slot to get hiding applied to) and a list of the slot's triangles as a BitArray.
/// Each bit indicates a flag of whether the triangle should be hidden or not in the final generated UMA.
/// After creating the MeshHideAsset, it can then be added to a list in a wardrobe recipes. This makes it so when the wardrobe recipe is active and the slot associated
/// with the MeshHideAsset is found in the UMA recipe, then apply the triangle hiding to the slot. MeshHideAsset's are also unioned, so multiple MeshHideAssets with
/// the same slotData can combine to hide their unioned list.
/// </remarks>
public class MeshHideAsset : ScriptableObject, ISerializationCallbackReceiver
{
/// <summary>
/// The asset we want to apply mesh hiding to if found in the generated UMA.
/// </summary>
/// <value>The SlotDataAsset.</value>
[SerializeField]
public SlotDataAsset asset
{
get
{
if (_asset != null)
{
_assetSlotName = _asset.slotName;
_asset = null;
}
return UMAContextAdpterIndexer.AdapterResource.GetAsset<SlotDataAsset>(_assetSlotName);
}
set
{
if (value != null)
_assetSlotName = value.slotName;
else
{
_assetSlotName = "";
}
}
}
[SerializeField, HideInInspector]
private SlotDataAsset _asset;
public bool HasReference
{
get { return _asset != null; }
}
public string AssetSlotName
{
get {
if (string.IsNullOrEmpty(_assetSlotName))
{
if (_asset != null)
{
_assetSlotName = _asset.slotName;
}
}
return _assetSlotName;
}
set
{
_assetSlotName = value;
}
}
[SerializeField, HideInInspector]
private string _assetSlotName = "";
/// <summary>
/// BitArray of the triangle flags list. The list stores only the first index of the triangle vertex in the asset's triangle list.
/// </summary>
/// <value>The array of BitArrays. A BitArray for each submesh triangle list.</value>
public BitArray[] triangleFlags { get { return _triangleFlags; }}
private BitArray[] _triangleFlags;
[System.Serializable]
public class serializedFlags
{
public int[] flags;
public int Count;
public serializedFlags(int count)
{
Count = count;
flags = new int[(Count + 31) / 32];
}
}
[SerializeField]
private serializedFlags[] _serializedFlags;
public int SubmeshCount
{
get
{
if (_triangleFlags != null)
{
return _triangleFlags.Length;
}
else
return 0;
}
}
/// <summary>
/// If this contains a reference to an asset, it is freed.
/// This asset reference is no longer needed, and
/// forces the asset to be included in the build.
/// It is kept only for upgrading from earlier UMA versions
/// </summary>
public void FreeReference()
{
if (_asset != null)
{
_assetSlotName = _asset.slotName;
_asset = null;
}
}
/// <summary>
/// Gets the total triangle count in the multidimensional triangleFlags.
/// </summary>
/// <value>The triangle count.</value>
public int TriangleCount
{
get
{
if (_triangleFlags != null)
{
int total = 0;
for (int i = 0; i < _triangleFlags.Length; i++)
total += _triangleFlags[i].Count;
return total;
}
else
return 0;
}
}
/// <summary>
/// Gets the hidden triangles count.
/// </summary>
/// <value>The hidden triangles count.</value>
public int HiddenCount
{
get
{
if (_triangleFlags != null)
{
int total = 0;
for (int i = 0; i < _triangleFlags.Length; i++)
{
total += UMAUtils.GetCardinality(_triangleFlags[i]);
}
return total;
}
else
return 0;
}
}
#if UNITY_EDITOR
[ContextMenu("CopyToClipboard")]
public void CopyToClipboard()
{
UnityEditor.EditorGUIUtility.systemCopyBuffer = JsonUtility.ToJson(this);
}
[ContextMenu("PasteFromClipboard")]
public void PasteFromClipboard()
{
JsonUtility.FromJsonOverwrite(UnityEditor.EditorGUIUtility.systemCopyBuffer, this);
}
#endif
/// <summary>
/// Custom serialization to write the BitArray to a boolean array.
/// </summary>
public void OnBeforeSerialize()
{
// _asset = null; // Let's not save this!
if (_triangleFlags == null)
return;
if (TriangleCount > 0)
{
_serializedFlags = new serializedFlags[_triangleFlags.Length];
for (int i = 0; i < _triangleFlags.Length; i++)
{
_serializedFlags[i] = new serializedFlags(_triangleFlags[i].Length);
_serializedFlags[i].flags.Initialize();
}
}
for (int i = 0; i < _triangleFlags.Length; i++)
{
_triangleFlags[i].CopyTo(_serializedFlags[i].flags, 0);
}
if (_serializedFlags == null)
{
if(Debug.isDebugBuild)
Debug.LogError("Serializing triangle flags failed!");
}
}
/// <summary>
/// Custom deserialization to write the boolean array to the BitArray.
/// </summary>
public void OnAfterDeserialize()
{
//We're not logging an error here because we'll get spammed by it for empty/not-set assets.
if (_asset == null && string.IsNullOrEmpty(_assetSlotName))
{
return;
}
if (_asset != null)
{
_assetSlotName = _asset.slotName;
}
if (_serializedFlags == null)
return;
if (_serializedFlags.Length > 0)
{
_triangleFlags = new BitArray[_serializedFlags.Length];
for (int i = 0; i < _serializedFlags.Length; i++)
{
_triangleFlags[i] = new BitArray(_serializedFlags[i].flags);
_triangleFlags[i].Length = _serializedFlags[i].Count;
}
}
}
/// <summary>
/// Initialize this asset by creating a new boolean array that matches the triangle length in the asset triangle list.
/// </summary>
[ExecuteInEditMode]
public void Initialize()
{
SlotDataAsset slot = asset;
if (slot == null)
{
_triangleFlags = null;
return;
}
if (slot.meshData == null)
return;
_triangleFlags = new BitArray[slot.meshData.subMeshCount];
for (int i = 0; i < slot.meshData.subMeshCount; i++)
{
_triangleFlags[i] = new BitArray(slot.meshData.submeshes[i].triangles.Length / 3);
}
}
/// <summary>
/// Set the triangle flag's boolean value
/// </summary>
/// <param name="triangleIndex">The first index for the triangle to set.</param>
/// <param name="flag">Bool to set the triangle flag to.</param>
/// <param name="submesh">The submesh index to access. Default = 0.</param>
[ExecuteInEditMode]
public void SetTriangleFlag(int triangleIndex, bool flag, int submesh = 0)
{
if (_triangleFlags == null)
{
if(Debug.isDebugBuild)
Debug.LogError("Triangle Array not initialized!");
return;
}
if (triangleIndex >= 0 && (_triangleFlags[submesh].Length - 3) > triangleIndex)
{
_triangleFlags[submesh][triangleIndex] = flag;
}
}
/// <summary>
/// Set the given BitArray to this object's triangleFlag's BitArray.
/// </summary>
/// <param name="selection">The BitArray selection.</param>
[ExecuteInEditMode]
public void SaveSelection( BitArray selection )
{
int submesh = asset.subMeshIndex;
if (selection.Count != _triangleFlags[submesh].Count)
{
if (Debug.isDebugBuild)
Debug.Log("SaveSelection: counts don't match!");
return;
}
//Only works for submesh 0 for now
_triangleFlags[submesh].SetAll(false);
if (selection.Length == _triangleFlags[submesh].Length)
_triangleFlags[submesh] = new BitArray(selection);
else
{
if (Debug.isDebugBuild)
Debug.LogWarning("SaveSelection: counts don't match!");
}
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
/// <summary>
/// Generates a final BitArray mask from a list of MeshHideAssets.
/// </summary>
/// <returns>The BitArray array mask.</returns>
/// <param name="assets">List of MeshHideAssets.</param>
public static BitArray[] GenerateMask( List<MeshHideAsset> assets )
{
List<BitArray[]> flags = new List<BitArray[]>();
foreach (MeshHideAsset asset in assets)
flags.Add(asset.triangleFlags);
return CombineTriangleFlags(flags);
}
/// <summary>
/// Combines the list of BitArray arrays.
/// </summary>
/// <returns>The final combined BitArray array.</returns>
/// <param name="flags">List of BitArray array flags.</param>
public static BitArray[] CombineTriangleFlags( List<BitArray[]> flags)
{
if (flags == null || flags.Count <= 0)
return null;
BitArray[] final = new BitArray[flags[0].Length];
for(int i = 0; i < flags[0].Length; i++)
{
final[i] = new BitArray(flags[0][i]);
}
for (int i = 1; i < flags.Count; i++)
{
for (int j = 0; j < flags[i].Length; j++)
{
if (flags[i][j].Count == flags[0][j].Count)
final[j].Or(flags[i][j]);
}
}
return final;
}
#if UNITY_EDITOR
#if UMA_HOTKEYS
[UnityEditor.MenuItem("Assets/Create/UMA/Misc/Mesh Hide Asset %#h")]
#else
[UnityEditor.MenuItem("Assets/Create/UMA/Misc/Mesh Hide Asset")]
#endif
public static void CreateMeshHideAsset()
{
UMA.CustomAssetUtility.CreateAsset<MeshHideAsset>();
}
#endif
}
} | 32.170213 | 173 | 0.508846 | [
"MIT"
] | coding2233/UMA | UMAProject/Assets/UMA/Core/StandardAssets/UMA/Scripts/MeshHideAsset.cs | 12,098 | C# |
// Copyright(c) Microsoft Corporation.
// All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the solution root folder for full license information
using System.Net.Http;
using System.Threading.Tasks;
namespace ApplicationCore.Interfaces
{
public interface IProposalManagerClientFactory
{
Task<HttpClient> GetProposalManagerClientAsync();
}
} | 25.2 | 108 | 0.791005 | [
"MIT"
] | laujan/ProposalManager | ApplicationCore/Interfaces/IProposalManagerClientFactory.cs | 380 | C# |
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System.Globalization;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StockTraderRI.Modules.News.Services;
namespace StockTraderRI.Modules.News.Tests.Services
{
[TestClass]
public class NewsFeedServiceFixture
{
[TestMethod]
public void HavingACurrentCultureDifferentThanEnglishShouldNotThrows()
{
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("es-AR");
NewsFeedService newsFeedService = new NewsFeedService();
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
}
| 45.410256 | 93 | 0.608696 | [
"MIT"
] | TataDvd/G | 2012/Tempo2012/Tempo2012.UI.WPF/StockTrader RI/Desktop/StockTraderRI.Modules.News.Tests/Services/NewsFeedServiceFixture.cs | 1,771 | C# |
#if !NETSTANDARD13
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codestar-notifications-2019-10-15.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.CodeStarNotifications.Model
{
/// <summary>
/// Paginator for the ListTargets operation
///</summary>
public interface IListTargetsPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListTargetsResponse> Responses { get; }
/// <summary>
/// Enumerable containing all of the Targets
/// </summary>
IPaginatedEnumerable<TargetSummary> Targets { get; }
}
}
#endif | 32.45 | 120 | 0.691063 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeStarNotifications/Generated/Model/_bcl45+netstandard/IListTargetsPaginator.cs | 1,298 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17626
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sannel.TestHelpers.Tests.Resources
{
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class AppResources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal AppResources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager
{
get
{
if (object.ReferenceEquals(resourceMan, null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sannel.TestHelpers.Tests.Resources.AppResources", typeof(AppResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to LeftToRight.
/// </summary>
public static string ResourceFlowDirection
{
get
{
return ResourceManager.GetString("ResourceFlowDirection", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to us-EN.
/// </summary>
public static string ResourceLanguage
{
get
{
return ResourceManager.GetString("ResourceLanguage", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MY APPLICATION.
/// </summary>
public static string ApplicationTitle
{
get
{
return ResourceManager.GetString("ApplicationTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to button.
/// </summary>
public static string AppBarButtonText
{
get
{
return ResourceManager.GetString("AppBarButtonText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to menu item.
/// </summary>
public static string AppBarMenuItemText
{
get
{
return ResourceManager.GetString("AppBarMenuItemText", resourceCulture);
}
}
}
}
| 28.671875 | 180 | 0.683924 | [
"Apache-2.0"
] | holtsoftware/Sannel.Helpers | Sannel.TestHelpers/WP 8.1 Silverlight/Sannel.TestHelpers.Tests/Resources/AppResources.Designer.cs | 3,672 | C# |
using CalculatorApp;
using Xunit;
namespace CalculatorTests
{
public class CalculatorTests
{
private readonly Calculator _calculator;
public CalculatorTests()
{
_calculator = new Calculator();
}
[Fact]
public void ShouldAddNumbers()
{
double actual = _calculator.Add(2, 3);
Assert.Equal(5, actual);
}
[Fact]
public void ShouldSubstractNumbers()
{
double actual = _calculator.Substract(5, 3);
Assert.Equal(2, actual);
}
[Fact]
public void ShouldMultiplyNumbers()
{
double actual = _calculator.Multiply(2, 3);
Assert.Equal(6, actual);
}
[Fact]
public void ShouldDivideNumbers()
{
double actual = _calculator.Divide(4, 2);
Assert.Equal(2, actual);
}
}
} | 19.604167 | 56 | 0.521785 | [
"Apache-2.0"
] | FilipAdamiak/tpw_game | CalculatorApp/CalculatorApp.Tests/CalculatorTests.cs | 941 | C# |
using Ferret.InGame.Data.Container;
using Ferret.InGame.Presentation.Controller;
using UnityEngine;
namespace Ferret.InGame.Domain.UseCase
{
public sealed class PlayerContainerUseCase
{
private readonly PlayerContainer _playerContainer;
public PlayerContainerUseCase(PlayerContainer playerContainer)
{
_playerContainer = playerContainer;
}
public void JumpAll()
{
_playerContainer.ControlAll(x => x.Jump());
}
public bool IsNone()
{
return _playerContainer.count == 0;
}
public int GetVictimCount()
{
return Mathf.Min(_playerContainer.count, InGameConfig.MAX_VICTIM_COUNT);
}
public PlayerController GetVictim()
{
return _playerContainer.Dequeue();
}
}
} | 23.888889 | 84 | 0.618605 | [
"MIT"
] | kitatas/FerretForever | Assets/Ferret/Scripts/InGame/Domain/UseCase/PlayerContainerUseCase.cs | 860 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DinkToPdf;
using DinkToPdf.Contracts;
using JRPC_HMS.Data;
using JRPC_HMS.Models;
using JRPC_HMS.Services.Mail;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using MimeKit;
namespace JRPC_HMS
{
[Authorize(Roles = "Admin, User")]
public class EditRequisitionModel : PageModel
{
private readonly IConverter _converter;
private readonly ApplicationDbContext _context;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IEmailSender _emailSender;
private readonly ILogger<CreateRequisitionModel> _logger;
public EditRequisitionModel(IConverter converter, ApplicationDbContext context,
IHostingEnvironment hostingEnvironment, UserManager<ApplicationUser> userManager,
IEmailSender emailSender, ILogger<CreateRequisitionModel> logger)
{
_converter = converter;
_context = context;
_hostingEnvironment = hostingEnvironment;
_userManager = userManager;
_logger = logger;
_emailSender = emailSender;
}
public IList<Requisition> Requisitions { get; set; }
public IList<Supplier> AllSuppliers { get; set; }
public List<SelectListItem> Suppliers { get; set; }
public Supplier Supplier { get; set; }
public IList<Warehouse> AllWarehouseStock { get; set; }
public List<SelectListItem> WarehouseStock { get; set; }
public IList<Warehouse> WStock { get; set; }
[BindProperty]
public int Quantity { get; set; }
[BindProperty]
public string SelectedSupplier { get; set; }
[BindProperty]
public string SelectedStock { get; set; }
public decimal Total { get; set; }
[BindProperty]
public IList<RequisitionModel> RequisitionModels { get; set; }
public ApplicationUser ApplicationUser { get; set; }
[BindProperty]
public string ReqNo { get; set; }
public async Task<IActionResult> OnGet(string reqNo)
{
Suppliers = _context.Suppliers.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.Name
}).ToList();
WarehouseStock = _context.WarehouseStock.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.StockName
}).ToList();
AllSuppliers = _context.Suppliers.AsNoTracking().ToList();
AllWarehouseStock = _context.WarehouseStock.AsNoTracking().ToList();
ApplicationUser = await _userManager.GetUserAsync(User);
Requisitions = _context.Requisitions.AsNoTracking().Where(r => r.ReqNo == reqNo).ToList();
Supplier = AllSuppliers.FirstOrDefault(s => s.Id == Requisitions.FirstOrDefault().SupplierId);
SelectedSupplier = Supplier.Name;
List<Warehouse> wStock = new List<Warehouse>();
foreach(var req in Requisitions)
{
wStock.Add(AllWarehouseStock.FirstOrDefault(w => w.Id == req.StockId));
}
WStock = wStock;
ReqNo = reqNo;
return Page();
}
public async Task<IActionResult> OnPost()
{
Suppliers = _context.Suppliers.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.Name
}).ToList();
WarehouseStock = _context.WarehouseStock.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.StockName
}).ToList();
AllSuppliers = _context.Suppliers.AsNoTracking().ToList();
AllWarehouseStock = _context.WarehouseStock.AsNoTracking().ToList();
ApplicationUser = await _userManager.GetUserAsync(User);
Requisitions = _context.Requisitions.AsNoTracking().Where(r => r.ReqNo == ReqNo).ToList();
Supplier = AllSuppliers.FirstOrDefault(s => s.Id == Requisitions.FirstOrDefault().SupplierId);
SelectedSupplier = Supplier.Name;
List<Warehouse> wStock = new List<Warehouse>();
foreach (var req in Requisitions)
{
wStock.Add(AllWarehouseStock.FirstOrDefault(w => w.Id == req.StockId));
}
WStock = wStock;
return Page();
}
public async Task<IActionResult> OnPostAddItems()
{
Suppliers = _context.Suppliers.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.Name
}).ToList();
WarehouseStock = _context.WarehouseStock.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.StockName
}).ToList();
AllSuppliers = _context.Suppliers.AsNoTracking().ToList();
AllWarehouseStock = _context.WarehouseStock.AsNoTracking().ToList();
Supplier = AllSuppliers.FirstOrDefault(s => s.Id == Requisitions.FirstOrDefault().SupplierId);
SelectedSupplier = Supplier.Name;
List<Warehouse> wStock = new List<Warehouse>();
foreach (var req in Requisitions)
{
wStock.Add(AllWarehouseStock.FirstOrDefault(w => w.Id == req.StockId));
}
WStock = wStock;
Warehouse warehouseStock = new Warehouse();
warehouseStock = _context.WarehouseStock.AsNoTracking().AsNoTracking().FirstOrDefault(s => s.Id == Convert.ToInt32(SelectedStock));
ApplicationUser = await _userManager.GetUserAsync(User);
Requisition requisition = new Requisition
{
StockId = warehouseStock.Id,
Quantity = Quantity,
Price = warehouseStock.Price,
Total = warehouseStock.Price * Quantity,
Requester = ApplicationUser.UserName,
ReqDate = DateTime.Now,
SupplierId = Convert.ToInt32(SelectedSupplier),
ReqNo = ReqNo,
Approved = "Waiting Approval",
ApprovedDate = DateTime.Now
};
await _context.Requisitions.AddAsync(requisition);
await _context.SaveChangesAsync();
Requisitions = _context.Requisitions.AsNoTracking().Where(r => r.ReqNo == ReqNo).ToList();
return Page();
}
public async Task<IActionResult> OnPostEditReq()
{
Suppliers = _context.Suppliers.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.Name
}).ToList();
WarehouseStock = _context.WarehouseStock.AsNoTracking().Select(n => new SelectListItem
{
Value = n.Id.ToString(),
Text = n.StockName
}).ToList();
AllSuppliers = _context.Suppliers.AsNoTracking().ToList();
AllWarehouseStock = _context.WarehouseStock.AsNoTracking().ToList();
ApplicationUser = await _userManager.GetUserAsync(User);
Supplier = AllSuppliers.FirstOrDefault(s => s.Id == Requisitions.FirstOrDefault().SupplierId);
SelectedSupplier = Supplier.Name;
List<Warehouse> wStock = new List<Warehouse>();
foreach (var req in Requisitions)
{
wStock.Add(AllWarehouseStock.FirstOrDefault(w => w.Id == req.StockId));
}
WStock = wStock;
if (await _userManager.IsInRoleAsync(ApplicationUser, "Admin"))
{
try
{
CreatePDF(AllSuppliers.FirstOrDefault(s => s.Id == Convert.ToInt32(SelectedSupplier)).Email, ReqNo);
}
catch (Exception)
{
_logger.LogError("Error in creating PDF");
}
Requisitions = _context.Requisitions.AsNoTracking().Where(r => r.ReqNo == ReqNo).ToList();
foreach (var req in Requisitions)
{
req.Approved = "Approved";
req.ApprovedDate = DateTime.Now;
req.Approver = ApplicationUser.UserName;
_context.Requisitions.Update(req);
}
_context.SaveChanges();
TempData["StatusMessage"] = "Requisition created, approved and sent to supplier.";
}
else
{
TempData["StatusMessage"] = "Requisition created and waiting approval.";
}
return Redirect("~/WarehousePages/RequisitionIndex");
}
public IActionResult OnPostCancelRequisition()
{
Requisitions = _context.Requisitions.AsNoTracking().Where(r => r.ReqNo == ReqNo).ToList();
_context.Requisitions.RemoveRange(Requisitions);
_context.SaveChanges();
TempData["StatusMessage"] = "Requisition was cancelled.";
return Redirect("~/WarehousePages/RequisitionIndex");
}
public void CreatePDF(string supplierEmail, string reqNo)
{
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Landscape,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 10 },
Out = Path.Combine(_hostingEnvironment.WebRootPath, reqNo + ".pdf")
};
var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent = GetHTMLString(supplierEmail),
WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(_hostingEnvironment.WebRootPath, "/libs/bootstrap/css", "bootstrap.css") },
HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
};
var pdf = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings }
};
_converter.Convert(pdf);
// Sending Mail
List<InternetAddress> toEmailAddresses = new List<InternetAddress>();
List<InternetAddress> fromEmailAddresses = new List<InternetAddress>();
MailboxAddress toAddress = new MailboxAddress(supplierEmail);
toEmailAddresses.Add(toAddress);
MailboxAddress fromAddress = new MailboxAddress("rudman11@gmail.com");
fromEmailAddresses.Add(fromAddress);
EmailMessage emailMessage = new EmailMessage()
{
ToAddresses = toEmailAddresses,
FromAddresses = fromEmailAddresses,
Subject = "Stock Approval Waiting.",
Content = "",
Attachments = Path.Combine(_hostingEnvironment.WebRootPath, reqNo + ".pdf")
};
_emailSender.SendMail(emailMessage);
}
public string GetHTMLString(string supplierEmail)
{
Requisitions = _context.Requisitions.AsNoTracking().ToList();
var sb = new StringBuilder();
sb.AppendFormat(@"
<html>
<head>
</head>
<body>
<div class='header'><h1>Requisition</h1></div>
<table class='table'>
<tr>
<td colspan='2' align='right'>{0}</td>
</tr>
<tr>
<td>
<table class='table'>
<tr>
<th>Requisitioner Info</th>
</tr>
<tr>
<th>Name</th>
<td>{1} {2}</td>
</tr>
<tr>
<th>Phone</th>
<td>{3}</td>
</tr>
<tr>
<th>Email</th>
<td>{4}</td>
</tr>
</table>
</td>
<td>
<table class='table'>
<tr>
<th>Supplier Info</th>
</tr>
<tr>
<th>Name</th>
<td>{5}</td>
</tr>
<tr>
<th>Phone</th>
<td>{6}</td>
</tr>
<tr>
<th>Address</th>
<td>{7}</td>
</tr>
<tr>
<th>Email</th>
<td>{8}</td>
</tr>
<tr>
<th>Attention</th>
<td>{9}</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan='2'>
<table class='table'>
<thead>
<tr>
<th>Stock Item</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>", ReqNo, ApplicationUser.FirstName, ApplicationUser.LastName, ApplicationUser.PhoneNumber, ApplicationUser.Email,
AllSuppliers.FirstOrDefault(s => s.Email == supplierEmail).Name, AllSuppliers.FirstOrDefault(s => s.Email == supplierEmail).Phone,
AllSuppliers.FirstOrDefault(s => s.Email == supplierEmail).Address, AllSuppliers.FirstOrDefault(s => s.Email == supplierEmail).Email, AllSuppliers.FirstOrDefault(s => s.Email == supplierEmail).Contact);
foreach (var item in Requisitions)
{
sb.AppendFormat(@"
<tr>
<td>{0}</td>
<td>{1}</td>
<td>{2}</td>
<td>{3}</td>
</tr>", AllWarehouseStock.FirstOrDefault(w => w.Id == item.StockId).StockName, item.Quantity, item.Price, item.Total);
}
sb.Append(@"
</tbody>
</table>
</td>
</tr>
</table>
</body>
</html>");
return sb.ToString();
}
}
} | 47.548128 | 227 | 0.453748 | [
"MIT"
] | rudman11/JRPC_HMS | Pages/WarehousePages/EditRequisition.cshtml.cs | 17,785 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Linq;
using Dnn.PersonaBar.Library.Containers;
using Dnn.PersonaBar.Library.Permissions;
using Dnn.PersonaBar.Library.Repository;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework;
using DotNetNuke.Instrumentation;
using Newtonsoft.Json;
using MenuItem = Dnn.PersonaBar.Library.Model.MenuItem;
using PersonaBarMenu = Dnn.PersonaBar.Library.Model.PersonaBarMenu;
namespace Dnn.PersonaBar.Library.Controllers
{
public class PersonaBarController : ServiceLocator<IPersonaBarController, PersonaBarController>, IPersonaBarController
{
private static readonly DnnLogger Logger = DnnLogger.GetClassLogger(typeof(PersonaBarController));
private readonly IPersonaBarRepository _personaBarRepository;
public PersonaBarController()
{
_personaBarRepository = PersonaBarRepository.Instance;
}
public PersonaBarMenu GetMenu(PortalSettings portalSettings, UserInfo user)
{
try
{
var personaBarMenu = _personaBarRepository.GetMenu();
var filteredMenu = new PersonaBarMenu();
var rootItems = personaBarMenu.MenuItems.Where(m => PersonaBarContainer.Instance.RootItems.Contains(m.Identifier)).ToList();
GetPersonaBarMenuWithPermissionCheck(portalSettings, user, filteredMenu.MenuItems, rootItems);
PersonaBarContainer.Instance.FilterMenu(filteredMenu);
return filteredMenu;
}
catch (Exception e)
{
DotNetNuke.Services.Exceptions.Exceptions.LogException(e);
return new PersonaBarMenu();
}
}
public bool IsVisible(PortalSettings portalSettings, UserInfo user, MenuItem menuItem)
{
var visible = menuItem.Enabled
&& !(user.IsSuperUser && !menuItem.AllowHost)
&& MenuPermissionController.CanView(portalSettings.PortalId, menuItem);
if (visible)
{
try
{
var menuController = GetMenuItemController(menuItem);
visible = menuController == null || menuController.Visible(menuItem);
}
catch (Exception ex)
{
Logger.Error(ex);
visible = false;
}
}
return visible;
}
private bool GetPersonaBarMenuWithPermissionCheck(PortalSettings portalSettings, UserInfo user, IList<MenuItem> filterItems, IList<MenuItem> menuItems)
{
var menuFiltered = false;
foreach (var menuItem in menuItems)
{
try
{
if (!IsVisible(portalSettings, user, menuItem))
{
menuFiltered = true;
continue;
}
var cloneItem = new MenuItem()
{
MenuId = menuItem.MenuId,
Identifier = menuItem.Identifier,
ModuleName = menuItem.ModuleName,
FolderName = menuItem.FolderName,
Controller = menuItem.Controller,
ResourceKey = menuItem.ResourceKey,
Path = menuItem.Path,
Link = menuItem.Link,
CssClass = menuItem.CssClass,
IconFile = menuItem.IconFile,
AllowHost = menuItem.AllowHost,
Order = menuItem.Order,
ParentId = menuItem.ParentId
};
UpdateParamters(cloneItem);
cloneItem.Settings = GetMenuSettings(menuItem);
var filtered = GetPersonaBarMenuWithPermissionCheck(portalSettings, user, cloneItem.Children,
menuItem.Children);
if (!filtered || cloneItem.Children.Count > 0)
{
filterItems.Add(cloneItem);
}
}
catch (Exception e) //Ignore the failure and still load personaBar
{
DotNetNuke.Services.Exceptions.Exceptions.LogException(e);
}
}
return menuFiltered;
}
private void UpdateParamters(MenuItem menuItem)
{
var menuController = GetMenuItemController(menuItem);
try
{
menuController?.UpdateParameters(menuItem);
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
private string GetMenuSettings(MenuItem menuItem)
{
IDictionary<string, object> settings;
try
{
var menuController = GetMenuItemController(menuItem);
settings = menuController?.GetSettings(menuItem) ?? new Dictionary<string, object>();
AddPermissions(menuItem, settings);
}
catch (Exception ex)
{
Logger.Error(ex);
settings = new Dictionary<string, object>();
}
return JsonConvert.SerializeObject(settings);
}
private void AddPermissions(MenuItem menuItem, IDictionary<string, object> settings)
{
var portalSettings = PortalSettings.Current;
if (!settings.ContainsKey("permissions") && portalSettings != null)
{
var menuPermissions = MenuPermissionController.GetPermissions(menuItem.MenuId)
.Where(p => p.PermissionKey != "VIEW");
var portalId = portalSettings.PortalId;
var permissions = new Dictionary<string, bool>();
foreach (var permission in menuPermissions)
{
var key = permission.PermissionKey;
var hasPermission = MenuPermissionController.HasMenuPermission(portalId, menuItem, key);
permissions.Add(key, hasPermission);
}
settings.Add("permissions", permissions);
}
}
private IMenuItemController GetMenuItemController(MenuItem menuItem)
{
var identifier = menuItem.Identifier;
var controller = menuItem.Controller;
if (string.IsNullOrEmpty(controller))
{
return null;
}
try
{
var cacheKey = $"PersonaBarMenuController_{identifier}";
return Reflection.CreateObject(controller, cacheKey) as IMenuItemController;
}
catch (Exception ex)
{
Logger.Error(ex);
return null;
}
}
protected override Func<IPersonaBarController> GetFactory()
{
return () => new PersonaBarController();
}
}
}
| 37.297561 | 160 | 0.535443 | [
"MIT"
] | Tychodewaard/Dnn.Platform | Dnn.AdminExperience/Library/Dnn.PersonaBar.Library/Controllers/PersonaBarController.cs | 7,648 | C# |
using System;
namespace Coffee.Beans.Tests.Utility
{
[BeanObject(BeanPolicy.OptOut)]
public class PlayerOptOut : Player
{
[BeanProperty]
public new string NickName { get; set; }
}
}
| 18 | 48 | 0.643519 | [
"MIT"
] | g3ntle/Coffee.Beans | test/Coffee.Beans.Tests/Utility/PlayerOptOut.cs | 218 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Metroit.Win32.Api
{
/// <summary>
/// ウィンドウメッセージを提供します。
/// </summary>
public static class WindowMessage
{
/// <summary>
/// キーの押下を定義します。
/// </summary>
public const int WM_KEYDOWN = 0x0100;
/// <summary>
/// キーのリリースを定義します。
/// </summary>
public const int WM_KEYUP = 0x0101;
/// <summary>
/// マウスホイール操作を定義します。
/// </summary>
public const int WM_MOUSEWHEEL = 0x020A;
/// <summary>
/// 貼り付けを定義します。
/// </summary>
public const int WM_PASTE = 0x0302;
/// <summary>
/// 切り取りを定義します。
/// </summary>
public const int WM_CUT = 0x0300;
/// <summary>
/// システムコマンドを定義します。
/// </summary>
public const int WM_SYSCOMMAND = 0x0112;
/// <summary>
/// ウィンドウのクライアント領域の描画を定義します。
/// </summary>
public const int WM_PAINT = 0x000F;
/// <summary>
/// ウインドウの非クライアント領域の描画を定義します。
/// </summary>
public const int WM_NCPAINT = 0x0085;
/// <summary>
/// IMEがキーストロークの結果としてコンポジション文字列を生成する直前に送信されるメッセージを定義します。
/// </summary>
public const int WM_IME_STARTCOMPOSITION = 0x010D;
/// <summary>
/// IMEが合成を終了すると送信されるメッセージを定義します。
/// </summary>
public const int WM_IME_ENDCOMPOSITION = 0x010E;
/// <summary>
/// IMEがキーストロークの結果として構成ステータスを変更すると送信されるメッセージを定義します。
/// </summary>
public const int WM_IME_COMPOSITION = 0x010F;
/// <summary>
/// イベントが発生したとき、またはコントロールが何らかの情報を必要とするときに、共通コントロールによってその親ウィンドウに送信されます。
/// </summary>
public const int WM_NOTIFY = 0x004E;
}
}
| 25.945205 | 79 | 0.529039 | [
"MIT"
] | takiru/Metro | net20/src/Metroit.2/Win32/Api/WindowMessage.cs | 2,556 | C# |
// <auto-generated />
using System;
using ElectionResults.Core.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace ElectionResults.Core.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20200928172740_AddedWinnersTable")]
partial class AddedWinnersTable
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.8")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("ElectionResults.Core.Entities.Article", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("AuthorId")
.HasColumnType("int");
b.Property<int>("BallotId")
.HasColumnType("int");
b.Property<string>("Body")
.HasColumnType("text");
b.Property<int>("ElectionId")
.HasColumnType("int");
b.Property<string>("Embed")
.HasColumnType("text");
b.Property<string>("Link")
.HasColumnType("text");
b.Property<DateTime>("Timestamp")
.HasColumnType("datetime");
b.Property<string>("Title")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.HasIndex("BallotId");
b.HasIndex("ElectionId");
b.ToTable("articles");
});
modelBuilder.Entity("ElectionResults.Core.Entities.ArticlePicture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("ArticleId")
.HasColumnType("int");
b.Property<string>("Url")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ArticleId");
b.ToTable("articlepictures");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Author", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Avatar")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("authors");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Ballot", b =>
{
b.Property<int>("BallotId")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("BallotType")
.HasColumnType("int");
b.Property<DateTime>("Date")
.HasColumnType("datetime");
b.Property<int>("ElectionId")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int?>("Round")
.HasColumnType("int");
b.Property<int?>("TurnoutId")
.HasColumnType("int");
b.HasKey("BallotId");
b.HasIndex("ElectionId");
b.HasIndex("TurnoutId");
b.ToTable("ballots");
});
modelBuilder.Entity("ElectionResults.Core.Entities.CandidateResult", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("BallotId")
.HasColumnType("int");
b.Property<int>("BallotPosition")
.HasColumnType("int");
b.Property<int?>("CountryId")
.HasColumnType("int");
b.Property<int?>("CountyId")
.HasColumnType("int");
b.Property<int>("Division")
.HasColumnType("int");
b.Property<int?>("LocalityId")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int>("NoVotes")
.HasColumnType("int");
b.Property<bool>("OverElectoralThreshold")
.HasColumnType("bit");
b.Property<int?>("PartyId")
.HasColumnType("int");
b.Property<string>("PartyName")
.HasColumnType("text");
b.Property<int>("Seats1")
.HasColumnType("int");
b.Property<int>("Seats2")
.HasColumnType("int");
b.Property<int>("SeatsGained")
.HasColumnType("int");
b.Property<string>("ShortName")
.HasColumnType("text");
b.Property<int>("TotalSeats")
.HasColumnType("int");
b.Property<int>("Votes")
.HasColumnType("int");
b.Property<int>("YesVotes")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BallotId");
b.HasIndex("CountyId");
b.HasIndex("LocalityId");
b.HasIndex("PartyId");
b.ToTable("candidateresults");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Country", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("countries");
});
modelBuilder.Entity("ElectionResults.Core.Entities.County", b =>
{
b.Property<int>("CountyId")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("ShortName")
.HasColumnType("text");
b.HasKey("CountyId");
b.ToTable("counties");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Election", b =>
{
b.Property<int>("ElectionId")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("Category")
.HasColumnType("int");
b.Property<DateTime>("Date")
.HasColumnType("datetime");
b.Property<bool>("Live")
.HasColumnType("bit");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Subtitle")
.HasColumnType("text");
b.HasKey("ElectionId");
b.ToTable("elections");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Locality", b =>
{
b.Property<int>("LocalityId")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("CountryId")
.HasColumnType("int");
b.Property<int>("CountyId")
.HasColumnType("int");
b.Property<int>("CountySiruta")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int>("Siruta")
.HasColumnType("int");
b.HasKey("LocalityId");
b.HasIndex("CountyId");
b.ToTable("localities");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Observation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("BallotId")
.HasColumnType("int");
b.Property<int>("CoveredCounties")
.HasColumnType("int");
b.Property<int>("CoveredPollingPlaces")
.HasColumnType("int");
b.Property<int>("IssueCount")
.HasColumnType("int");
b.Property<int>("MessageCount")
.HasColumnType("int");
b.Property<int>("ObserverCount")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("observations");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Party", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Alias")
.HasColumnType("text");
b.Property<string>("Color")
.HasColumnType("text");
b.Property<string>("LogoUrl")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("ShortName")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("parties");
});
modelBuilder.Entity("ElectionResults.Core.Entities.PartyResult", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("BallotId")
.HasColumnType("int");
b.Property<int>("PartyId")
.HasColumnType("int");
b.Property<int>("Votes")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("partyresults");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Turnout", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("BallotId")
.HasColumnType("int");
b.Property<int>("Circumscription")
.HasColumnType("int");
b.Property<int>("Coefficient")
.HasColumnType("int");
b.Property<int>("CorrespondenceVotes")
.HasColumnType("int");
b.Property<int?>("CountryId")
.HasColumnType("int");
b.Property<int?>("CountyId")
.HasColumnType("int");
b.Property<int>("Division")
.HasColumnType("int");
b.Property<int>("EligibleVoters")
.HasColumnType("int");
b.Property<int?>("LocalityId")
.HasColumnType("int");
b.Property<int>("Mandates")
.HasColumnType("int");
b.Property<int>("MinVotes")
.HasColumnType("int");
b.Property<int>("NullVotes")
.HasColumnType("int");
b.Property<int>("PermanentListsVotes")
.HasColumnType("int");
b.Property<int>("SpecialListsVotes")
.HasColumnType("int");
b.Property<int>("SuplimentaryVotes")
.HasColumnType("int");
b.Property<int>("Threshold")
.HasColumnType("int");
b.Property<int>("TotalSeats")
.HasColumnType("int");
b.Property<int>("TotalVotes")
.HasColumnType("int");
b.Property<int>("ValidVotes")
.HasColumnType("int");
b.Property<int>("VotesByMail")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("turnouts");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Winner", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int?>("BallotId")
.HasColumnType("int");
b.Property<int?>("CandidateId")
.HasColumnType("int");
b.Property<int?>("CountryId")
.HasColumnType("int");
b.Property<int?>("CountyId")
.HasColumnType("int");
b.Property<int>("Division")
.HasColumnType("int");
b.Property<int?>("LocalityId")
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<int?>("PartyId")
.HasColumnType("int");
b.Property<int?>("TurnoutId")
.HasColumnType("int");
b.Property<int>("Votes")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("BallotId");
b.HasIndex("CandidateId");
b.HasIndex("PartyId");
b.HasIndex("TurnoutId");
b.ToTable("Winners");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("varchar(256)");
b.Property<string>("Name")
.HasColumnType("varchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("varchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("varchar(127)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(767)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasColumnType("varchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp");
b.Property<string>("NormalizedEmail")
.HasColumnType("varchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("varchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("varchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(767)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.Property<string>("ProviderKey")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(767)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.Property<string>("RoleId")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.Property<string>("LoginProvider")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.Property<string>("Name")
.HasColumnType("varchar(127)")
.HasMaxLength(127);
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Article", b =>
{
b.HasOne("ElectionResults.Core.Entities.Author", "Author")
.WithMany()
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ElectionResults.Core.Entities.Ballot", "Ballot")
.WithMany()
.HasForeignKey("BallotId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ElectionResults.Core.Entities.Election", "Election")
.WithMany()
.HasForeignKey("ElectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ElectionResults.Core.Entities.ArticlePicture", b =>
{
b.HasOne("ElectionResults.Core.Entities.Article", null)
.WithMany("Pictures")
.HasForeignKey("ArticleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ElectionResults.Core.Entities.Ballot", b =>
{
b.HasOne("ElectionResults.Core.Entities.Election", "Election")
.WithMany("Ballots")
.HasForeignKey("ElectionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ElectionResults.Core.Entities.Turnout", "Turnout")
.WithMany()
.HasForeignKey("TurnoutId");
});
modelBuilder.Entity("ElectionResults.Core.Entities.CandidateResult", b =>
{
b.HasOne("ElectionResults.Core.Entities.Ballot", "Ballot")
.WithMany()
.HasForeignKey("BallotId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ElectionResults.Core.Entities.County", "County")
.WithMany()
.HasForeignKey("CountyId");
b.HasOne("ElectionResults.Core.Entities.Locality", "Locality")
.WithMany()
.HasForeignKey("LocalityId");
b.HasOne("ElectionResults.Core.Entities.Party", "Party")
.WithMany()
.HasForeignKey("PartyId");
});
modelBuilder.Entity("ElectionResults.Core.Entities.Locality", b =>
{
b.HasOne("ElectionResults.Core.Entities.County", "County")
.WithMany("Localities")
.HasForeignKey("CountyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ElectionResults.Core.Entities.Winner", b =>
{
b.HasOne("ElectionResults.Core.Entities.Ballot", "Ballot")
.WithMany()
.HasForeignKey("BallotId");
b.HasOne("ElectionResults.Core.Entities.CandidateResult", "Candidate")
.WithMany()
.HasForeignKey("CandidateId");
b.HasOne("ElectionResults.Core.Entities.Party", "Party")
.WithMany()
.HasForeignKey("PartyId");
b.HasOne("ElectionResults.Core.Entities.Turnout", "Turnout")
.WithMany()
.HasForeignKey("TurnoutId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 34.34657 | 95 | 0.419978 | [
"MPL-2.0"
] | Utwo/rezultate-vot-api | src/ElectionResults.Core/Migrations/20200928172740_AddedWinnersTable.Designer.cs | 28,544 | C# |
namespace Valhalla.Modules.Domain.Enums
{
public enum EAddressType
{
Delivery = 1,
Payment = 2
}
}
| 14.222222 | 40 | 0.578125 | [
"MIT"
] | Louzada08/valhalla-hexagonal-architecture | src/Modules/Valhalla.Modules.Domain/Enums/EAddressType.cs | 130 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Devices.V20200101.Outputs
{
[OutputType]
public sealed class IotDpsPropertiesDescriptionResponse
{
/// <summary>
/// Allocation policy to be used by this provisioning service.
/// </summary>
public readonly string? AllocationPolicy;
/// <summary>
/// List of authorization keys for a provisioning service.
/// </summary>
public readonly ImmutableArray<Outputs.SharedAccessSignatureAuthorizationRuleAccessRightsDescriptionResponse> AuthorizationPolicies;
/// <summary>
/// Device endpoint for this provisioning service.
/// </summary>
public readonly string DeviceProvisioningHostName;
/// <summary>
/// Unique identifier of this provisioning service.
/// </summary>
public readonly string IdScope;
/// <summary>
/// List of IoT hubs associated with this provisioning service.
/// </summary>
public readonly ImmutableArray<Outputs.IotHubDefinitionDescriptionResponse> IotHubs;
/// <summary>
/// The IP filter rules.
/// </summary>
public readonly ImmutableArray<Outputs.IpFilterRuleResponse> IpFilterRules;
/// <summary>
/// The ARM provisioning state of the provisioning service.
/// </summary>
public readonly string? ProvisioningState;
/// <summary>
/// Service endpoint for provisioning service.
/// </summary>
public readonly string ServiceOperationsHostName;
/// <summary>
/// Current state of the provisioning service.
/// </summary>
public readonly string? State;
[OutputConstructor]
private IotDpsPropertiesDescriptionResponse(
string? allocationPolicy,
ImmutableArray<Outputs.SharedAccessSignatureAuthorizationRuleAccessRightsDescriptionResponse> authorizationPolicies,
string deviceProvisioningHostName,
string idScope,
ImmutableArray<Outputs.IotHubDefinitionDescriptionResponse> iotHubs,
ImmutableArray<Outputs.IpFilterRuleResponse> ipFilterRules,
string? provisioningState,
string serviceOperationsHostName,
string? state)
{
AllocationPolicy = allocationPolicy;
AuthorizationPolicies = authorizationPolicies;
DeviceProvisioningHostName = deviceProvisioningHostName;
IdScope = idScope;
IotHubs = iotHubs;
IpFilterRules = ipFilterRules;
ProvisioningState = provisioningState;
ServiceOperationsHostName = serviceOperationsHostName;
State = state;
}
}
}
| 35.905882 | 140 | 0.656291 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Devices/V20200101/Outputs/IotDpsPropertiesDescriptionResponse.cs | 3,052 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the firehose-2015-08-04.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.KinesisFirehose
{
/// <summary>
/// Configuration for accessing Amazon KinesisFirehose service
/// </summary>
public partial class AmazonKinesisFirehoseConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.100.34");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonKinesisFirehoseConfig()
{
this.AuthenticationServiceName = "firehose";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "firehose";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2015-08-04";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.475 | 106 | 0.59254 | [
"Apache-2.0"
] | icanread/aws-sdk-net | sdk/src/Services/KinesisFirehose/Generated/AmazonKinesisFirehoseConfig.cs | 2,118 | C# |
using System.IO;
namespace ReferenceAnalyzer.Core.ProjectEdit
{
public class ProjectAccess : IProjectAccess
{
public string Read(string path)
{
return File.ReadAllText(path);
}
public void Write(string path, string content)
{
File.WriteAllText(path, content);
}
}
}
| 19.555556 | 54 | 0.590909 | [
"MIT"
] | OptiNav/ReferenceAnalyzer | src/ReferenceAnalyzer.Core/ProjectEdit/ProjectAccess.cs | 352 | C# |
using Microsoft.AspNet.OData.Query;
namespace AutoMapper.AspNet.OData
{
/// <summary>
/// This class describes the settings to use during query composition.
/// </summary>
public class QuerySettings
{
/// <summary>
/// Settings for configuring OData options on the server
/// </summary>
public ODataSettings ODataSettings { get; set; }
/// <summary>
/// Miscellaneous arguments for IMapper.ProjectTo
/// </summary>
public ProjectionSettings ProjectionSettings { get; set; }
/// <summary>
/// Async Settings hold the cancellation token for async requests
/// </summary>
public AsyncSettings AsyncSettings { get; set; }
}
} | 29.8 | 74 | 0.616107 | [
"MIT"
] | darjanbogdan/AutoMapper.Extensions.OData | AutoMapper.AspNetCore.OData.EFCore/QuerySettings.cs | 747 | C# |
namespace Zoo
{
public class Gorilla : Mammal
{
public Gorilla(string name) : base(name) { }
}
}
| 14.75 | 52 | 0.567797 | [
"MIT"
] | vassdeniss/software-university-courses | csharp-oop/02.InheritanceExercise/E02.Zoo/Gorilla.cs | 120 | C# |
namespace IoTHs.Core
{
public static class IoTHsConstants
{
public const int MessageLoopDelay = 1; // Delay in ms for message loops
}
}
| 19.625 | 79 | 0.66242 | [
"MIT"
] | kreuzhofer/homeautomation | src/IoTApp/IoTHs.Core/IoTHsConstants.cs | 159 | C# |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using NLog.Targets;
/// <summary>
/// Provides simple programmatic configuration API used for trivial logging cases.
/// </summary>
public static class SimpleConfigurator
{
/// <summary>
/// Configures NLog for console logging so that all messages above and including
/// the <see cref="LogLevel.Info"/> level are output to the console.
/// </summary>
public static void ConfigureForConsoleLogging()
{
ConfigureForConsoleLogging(LogLevel.Info);
}
/// <summary>
/// Configures NLog for console logging so that all messages above and including
/// the specified level are output to the console.
/// </summary>
/// <param name="minLevel">The minimal logging level.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
public static void ConfigureForConsoleLogging(LogLevel minLevel)
{
ConsoleTarget consoleTarget = new ConsoleTarget();
LoggingConfiguration config = new LoggingConfiguration();
LoggingRule rule = new LoggingRule("*", minLevel, consoleTarget);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
}
/// <summary>
/// Configures NLog for to log to the specified target so that all messages
/// above and including the <see cref="LogLevel.Info"/> level are output.
/// </summary>
/// <param name="target">The target to log all messages to.</param>
public static void ConfigureForTargetLogging(Target target)
{
ConfigureForTargetLogging(target, LogLevel.Info);
}
/// <summary>
/// Configures NLog for to log to the specified target so that all messages
/// above and including the specified level are output.
/// </summary>
/// <param name="target">The target to log all messages to.</param>
/// <param name="minLevel">The minimal logging level.</param>
public static void ConfigureForTargetLogging(Target target, LogLevel minLevel)
{
LoggingConfiguration config = new LoggingConfiguration();
LoggingRule rule = new LoggingRule("*", minLevel, target);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
}
/// <summary>
/// Configures NLog for file logging so that all messages above and including
/// the <see cref="LogLevel.Info"/> level are written to the specified file.
/// </summary>
/// <param name="fileName">Log file name.</param>
public static void ConfigureForFileLogging(string fileName)
{
ConfigureForFileLogging(fileName, LogLevel.Info);
}
/// <summary>
/// Configures NLog for file logging so that all messages above and including
/// the specified level are written to the specified file.
/// </summary>
/// <param name="fileName">Log file name.</param>
/// <param name="minLevel">The minimal logging level.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
public static void ConfigureForFileLogging(string fileName, LogLevel minLevel)
{
FileTarget target = new FileTarget();
target.FileName = fileName;
ConfigureForTargetLogging(target, minLevel);
}
}
}
| 45.65812 | 177 | 0.672033 | [
"BSD-3-Clause"
] | BrandonLegault/NLog | src/NLog/Config/SimpleConfigurator.cs | 5,342 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace GenericMvc.Clients
{
public class ReadOnlyClient<T, TKey> : IReadOnlyClient<T, TKey>
where T : class
where TKey : IEquatable<TKey>
{
protected readonly HttpClient _client;
public readonly string AuthCookie;
public readonly string MimeType = "application/json";
public string Protocal { get; set; } = "http://";
public string HostName { get; set; } = "localhost";
public string HostUrl => Protocal + HostName;
public string ApiPath => "/api/" + typeof(T).Name;
public string GetAllRoute => ApiPath + "/getall";
public string GetRoute => ApiPath + "/get";
public ReadOnlyClient(
HttpClient fixtureClient,
string authCookie,
IList<JsonConverter> converters)
{
try
{
_client = fixtureClient ?? throw new ArgumentNullException(nameof(fixtureClient));
_client.DefaultRequestHeaders
.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders
.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
//setup JsonConvert
Func<JsonSerializerSettings> settingsMethod = () =>
{
var converterlist = converters;
JsonSerializerSettings settings = new JsonSerializerSettings
{
Converters = converterlist,
};
return settings;
};
JsonConvert.DefaultSettings = settingsMethod;
//login to rest and get cookie
AuthCookie = authCookie;
}
catch (Exception ex)
{
throw new Exception(typeof(T).Name + " Constructor Failed", ex);
}
}
/// <summary>
/// Sends the request.
/// </summary>
/// <param name="route">The route.</param>
/// <param name="method">The method.</param>
/// <param name="concatCookies">The concat cookies.</param>
/// <param name="content">The content.</param>
/// <returns></returns>
/// <exception cref="System.Exception">Sending Http Request Failed</exception>
public async Task<HttpResponseMessage> SendRequest(string route, string concatCookies, HttpMethod method, HttpContent content)
{
try
{
var message = new HttpRequestMessage(method, route);
//set headers
if (concatCookies != null)
message.Headers.Add("Cookie", concatCookies);
//set content
if (content != null)
message.Content = content;
return await _client.SendAsync(message);
}
catch (Exception ex)
{
throw new Exception(typeof(T).Name + ": Sending http Request Failed", ex);
}
}
public async Task<HttpResponseMessage> Get(TKey id, bool useAuth)
{
try
{
if (useAuth)
return await SendRequest(GetRoute + "?id=" + id, AuthCookie, HttpMethod.Get, null);
return await SendRequest(GetRoute + "?id=" + id, null, HttpMethod.Get, null);
}
catch (Exception ex)
{
throw new Exception(typeof(T).Name + ": Get Request Failed", ex);
}
}
public async Task<HttpResponseMessage> GetAll(bool useAuth)
{
try
{
if (useAuth)
return await SendRequest(GetAllRoute, AuthCookie, HttpMethod.Get, null);
return await SendRequest(GetAllRoute, null, HttpMethod.Get, null);
}
catch (Exception ex)
{
throw new Exception(typeof(T).Name + ": Get Request Failed", ex);
}
}
public async Task<T> Get(TKey id)
{
try
{
var response = await this.Get(id, true);
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>
(await response.Content.ReadAsStringAsync());
}
else if (response.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
else
{
throw new Exception("Response returned non-success code");
}
}
catch (Exception ex)
{
throw new Exception(typeof(T).Name + ": Get Request Failed", ex);
}
}
public async Task<IEnumerable<T>> GetAll()
{
try
{
var response = await GetAll(true);
if (!response.IsSuccessStatusCode)
throw new Exception("Response returned non-success code");
return JsonConvert.DeserializeObject<IEnumerable<T>>
(await response.Content.ReadAsStringAsync());
}
catch (Exception ex)
{
throw new Exception(typeof(T).Name + ": Get All Request Failed", ex);
}
}
}
} | 24.438202 | 128 | 0.669655 | [
"MIT"
] | clarkis117/GenericMvc | src/GenericMvc.Clients/ReadOnlyClient.cs | 4,352 | C# |
using Finanzuebersicht.Backend.Generated.Contract.Persistence.Modules.Accounting.AccountingEntries;
using Finanzuebersicht.Backend.Generated.Contract.Persistence.Modules.Accounting.Categories;
using Finanzuebersicht.Backend.Generated.Contract.Persistence.Modules.Accounting.CategorySearchTerms;
using System;
using System.Collections.Generic;
namespace Finanzuebersicht.Backend.Generated.Contract.Persistence.Modules.Accounting.Categories
{
public interface IDbCategoryDetail
{
Guid Id { get; set; }
IEnumerable<IDbAccountingEntry> AccountingEntries { get; set; }
IEnumerable<IDbCategory> ChildCategories { get; set; }
IDbCategory SuperCategory { get; set; }
IEnumerable<IDbCategorySearchTerm> CategorySearchTerms { get; set; }
string Title { get; set; }
string Color { get; set; }
}
} | 34.4 | 101 | 0.75814 | [
"MIT"
] | shuralw/Finanzuebersicht2.0 | Finanzuebersicht.CodeGeneration/2-Post-Contractor/Backend/Contract/Persistence/Modules/Accounting/Categories/DTOs/IDbCategoryDetail.cs | 860 | C# |
// <copyright file="ActivityExtensionsTest.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Google.Protobuf.Collections;
using OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation;
#if NET452
using OpenTelemetry.Internal;
#endif
using Xunit;
using OtlpCommon = Opentelemetry.Proto.Common.V1;
using OtlpTrace = Opentelemetry.Proto.Trace.V1;
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests
{
public class ActivityExtensionsTest
{
static ActivityExtensionsTest()
{
Activity.DefaultIdFormat = ActivityIdFormat.W3C;
Activity.ForceDefaultIdFormat = true;
var listener = new ActivityListener
{
ShouldListenTo = _ => true,
GetRequestedDataUsingParentId = (ref ActivityCreationOptions<string> options) => ActivityDataRequest.AllData,
GetRequestedDataUsingContext = (ref ActivityCreationOptions<ActivityContext> options) => ActivityDataRequest.AllData,
};
ActivitySource.AddActivityListener(listener);
}
[Fact]
public void ToOtlpResourceSpansTest()
{
var evenTags = new[] { new KeyValuePair<string, string>("k0", "v0") };
var oddTags = new[] { new KeyValuePair<string, string>("k1", "v1") };
var sources = new[]
{
new ActivitySource("even", "2.4.6"),
new ActivitySource("odd", "1.3.5"),
};
var activities = new List<Activity>();
Activity activity = null;
const int numOfSpans = 10;
bool isEven;
for (var i = 0; i < numOfSpans; i++)
{
isEven = i % 2 == 0;
var source = sources[i % 2];
var activityKind = isEven ? ActivityKind.Client : ActivityKind.Server;
var activityTags = isEven ? evenTags : oddTags;
activity = source.StartActivity($"span-{i}", activityKind, activity?.Context ?? default, activityTags);
activities.Add(activity);
}
activities.Reverse();
var otlpResourceSpans = activities.ToOtlpResourceSpans();
Assert.Single(otlpResourceSpans);
foreach (var instrumentationLibrarySpans in otlpResourceSpans.First().InstrumentationLibrarySpans)
{
Assert.Equal(numOfSpans / 2, instrumentationLibrarySpans.Spans.Count);
Assert.NotNull(instrumentationLibrarySpans.InstrumentationLibrary);
var expectedSpanNames = new List<string>();
var start = instrumentationLibrarySpans.InstrumentationLibrary.Name == "even" ? 0 : 1;
for (var i = start; i < numOfSpans; i += 2)
{
expectedSpanNames.Add($"span-{i}");
}
var otlpSpans = instrumentationLibrarySpans.Spans;
Assert.Equal(expectedSpanNames.Count, otlpSpans.Count);
var expectedTag = instrumentationLibrarySpans.InstrumentationLibrary.Name == "even"
? new OtlpCommon.AttributeKeyValue { Key = "k0", StringValue = "v0" }
: new OtlpCommon.AttributeKeyValue { Key = "k1", StringValue = "v1" };
foreach (var otlpSpan in otlpSpans)
{
Assert.Contains(otlpSpan.Name, expectedSpanNames);
Assert.Contains(expectedTag, otlpSpan.Attributes);
}
}
}
[Fact]
public void ToOtlpSpanTest()
{
var activitySource = new ActivitySource(nameof(this.ToOtlpSpanTest));
using var rootActivity = activitySource.StartActivity("root", ActivityKind.Producer);
var attributes = new Dictionary<string, object>
{
["bool"] = true,
["long"] = 1L,
["string"] = "text",
["double"] = 3.14,
["unknown_attrib_type"] =
new byte[] { 1 }, // TODO: update if arrays of standard attribute types are supported
};
var tags = new List<KeyValuePair<string, string>>(attributes.Count);
foreach (var kvp in attributes)
{
rootActivity.AddTag(kvp.Key, kvp.Value.ToString());
tags.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Value.ToString()));
}
var startTime = new DateTime(2020, 02, 20, 20, 20, 20, DateTimeKind.Utc);
DateTimeOffset dateTimeOffset;
#if NET452
dateTimeOffset = DateTimeOffsetExtensions.FromUnixTimeMilliseconds(0);
#else
dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(0);
#endif
var expectedUnixTimeTicks = (ulong)(startTime.Ticks - dateTimeOffset.Ticks);
var duration = TimeSpan.FromMilliseconds(1555);
rootActivity.SetStartTime(startTime);
rootActivity.SetEndTime(startTime + duration);
Span<byte> traceIdSpan = stackalloc byte[16];
rootActivity.TraceId.CopyTo(traceIdSpan);
var traceId = traceIdSpan.ToArray();
var otlpSpan = rootActivity.ToOtlpSpan();
Assert.NotNull(otlpSpan);
Assert.Equal("root", otlpSpan.Name);
Assert.Equal(OtlpTrace.Span.Types.SpanKind.Producer, otlpSpan.Kind);
Assert.Equal(traceId, otlpSpan.TraceId);
Assert.Empty(otlpSpan.ParentSpanId);
Assert.Null(otlpSpan.Status);
Assert.Empty(otlpSpan.Events);
Assert.Empty(otlpSpan.Links);
AssertActivityTagsIntoOtlpAttributes(tags, otlpSpan.Attributes);
var expectedStartTimeUnixNano = 100 * expectedUnixTimeTicks;
Assert.Equal(expectedStartTimeUnixNano, otlpSpan.StartTimeUnixNano);
var expectedEndTimeUnixNano = expectedStartTimeUnixNano + (duration.TotalMilliseconds * 1_000_000);
Assert.Equal(expectedEndTimeUnixNano, otlpSpan.EndTimeUnixNano);
var childLinks = new List<ActivityLink> { new ActivityLink(rootActivity.Context, attributes) };
var childActivity = activitySource.StartActivity(
"child",
ActivityKind.Client,
rootActivity.Context,
links: childLinks);
var childEvents = new List<ActivityEvent> { new ActivityEvent("e0"), new ActivityEvent("e1", attributes) };
childActivity.AddEvent(childEvents[0]);
childActivity.AddEvent(childEvents[1]);
Span<byte> parentIdSpan = stackalloc byte[8];
rootActivity.Context.SpanId.CopyTo(parentIdSpan);
var parentId = parentIdSpan.ToArray();
otlpSpan = childActivity.ToOtlpSpan();
Assert.NotNull(otlpSpan);
Assert.Equal("child", otlpSpan.Name);
Assert.Equal(OtlpTrace.Span.Types.SpanKind.Client, otlpSpan.Kind);
Assert.Equal(traceId, otlpSpan.TraceId);
Assert.Equal(parentId, otlpSpan.ParentSpanId);
Assert.Empty(otlpSpan.Attributes);
Assert.Equal(childEvents.Count, otlpSpan.Events.Count);
for (var i = 0; i < childEvents.Count; i++)
{
Assert.Equal(childEvents[i].Name, otlpSpan.Events[i].Name);
AssertOtlpAttributes(childEvents[i].Attributes.ToList(), otlpSpan.Events[i].Attributes);
}
childLinks.Reverse();
Assert.Equal(childLinks.Count, otlpSpan.Links.Count);
for (var i = 0; i < childLinks.Count; i++)
{
AssertOtlpAttributes(childLinks[i].Attributes.ToList(), otlpSpan.Links[i].Attributes);
}
}
private static void AssertActivityTagsIntoOtlpAttributes(
List<KeyValuePair<string, string>> expectedTags,
RepeatedField<OtlpCommon.AttributeKeyValue> otlpAttributes)
{
Assert.Equal(expectedTags.Count, otlpAttributes.Count);
for (var i = 0; i < expectedTags.Count; i++)
{
Assert.Equal(expectedTags[i].Key, otlpAttributes[i].Key);
AssertOtlpAttributeValue(expectedTags[i].Value, otlpAttributes[i]);
}
}
private static void AssertOtlpAttributes(
List<KeyValuePair<string, object>> expectedAttributes,
RepeatedField<OtlpCommon.AttributeKeyValue> otlpAttributes)
{
Assert.Equal(expectedAttributes.Count(), otlpAttributes.Count);
for (int i = 0; i < otlpAttributes.Count; i++)
{
Assert.Equal(expectedAttributes[i].Key, otlpAttributes[i].Key);
AssertOtlpAttributeValue(expectedAttributes[i].Value, otlpAttributes[i]);
}
}
private static void AssertOtlpAttributeValue(object originalValue, OtlpCommon.AttributeKeyValue akv)
{
switch (originalValue)
{
case string s:
Assert.Equal(akv.StringValue, s);
break;
case bool b:
Assert.Equal(akv.BoolValue, b);
break;
case long l:
Assert.Equal(akv.IntValue, l);
break;
case double d:
Assert.Equal(akv.DoubleValue, d);
break;
default:
Assert.Equal(akv.StringValue, originalValue?.ToString());
break;
}
}
}
}
| 40.708661 | 133 | 0.597389 | [
"Apache-2.0"
] | yallie/opentelemetry-dotnet | test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/ActivityExtensionsTest.cs | 10,342 | C# |
using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Text;
namespace EasyRpc.AspNetCore.CodeGeneration
{
/// <summary>
/// Used by 3rd party serializer to attribute type for serialization
/// </summary>
public interface ISerializationTypeAttributor
{
void AttributeType(TypeBuilder typeBuilder, string classNameHint);
void AttributeProperty(PropertyBuilder propertyBuilder, int index);
void AttributeMethodType(TypeBuilder typeBuilder, IEndPointMethodConfigurationReadOnly methodConfiguration);
void AttributeMethodProperty(PropertyBuilder propertyBuilder,
IEndPointMethodConfigurationReadOnly methodConfiguration,
RpcParameterInfo parameterInfoParameter);
}
}
| 32.708333 | 116 | 0.763057 | [
"MIT"
] | ipjohnson/EasyRpc | src/EasyRpc.AspNetCore/CodeGeneration/ISerializationTypeAttributor.cs | 787 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rekognition-2016-06-27.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Rekognition.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Rekognition.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ThrottlingException Object
/// </summary>
public class ThrottlingExceptionUnmarshaller : IErrorResponseUnmarshaller<ThrottlingException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ThrottlingException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public ThrottlingException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse)
{
context.Read();
ThrottlingException unmarshalledObject = new ThrottlingException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static ThrottlingExceptionUnmarshaller _instance = new ThrottlingExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ThrottlingExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.317647 | 130 | 0.647235 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Rekognition/Generated/Model/Internal/MarshallTransformations/ThrottlingExceptionUnmarshaller.cs | 3,002 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Launcher Loading Bar")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Launcher Loading Bar")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("68726311-ee29-4c09-a49c-0e548a84c384")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.054054 | 84 | 0.747869 | [
"MIT"
] | Lynxx21/Launcher-Samp-Loading-Bar | Properties/AssemblyInfo.cs | 1,411 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class general : Singleton<general>
{
protected general() { } // Protect the constructor!
public string globalVar;
public int lifeHero = 100;
public int staminaHero = 100;
public int globalHeroFace = 0;
public int globalHeroStars = 10;
public int globalHeroDeats = 0;
public bool obj1;
public bool obj2;
public bool obj3;
public bool obj21;
public bool obj22;
public bool obj23;
void Awake()
{
Debug.Log("Awoke Singleton Instance: " + gameObject.GetInstanceID());
}
public void DamageHero(int val)
{
if (lifeHero >=1)
{
lifeHero -= val;
}else if(lifeHero <= 0)
{
lifeHero = 0;
}
}
public void ResetHero()
{
lifeHero = 100;
staminaHero = 100;
}
} | 16.781818 | 77 | 0.587216 | [
"MIT"
] | ConradoAndrade/Dont-Trust-in-Drones | Assets/codes/general.cs | 923 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Bytewizer.TinyCLR.Http
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
/// <summary>
/// Well-know header names.
/// </summary>
public static partial class HeaderNames
{
// TODO: Trim size way down to most common
//public static readonly string Accept = "Accept";
//public static readonly string AcceptCharset = "Accept-Charset";
//public static readonly string AcceptEncoding = "Accept-Encoding";
//public static readonly string AcceptLanguage = "Accept-Language";
//public static readonly string AcceptRanges = "Accept-Ranges";
//public static readonly string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";
public static readonly string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
public static readonly string AccessControlAllowMethods = "Access-Control-Allow-Methods";
public static readonly string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
//public static readonly string AccessControlExposeHeaders = "Access-Control-Expose-Headers";
//public static readonly string AccessControlMaxAge = "Access-Control-Max-Age";
public static readonly string AccessControlRequestHeaders = "Access-Control-Request-Headers";
public static readonly string AccessControlRequestMethod = "Access-Control-Request-Method";
//public static readonly string Age = "Age";
//public static readonly string Allow = "Allow";
//public static readonly string AltSvc = "Alt-Svc";
//public static readonly string Authority = ":authority";
public static readonly string Authorization = "Authorization";
public static readonly string CacheControl = "Cache-Control";
public static readonly string Connection = "Connection";
public static readonly string ContentDisposition = "Content-Disposition";
public static readonly string ContentEncoding = "Content-Encoding";
//public static readonly string ContentLanguage = "Content-Language";
public static readonly string ContentLength = "Content-Length";
//public static readonly string ContentLocation = "Content-Location";
//public static readonly string ContentMD5 = "Content-MD5";
//public static readonly string ContentRange = "Content-Range";
//public static readonly string ContentSecurityPolicy = "Content-Security-Policy";
//public static readonly string ContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only";
public static readonly string ContentType = "Content-Type";
//public static readonly string CorrelationContext = "Correlation-Context";
public static readonly string Cookie = "Cookie";
public static readonly string Date = "Date";
//public static readonly string DNT = "DNT";
//public static readonly string ETag = "ETag";
//public static readonly string Expires = "Expires";
//public static readonly string Expect = "Expect";
//public static readonly string From = "From";
public static readonly string Host = "Host";
//public static readonly string KeepAlive = "Keep-Alive";
//public static readonly string IfMatch = "If-Match";
public static readonly string IfModifiedSince = "If-Modified-Since";
//public static readonly string IfNoneMatch = "If-None-Match";
//public static readonly string IfRange = "If-Range";
//public static readonly string IfUnmodifiedSince = "If-Unmodified-Since";
public static readonly string LastModified = "Last-Modified";
public static readonly string Location = "Location";
//public static readonly string MaxForwards = "Max-Forwards";
//public static readonly string Method = ":method";
public static readonly string Origin = "Origin";
//public static readonly string Path = ":path";
//public static readonly string Pragma = "Pragma";
//public static readonly string ProxyAuthenticate = "Proxy-Authenticate";
//public static readonly string ProxyAuthorization = "Proxy-Authorization";
//public static readonly string Range = "Range";
//public static readonly string Referer = "Referer";
//public static readonly string RetryAfter = "Retry-After";
//public static readonly string RequestId = "Request-Id";
//public static readonly string Scheme = ":scheme";
public static readonly string SecWebSocketAccept = "Sec-WebSocket-Accept";
public static readonly string SecWebSocketKey = "Sec-WebSocket-Key";
public static readonly string SecWebSocketProtocol = "Sec-WebSocket-Protocol";
public static readonly string SecWebSocketVersion = "Sec-WebSocket-Version";
public static readonly string Server = "Server";
public static readonly string SetCookie = "Set-Cookie";
//public static readonly string Status = ":status";
//public static readonly string StrictTransportSecurity = "Strict-Transport-Security";
//public static readonly string TE = "TE";
//public static readonly string Trailer = "Trailer";
//public static readonly string TransferEncoding = "Transfer-Encoding";
//public static readonly string Translate = "Translate";
//public static readonly string TraceParent = "traceparent";
//public static readonly string TraceState = "tracestate";
public static readonly string Upgrade = "Upgrade";
//public static readonly string UpgradeInsecureRequests = "Upgrade-Insecure-Requests";
//public static readonly string UserAgent = "User-Agent";
public static readonly string Vary = "Vary";
//public static readonly string Via = "Via";
//public static readonly string Warning = "Warning";
//public static readonly string WebSocketSubProtocols = "Sec-WebSocket-Protocol";
public static readonly string WWWAuthenticate = "WWW-Authenticate";
//public static readonly string XFrameOptions = "X-Frame-Options";
public static readonly string XContentTypeOptions = "X-Content-Type-Options";
}
}
| 64.1 | 112 | 0.701872 | [
"MIT"
] | bytewizer/microserver | src/Bytewizer.TinyCLR.Http/Http/HeaderNames.cs | 6,412 | C# |
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using Ordering.Domain.Events;
using Ordering.Domain.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate
{
public class Order
: Entity, IAggregateRoot
{
// DDD 模式 建议
// 使用私有字段(自EF Core 1.1以来就允许使用)是一种更好的封装
// 与DDD聚合和域实体 保持一致,(而不是只会用属性或者属性集合)
private DateTime _orderDate;
// Address是一个值对象模式示例,持久化为EF Core 2.0拥有的实体
public Address Address { get; private set; }
public int? GetBuyerId => _buyerId;
private int? _buyerId;
public OrderStatus OrderStatus { get; private set; }
private int _orderStatusId;
private string _description;
// 模拟的订单将此设置为true。目前我们不检查任何地方的草稿似的状态的订单,但如果需要,我们可以这样做
private bool _isDraft;
// DDD 模式 建议
// 使用私有集合字段,更适合DDD聚合的封装
// 因此,OrderItems不能从“AggregateRoot外部”直接添加到集合中,
// 只能通过包含领域行为的方法OrderAggrergateRoot.AddOrderItem()来添加进来。
private readonly List<OrderItem> _orderItems;
public IReadOnlyCollection<OrderItem> OrderItems => _orderItems;
private int? _paymentMethodId;
public static Order NewDraft()
{
var order = new Order();
order._isDraft = true;
return order;
}
protected Order()
{
_orderItems = new List<OrderItem>();
_isDraft = false;
}
// 添加订单方法,因为属性是私有的,只能通过构造函数添加
public Order(string userId, string userName, Address address, int cardTypeId, string cardNumber, string cardSecurityNumber,
string cardHolderName, DateTime cardExpiration, int? buyerId = null, int? paymentMethodId = null) : this()
{
_buyerId = buyerId;
_paymentMethodId = paymentMethodId;
_orderStatusId = OrderStatus.Submitted.Id;
_orderDate = DateTime.UtcNow;
Address = address;
// 将OrderStarterDomainEvent添加到域事件集合
// 在更新到数据库{执行DbContext.SaveChanges()} 以后,触发/调度
AddOrderStartedDomainEvent(userId, userName, cardTypeId, cardNumber,
cardSecurityNumber, cardHolderName, cardExpiration);
}
// DDD 模式 建议
// 这个Order AggregateRoot的方法 "AddOrderitem()" 应该是向订单添加项的唯一方法,
// 因此,任何行为(折扣等)和验证都由聚合根AggregateRoot控制
// 以保持整个聚合之间的一致性。
public void AddOrderItem(int productId, string productName, decimal unitPrice, decimal discount, string pictureUrl, int units = 1)
{
// 是否存在某一个产品的订单
var existingOrderForProduct = _orderItems.Where(o => o.ProductId == productId)
.SingleOrDefault();
if (existingOrderForProduct != null)
{
//如果discount大于当前的折扣,用更高的折扣和单位修改它。
if (discount > existingOrderForProduct.GetCurrentDiscount())
{
existingOrderForProduct.SetNewDiscount(discount);
}
existingOrderForProduct.AddUnits(units);
}
else
{
//添加经过验证的新订单项
var orderItem = new OrderItem(productId, productName, unitPrice, discount, pictureUrl, units);
_orderItems.Add(orderItem);
}
}
// 设置支付Id
public void SetPaymentId(int id)
{
_paymentMethodId = id;
}
// 设置买家Id
public void SetBuyerId(int id)
{
_buyerId = id;
}
// 设置订单状态为:等待验证,MediatR总线
public void SetAwaitingValidationStatus()
{
if (_orderStatusId == OrderStatus.Submitted.Id)
{
// 添加领域事件
AddDomainEvent(new OrderStatusChangedToAwaitingValidationDomainEvent(Id, _orderItems));
_orderStatusId = OrderStatus.AwaitingValidation.Id;
}
}
// 设置订单状态为:库存确认
public void SetStockConfirmedStatus()
{
if (_orderStatusId == OrderStatus.AwaitingValidation.Id)
{
AddDomainEvent(new OrderStatusChangedToStockConfirmedDomainEvent(Id));
_orderStatusId = OrderStatus.StockConfirmed.Id;
_description = "All the items were confirmed with available stock.";
}
}
// 设置订单状态为:已支付
public void SetPaidStatus()
{
if (_orderStatusId == OrderStatus.StockConfirmed.Id)
{
AddDomainEvent(new OrderStatusChangedToPaidDomainEvent(Id, OrderItems));
_orderStatusId = OrderStatus.Paid.Id;
_description = "The payment was performed at a simulated \"American Bank checking bank account ending on XX35071\"";
}
}
// 设置订单状态为:已发货
public void SetShippedStatus()
{
if (_orderStatusId != OrderStatus.Paid.Id)
{
StatusChangeException(OrderStatus.Shipped);
}
_orderStatusId = OrderStatus.Shipped.Id;
_description = "The order was shipped.";
AddDomainEvent(new OrderShippedDomainEvent(this));
}
// 设置订单状态为:已取消
public void SetCancelledStatus()
{
if (_orderStatusId == OrderStatus.Paid.Id ||
_orderStatusId == OrderStatus.Shipped.Id)
{
StatusChangeException(OrderStatus.Cancelled);
}
_orderStatusId = OrderStatus.Cancelled.Id;
_description = $"The order was cancelled.";
AddDomainEvent(new OrderCancelledDomainEvent(this));
}
// 设置订单状态为:当库存被拒绝时设置取消
public void SetCancelledStatusWhenStockIsRejected(IEnumerable<int> orderStockRejectedItems)
{
if (_orderStatusId == OrderStatus.AwaitingValidation.Id)
{
_orderStatusId = OrderStatus.Cancelled.Id;
var itemsStockRejectedProductNames = OrderItems
.Where(c => orderStockRejectedItems.Contains(c.ProductId))
.Select(c => c.GetOrderItemProductName());
var itemsStockRejectedDescription = string.Join(", ", itemsStockRejectedProductNames);
_description = $"The product items don't have stock: ({itemsStockRejectedDescription}).";
}
}
// 添加订单开始领域命令,SaveChange()后触发
private void AddOrderStartedDomainEvent(string userId, string userName, int cardTypeId, string cardNumber,
string cardSecurityNumber, string cardHolderName, DateTime cardExpiration)
{
var orderStartedDomainEvent = new OrderStartedDomainEvent(this, userId, userName, cardTypeId,
cardNumber, cardSecurityNumber,
cardHolderName, cardExpiration);
this.AddDomainEvent(orderStartedDomainEvent);
}
// 状态修改异常
private void StatusChangeException(OrderStatus orderStatusToChange)
{
throw new OrderingDomainException($"Is not possible to change the order status from {OrderStatus.Name} to {orderStatusToChange.Name}.");
}
// 获取订单添加项的总数
public decimal GetTotal()
{
return _orderItems.Sum(o => o.GetUnits() * o.GetUnitPrice());
}
}
}
| 34.843318 | 148 | 0.591588 | [
"MIT"
] | anjoy8/eShopOnContainersAs | src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Order.cs | 8,471 | C# |
using Newtonsoft.Json;
namespace HipChat.Net.Models.Response
{
[JsonObject]
public class Notification : IMessage
{
[JsonProperty("color")]
public string Color { get; set; }
[JsonProperty("date")]
public string Date { get; set; }
[JsonProperty("from")]
public string From { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("mentions")]
public Mention[] Mentions { get; set; }
[JsonProperty("message")]
public string MessageText { get; set; }
[JsonProperty("message_format")]
public string Format { get; set; }
public Notification()
{
Mentions = new[] { new Mention() };
}
}
} | 20.411765 | 43 | 0.615274 | [
"MIT"
] | cmsd2/manfred | src/HipChat.Net/Models/Response/Notification.cs | 696 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mindscape.Raygun4Net;
namespace Mindscape.Raygun4Net4.Tests
{
public class FakeRaygunClient : RaygunClient
{
public IEnumerable<Exception> ExposeStripWrapperExceptions(Exception exception)
{
return base.StripWrapperExceptions(exception);
}
}
}
| 21.294118 | 83 | 0.773481 | [
"MIT"
] | Havunen/raygun4net | Mindscape.Raygun4Net4.Tests/Model/FakeRaygunClient.cs | 364 | C# |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System.Threading;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public sealed class MethodReturnType : IConstantProvider, ICustomAttributeProvider/*, IMarshalInfoProvider*/ {
internal IMethodSignature method;
internal ParameterDefinition parameter;
TypeReference return_type;
public IMethodSignature Method {
get { return method; }
}
public TypeReference ReturnType {
get { return return_type; }
set { return_type = value; }
}
internal ParameterDefinition Parameter {
get {
if (parameter == null)
Interlocked.CompareExchange (ref parameter, new ParameterDefinition (return_type, method), null);
return parameter;
}
}
public MetadataToken MetadataToken {
get { return Parameter.MetadataToken; }
set { Parameter.MetadataToken = value; }
}
public ParameterAttributes Attributes {
get { return Parameter.Attributes; }
set { Parameter.Attributes = value; }
}
public string Name {
get { return Parameter.Name; }
set { Parameter.Name = value; }
}
public bool HasCustomAttributes {
get { return parameter != null && parameter.HasCustomAttributes; }
}
public Collection<CustomAttribute> CustomAttributes {
get { return Parameter.CustomAttributes; }
}
public bool HasDefault {
get { return parameter != null && parameter.HasDefault; }
set { Parameter.HasDefault = value; }
}
public bool HasConstant {
get { return parameter != null && parameter.HasConstant; }
set { Parameter.HasConstant = value; }
}
public object Constant {
get { return Parameter.Constant; }
set { Parameter.Constant = value; }
}
//public bool HasFieldMarshal {
// get { return parameter != null && parameter.HasFieldMarshal; }
// set { Parameter.HasFieldMarshal = value; }
//}
//public bool HasMarshalInfo {
// get { return parameter != null && parameter.HasMarshalInfo; }
//}
//public MarshalInfo MarshalInfo {
// get { return Parameter.MarshalInfo; }
// set { Parameter.MarshalInfo = value; }
//}
public MethodReturnType (IMethodSignature method)
{
this.method = method;
}
}
}
| 23.272727 | 111 | 0.689236 | [
"MIT"
] | TestCentric/TestCentric.Metadata | src/testcentric.engine.metadata/Mono.Cecil/MethodReturnType.cs | 2,304 | C# |
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
using LLVMSharp.Interop;
namespace LLVMSharp
{
public partial class Instruction
{
public enum BinaryOps
{
Add = LLVMOpcode.LLVMAdd,
FAdd = LLVMOpcode.LLVMFAdd,
Sub = LLVMOpcode.LLVMSub,
FSub = LLVMOpcode.LLVMFSub,
Mul = LLVMOpcode.LLVMMul,
FMul = LLVMOpcode.LLVMFMul,
UDiv = LLVMOpcode.LLVMUDiv,
SDiv = LLVMOpcode.LLVMSDiv,
FDiv = LLVMOpcode.LLVMFDiv,
URem = LLVMOpcode.LLVMURem,
SRem = LLVMOpcode.LLVMSRem,
FRem = LLVMOpcode.LLVMFRem,
Shl = LLVMOpcode.LLVMShl,
LShr = LLVMOpcode.LLVMLShr,
AShr = LLVMOpcode.LLVMAShr,
And = LLVMOpcode.LLVMAnd,
Or = LLVMOpcode.LLVMOr,
Xor = LLVMOpcode.LLVMXor,
}
}
}
| 32 | 169 | 0.585938 | [
"MIT"
] | Microsoft/LLVMSharp | sources/LLVMSharp/Values/Users/Instructions/Instruction.BinaryOps.cs | 1,024 | C# |
namespace GlobalConstants
{
public class CommonConstants
{
public const int DEFAULT_PAGE_SIZE = 10;
public const int DEFAULT_PAGE = 1;
}
}
| 16.9 | 48 | 0.650888 | [
"Apache-2.0"
] | siderisltd/EshopPrototypeRepository | Eshop/GlobalConstants/CommonConstants.cs | 171 | C# |
namespace Whiskey_Tycoon.lib.Marketing.Base
{
public abstract class BaseMarketing
{
public abstract string Name { get; }
public abstract uint Impact { get; }
public abstract uint QuartersLength { get; }
public abstract ulong QuarterCost { get; }
}
} | 22.846154 | 52 | 0.649832 | [
"MIT"
] | jcapellman/Whiskey-Tycoon | src/Whiskey-Tycoon.lib/Marketing/Base/BaseMarketing.cs | 299 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEngine;
namespace LMirman.VespaIO
{
public static class DevConsole
{
/// <summary>
/// Whether the console is currently enabled and open.
/// </summary>
public static bool ConsoleActive { get; internal set; }
/// <summary>
/// Whether the console is allowed to be opened or utilized.
/// </summary>
public static bool ConsoleEnabled { get; set; }
/// <summary>
/// True when the user has enabled cheats, false if they have not yet.
/// </summary>
/// <remarks>By default cheats can not be disabled at any point during an active session. Therefore to prevent players exploting the cheat commands you can check for cheats enabled to prevent saving game data to disk, granting achievements, sending telemetry data, etc.</remarks>
public static bool CheatsEnabled { get; internal set; }
internal static StringBuilder output = new StringBuilder();
/// <summary>
/// Invoked when something is logged into the console output or if it is cleared.
/// </summary>
internal static event Action OutputUpdate = delegate { };
internal static LinkedList<string> recentCommands = new LinkedList<string>();
public static void ProcessCommand(string submitText)
{
// Add the command to history if it was not the most recent command sent.
if ((recentCommands.Count <= 0 || !recentCommands.First.Value.Equals(submitText)) && !string.IsNullOrWhiteSpace(submitText))
{
recentCommands.AddFirst(submitText);
}
// Restrict list to certain capacity
while (recentCommands.Count > 0 && recentCommands.Count > ConsoleSettings.Config.commandHistoryCapacity)
{
recentCommands.RemoveLast();
}
if (!ConsoleEnabled)
{
Log("<color=red>Error:</color> Console is not enabled.");
return;
}
// Parse input into useful variables
if (!TryParseCommand(submitText, out string commandName, out object[] args, out LongString longString))
{
Log("<color=red>Error:</color> Bad command syntax");
return;
}
// Find the command in the Commands lookup table
if (!Commands.Lookup.TryGetValue(commandName, out Command command))
{
Log($"<color=red>Error:</color> Unrecognized command \"{commandName}\"");
return;
}
#if UNITY_EDITOR
// Automatically enable cheats if configured to do so in the config, making quick debugging more convenient when enabled.
if (command.Cheat && !CheatsEnabled && ConsoleSettings.Config.editorAutoEnableCheats)
{
Log("<color=yellow>Cheats have automatically been enabled.</color>");
CheatsEnabled = true;
}
#endif
// Test the command found that it can be executed if it is a cheat
if (command.Cheat && !CheatsEnabled)
{
Log("<color=red>Error:</color> Command provided can only be used when cheats are enabled");
return;
}
// Filter out methods in the command that have more required parameters than the user has input
List<MethodInfo> validMethods = new List<MethodInfo>();
for (int i = 0; i < command.Methods.Count; i++)
{
MethodInfo method = command.Methods[i];
ParameterInfo[] parameters = method.GetParameters();
int requiredParams = 0;
for (int j = 0; j < parameters.Length; j++)
{
if (!parameters[j].IsOptional)
{
requiredParams++;
}
}
if (args.Length >= requiredParams)
{
validMethods.Add(method);
}
}
// Exit if no methods are valid for the parameters provided by the user
if (validMethods.Count <= 0)
{
if (args.Length > 0)
{
Log("<color=red>Error:</color> Not enough arguments provided for command");
}
LogCommandHelp(command);
return;
}
// Get the best method from the arguments
// The best method is the one with all parameters of the same type and the most parameters matched
MethodInfo longStringMethod = null;
MethodInfo bestMethod = null;
int bestMethodArgCount = -1;
for (int i = 0; i < validMethods.Count; i++)
{
MethodInfo method = validMethods[i];
ParameterInfo[] parameters = method.GetParameters();
bool canCastAll = true;
for (int j = 0; j < parameters.Length && j < args.Length; j++)
{
if (parameters[j].ParameterType != args[j].GetType())
{
if (parameters[j].ParameterType == typeof(float) && args[j].GetType() == typeof(int))
{
// Since an int argument can be implictly converted to a float we do so here to ensure a method looking for it can use it.
int intObject = (int)args[j];
args[j] = (float)intObject;
}
else
{
canCastAll = false;
}
}
}
if (canCastAll && parameters.Length > bestMethodArgCount)
{
bestMethod = method;
bestMethodArgCount = parameters.Length;
}
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(LongString))
{
longStringMethod = method;
}
}
// Execute the best method found in the previous step, if one is found
if (longStringMethod != null && !string.IsNullOrWhiteSpace(longString) && (bestMethod == null || bestMethodArgCount == 0))
{
longStringMethod.Invoke(null, new object[] { longString });
}
else if (bestMethod != null)
{
if (args.Length < bestMethodArgCount)
{
object[] newArgs = new object[bestMethodArgCount];
ParameterInfo[] parameters = bestMethod.GetParameters();
for (int i = 0; i < bestMethodArgCount; i++)
{
newArgs[i] = i < args.Length ? args[i] : parameters[i].DefaultValue;
}
args = newArgs;
}
else if (args.Length > bestMethodArgCount)
{
object[] newArgs = new object[bestMethodArgCount];
for (int i = 0; i < bestMethodArgCount; i++)
{
newArgs[i] = args[i];
}
args = newArgs;
}
bestMethod.Invoke(null, args);
}
// No methods support the user input parameters.
else
{
Log("<color=red>Error:</color> Invalid arguments provided for command");
LogCommandHelp(command);
return;
}
}
/// <summary>
/// Parse the user input into convenient variables for the console to handle.
/// </summary>
/// <param name="input">The user input to parse</param>
/// <param name="commandName">The name of the command that the user has input</param>
/// <param name="args">None to many long array of the arguments provided by the user.</param>
/// <param name="longString">All parameters provided by the user in a single spaced string.</param>
/// <remarks>All output variables will be null if the parsing failed.</remarks>
/// <returns>True if the input was parsed properly, false if the parsing failed.</returns>
private static bool TryParseCommand(string input, out string commandName, out object[] args, out LongString longString)
{
try
{
string[] splitInput = input.Split(' ');
commandName = splitInput[0].ToLower();
List<object> foundArgs = new List<object>();
for (int i = 1; i < splitInput.Length; i++)
{
if (!string.IsNullOrWhiteSpace(splitInput[i]))
{
foundArgs.Add(ParseObject(splitInput[i]));
}
}
args = foundArgs.ToArray();
longString = foundArgs.Count > 0 ? (LongString)input.Remove(0, commandName.Length + 1) : (LongString)string.Empty;
return true;
}
catch
{
args = null;
commandName = null;
longString = null;
return false;
}
}
private static object ParseObject(string arg) => int.TryParse(arg, out int intValue) ? (object)intValue : float.TryParse(arg, out float floatValue) ? (object)floatValue : (object)arg;
[RuntimeInitializeOnLoadMethod]
private static void CreateConsole()
{
PrintWelcome();
#if UNITY_EDITOR
ConsoleEnabled = ConsoleSettings.Config.defaultConsoleEnableEditor;
#else
ConsoleEnabled = ConsoleSettings.Config.defaultConsoleEnableStandalone;
#endif
if (ConsoleSettings.Config.preloadType == PreloadType.RuntimeStart)
{
Commands.PreloadLookup();
}
if (ConsoleSettings.Config.instantiateConsoleOnLoad)
{
GameObject original = Resources.Load<GameObject>(ConsoleSettings.Config.consoleResourcePath);
if (original != null)
{
UnityEngine.Object.Instantiate(original, Vector3.zero, Quaternion.identity);
}
else
{
Debug.LogError($"Unable to instantiate console prefab from \"{ConsoleSettings.Config.consoleResourcePath}\". Please ensure that a prefab exists at this path.");
}
}
}
/// <summary>
/// Clear the output of the console.
/// </summary>
public static void Clear()
{
output.Clear();
OutputUpdate.Invoke();
}
/// <summary>
/// Log a message to the console.
/// </summary>
/// <param name="message">The message to log to the console.</param>
/// <param name="startWithNewLine">When true start a new line before logging the message.</param>
public static void Log(string message, bool startWithNewLine = true)
{
if (startWithNewLine)
{
output.AppendLine();
}
output.Append(message);
OutputUpdate.Invoke();
}
public static void LogCommandHelp(Command command)
{
Log($"{command.Key} \"{command.Name}\"\n{command.Guide}");
}
/// <summary>
/// Log the <see cref="ConsoleSettingsConfig.welcomeText"/> to the <see cref="DevConsole"/>
/// </summary>
public static void PrintWelcome()
{
Log(ConsoleSettings.Config.welcomeText);
if (ConsoleSettings.Config.printMetadataOnWelcome)
{
Log($"Version: {Application.version} {(Application.genuine ? "" : "[MODIFIED]")}\nUnity Version: {Application.unityVersion}\nPlatform: {Application.platform}");
}
}
public enum PreloadType
{
None, ConsoleOpen, ConsoleStart, RuntimeStart
}
}
} | 31.440129 | 281 | 0.671745 | [
"MIT"
] | Orange-Panda/VespaIO | Runtime/DevConsole.cs | 9,717 | C# |
/*
This code is derived from jgit (http://eclipse.org/jgit).
Copyright owners are documented in jgit's IP log.
This program and the accompanying materials are made available
under the terms of the Eclipse Distribution License v1.0 which
accompanies this distribution, is reproduced below, and is
available at http://www.eclipse.org/org/documents/edl-v10.php
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
- Neither the name of the Eclipse Foundation, Inc. nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using NGit;
using NGit.Revwalk;
using Sharpen;
namespace NGit.Revwalk
{
/// <summary>
/// Application level mark bit for
/// <see cref="RevObject">RevObject</see>
/// s.
/// <p>
/// To create a flag use
/// <see cref="RevWalk.NewFlag(string)">RevWalk.NewFlag(string)</see>
/// .
/// </summary>
public class RevFlag
{
/// <summary>
/// Uninteresting by
/// <see cref="RevWalk.MarkUninteresting(RevCommit)">RevWalk.MarkUninteresting(RevCommit)
/// </see>
/// .
/// <p>
/// We flag commits as uninteresting if the caller does not want commits
/// reachable from a commit to
/// <see cref="RevWalk.MarkUninteresting(RevCommit)">RevWalk.MarkUninteresting(RevCommit)
/// </see>
/// .
/// This flag is always carried into the commit's parents and is a key part
/// of the "rev-list B --not A" feature; A is marked UNINTERESTING.
/// <p>
/// This is a static flag. Its RevWalk is not available.
/// </summary>
public static readonly NGit.Revwalk.RevFlag UNINTERESTING = new RevFlag.StaticRevFlag
("UNINTERESTING", RevWalk.UNINTERESTING);
internal readonly RevWalk walker;
internal readonly string name;
internal readonly int mask;
internal RevFlag(RevWalk w, string n, int m)
{
walker = w;
name = n;
mask = m;
}
/// <summary>Get the revision walk instance this flag was created from.</summary>
/// <remarks>Get the revision walk instance this flag was created from.</remarks>
/// <returns>the walker this flag was allocated out of, and belongs to.</returns>
public virtual RevWalk GetRevWalk()
{
return walker;
}
public override string ToString()
{
return name;
}
internal class StaticRevFlag : RevFlag
{
internal StaticRevFlag(string n, int m) : base(null, n, m)
{
}
public override RevWalk GetRevWalk()
{
throw new NotSupportedException(MessageFormat.Format(JGitText.Get().isAStaticFlagAndHasNorevWalkInstance
, ToString()));
}
}
}
}
| 31.504132 | 108 | 0.737671 | [
"BSD-3-Clause"
] | ashmind/ngit | NGit/NGit.Revwalk/RevFlag.cs | 3,812 | C# |
namespace SkySwordKill.Next.Mod
{
public enum ModState
{
Unload,
Disable,
Loading,
LoadSuccess,
LoadFail
}
} | 14.636364 | 32 | 0.52795 | [
"MIT"
] | magicskysword/Next | Next/Scr/Mod/ModState.cs | 163 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GridGraphics
{
public partial class MainForm : Form
{
private readonly Grid grid = new Grid();
public MainForm()
{
InitializeComponent();
grid.AnchorX.AsCoef = true;
grid.AnchorY.AsCoef = true;
grid.AnchorGridX.AsCoef = true;
grid.AnchorGridY.AsCoef = true;
}
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
var di = Convert.ToInt32(e.KeyCode == Keys.Left) - Convert.ToInt32(e.KeyCode == Keys.Right);
var shiftX = grid.AnchorGridX.Shift;
grid.AnchorGridX.ShiftCells(di);
if (!grid.AnchorGridX.InBorder())
grid.AnchorGridX.Shift = shiftX;
var dj = Convert.ToInt32(e.KeyCode == Keys.Up) - Convert.ToInt32(e.KeyCode == Keys.Down);
var shiftY = grid.AnchorGridY.Shift;
grid.AnchorGridY.ShiftCells(dj);
if (!grid.AnchorGridY.InBorder())
grid.AnchorGridY.Shift = shiftY;
Invalidate();
}
private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Close();
if (e.KeyCode == Keys.Enter)
{
grid.MoveToCenter();
grid.ScaleToFit();
Invalidate();
}
}
private void MainForm_Paint(object sender, PaintEventArgs e)
{
grid.Draw(e.Graphics);
}
private void MainForm_Resize(object sender, EventArgs e)
{
grid.AnchorX.Size = ClientSize.Width;
grid.AnchorY.Size = ClientSize.Height;
}
private Point mouseLocation;
private void MainForm_MouseDown(object sender, MouseEventArgs e)
{
mouseLocation = e.Location;
}
private void MainForm_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
var shiftX = grid.AnchorX.Shift;
grid.AnchorX.Shift += e.X - mouseLocation.X;
if (!grid.AnchorGridX.InBorder())
grid.AnchorX.Shift = shiftX;
var shiftY = grid.AnchorY.Shift;
grid.AnchorY.Shift += e.Y - mouseLocation.Y;
if (!grid.AnchorGridY.InBorder())
grid.AnchorY.Shift = shiftY;
mouseLocation = e.Location;
Invalidate();
}
private void MainForm_MouseWheel(object sender, MouseEventArgs e)
{
const int WHEEL_DELTA = 120; // TODO: How get it from system?
var delta = e.Delta / WHEEL_DELTA;
var stepX = grid.AnchorGridX.Step;
var stepY = grid.AnchorGridY.Step;
grid.AnchorGridX.Step = Math.Max(1, grid.AnchorGridX.Step - delta);
grid.AnchorGridY.Step = Math.Max(1, grid.AnchorGridY.Step - delta);
if (!grid.AnchorGridX.InBorder() || !grid.AnchorGridY.InBorder())
{
grid.AnchorGridX.Step = stepX;
grid.AnchorGridY.Step = stepY;
}
Invalidate();
}
}
}
| 29.827273 | 104 | 0.54648 | [
"Unlicense"
] | Ring-r/GridGraphics | GridGraphics/MainForm.cs | 3,283 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace KoS.Apps.SharePoint.SmartCAML.Editor.BindingConverters
{
public class BooleanConverter<T> : IValueConverter
{
public BooleanConverter() {}
public BooleanConverter(T trueValue, T falseValue)
{
True = trueValue;
False = falseValue;
}
public T True { get; set; }
public T False { get; set; }
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is bool && ((bool)value) ? True : False;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is T && EqualityComparer<T>.Default.Equals((T)value, True);
}
}
public sealed class BoolToVisibilityConverter : BooleanConverter<Visibility>
{
public BoolToVisibilityConverter() :
base(Visibility.Visible, Visibility.Collapsed)
{ }
}
public sealed class InvertBoolConverter : BooleanConverter<bool>
{
public InvertBoolConverter() :
base(false, true)
{ }
}
public sealed class BoolToStringConverter : BooleanConverter<string>
{
}
} | 27.74 | 111 | 0.63951 | [
"Apache-2.0"
] | konradsikorski/smartCAML | KoS.Apps.SharePoint.SmartCAML/KoS.Apps.SharePoint.SmartCAML.Editor/BindingConverters/BooleanConverter.cs | 1,389 | C# |
using Entitas;
using Entitas.CodeGeneration.Attributes;
namespace _1010C.Scripts.Components.Piece
{
[Game, FlagPrefix("flag"), Event(EventTarget.Self), Event(EventTarget.Self, EventType.Removed)]
public class DragComponent : IComponent
{
}
} | 25.9 | 99 | 0.745174 | [
"MIT"
] | ahmetayrnc/1010C | Assets/1010C/Scripts/Components/Piece/DragComponent.cs | 261 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using TestApp.Models;
namespace TestApp.Providers
{
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}
return Task.FromResult<object>(null);
}
public static AuthenticationProperties CreateProperties(string userName)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName }
};
return new AuthenticationProperties(data);
}
}
} | 34.989796 | 115 | 0.641586 | [
"MIT"
] | nmug/Workshop-Angular2AndDotNetCore-12-2016 | Prep/TestApp/Providers/ApplicationOAuthProvider.cs | 3,431 | C# |
using BonusBot.Common.Extensions;
using BonusBot.Common.Interfaces.Commands;
using BonusBot.Common.Interfaces.Guilds;
using BonusBot.LoggingModule.Language;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Threading.Tasks;
namespace BonusBot.LoggingModule.EventHandlers
{
internal class WebCommandExecuted
{
private readonly IGuildsHandler _guildsHandler;
public WebCommandExecuted(IGuildsHandler guildsHandler)
=> _guildsHandler = guildsHandler;
internal async Task Log(Optional<CommandInfo> _1, ICommandContext context, IResult _2)
{
if (context is not ICustomCommandContext { IsWeb: true } webContext)
return;
if (IsCommandToIgnore(webContext.Message.Content))
return;
var bonusGuild = _guildsHandler.GetGuild(webContext.Guild.Id);
if (bonusGuild is null) return;
var channel = await bonusGuild.Settings.Get<SocketTextChannel>(GetType().Assembly, Settings.WebCommandExecutedChannel);
if (channel is null) return;
await channel.SendMessageAsync(string.Format(ModuleTexts.WebCommandExecutedInfo, GetUserName(webContext), context.Message.Content));
}
private string GetUserName(ICustomCommandContext context)
{
if (context.GuildUser is { } guildUser)
return guildUser.GetFullNameInfo();
return context.User.Username + "#" + context.User.Discriminator;
}
private bool IsCommandToIgnore(string command)
=> command switch
{
string s when s.StartsWith("GetState", System.StringComparison.OrdinalIgnoreCase) => true,
_ => false
};
}
}
| 35.74 | 144 | 0.668719 | [
"MIT"
] | emre1702/BonusBo | Modules/LoggingModule/EventHandlers/WebCommandExecuted.cs | 1,789 | C# |
using System;
using System.Diagnostics;
using J = Newtonsoft.Json.JsonPropertyAttribute;
namespace Fortnite_API.Objects.V1
{
[DebuggerDisplay("{" + nameof(Score) + "}")]
public class BrStatsV2V1LtmStats : IEquatable<BrStatsV2V1LtmStats>
{
[J] public long Score { get; private set; }
[J] public double ScorePerMin { get; private set; }
[J] public double ScorePerMatch { get; private set; }
[J] public long Wins { get; private set; }
[J] public long Kills { get; private set; }
[J] public double KillsPerMin { get; private set; }
[J] public double KillsPerMatch { get; private set; }
[J] public long Deaths { get; private set; }
[J] public double Kd { get; private set; }
[J] public long Matches { get; private set; }
[J] public double WinRate { get; private set; }
[J] public long MinutesPlayed { get; private set; }
[J] public long PlayersOutlived { get; private set; }
[J] public DateTime LastModified { get; private set; }
public bool Equals(BrStatsV2V1LtmStats other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Score == other.Score && Wins == other.Wins && Kills == other.Kills && Matches == other.Matches && LastModified.Equals(other.LastModified);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((BrStatsV2V1LtmStats)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Score.GetHashCode();
hashCode = hashCode * 397 ^ Wins.GetHashCode();
hashCode = hashCode * 397 ^ Kills.GetHashCode();
hashCode = hashCode * 397 ^ Matches.GetHashCode();
hashCode = hashCode * 397 ^ LastModified.GetHashCode();
return hashCode;
}
}
public static bool operator ==(BrStatsV2V1LtmStats left, BrStatsV2V1LtmStats right)
{
return Equals(left, right);
}
public static bool operator !=(BrStatsV2V1LtmStats left, BrStatsV2V1LtmStats right)
{
return !Equals(left, right);
}
}
} | 26.047619 | 148 | 0.665905 | [
"MIT"
] | Fortnite-API/csharp-wrapper | src/Fortnite-API/Objects/V1/BrStatsV2V1LtmStats.cs | 2,190 | C# |
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using PS.Build.Extensions;
using PS.Build.Services;
using PS.Build.Types;
namespace PS.Build.Essentials.Attributes
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[Designer("PS.Build.Adaptation")]
public class FilesEmbedAttribute : FilesBaseAttribute
{
#region Constructors
public FilesEmbedAttribute(string selectPattern, params string[] filterPatterns) :
base(selectPattern, filterPatterns)
{
BuildStep = BuildStep.PreBuild;
}
#endregion
#region Properties
public string NamePrefix { get; set; }
#endregion
#region Override members
protected override void Process(RecursivePath[] files, IServiceProvider provider)
{
var logger = provider.GetService<ILogger>();
if (BuildStep.HasFlag(BuildStep.PostBuild))
{
logger.Error("Files could not be embedded on PostBuild event");
return;
}
var macroResolver = provider.GetService<IMacroResolver>();
var artifactory = provider.GetService<IArtifactory>();
var namePrefix = macroResolver.Resolve(NamePrefix ?? string.Empty);
logger.Info(files.Any() ? $"There is {files.Length} files to embed:" : "There is no files to embed");
foreach (var file in files)
{
logger.Info($"* Embed: {file.Original}");
var artifact = artifactory.Artifact(file.Original, BuildItem.EmbeddedResource)
.Permanent();
if (!string.IsNullOrWhiteSpace(namePrefix) && file.Recursive != null)
{
var link = Path.Combine(namePrefix, file.Recursive, file.Postfix);
using (logger.IndentMessages())
{
logger.Debug($"- Link: {link}");
}
artifact.Metadata("Link", link);
}
artifact.Dependencies().FileDependency(file.Original);
}
}
#endregion
}
} | 31.492958 | 113 | 0.571556 | [
"MIT"
] | BlackGad/PS.Build | PS.Build.Essentials/Attributes/Files/FilesEmbedAttribute.cs | 2,236 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Network.Models
{
public partial class P2SVpnConnectionHealthRequest : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsCollectionDefined(VpnUserNamesFilter))
{
writer.WritePropertyName("vpnUserNamesFilter");
writer.WriteStartArray();
foreach (var item in VpnUserNamesFilter)
{
writer.WriteStringValue(item);
}
writer.WriteEndArray();
}
if (Optional.IsDefined(OutputBlobSasUrl))
{
writer.WritePropertyName("outputBlobSasUrl");
writer.WriteStringValue(OutputBlobSasUrl);
}
writer.WriteEndObject();
}
}
}
| 28.918919 | 78 | 0.594393 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Models/P2SVpnConnectionHealthRequest.Serialization.cs | 1,070 | C# |
#pragma checksum "..\..\MainPage.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "45DCDC8D4427BA181FE43860FC4F0640F4FAF314"
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
using KeepWastes.ViewModel;
using MaterialDesignThemes.Wpf;
using MaterialDesignThemes.Wpf.Transitions;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace KeepWastes {
/// <summary>
/// MainPage
/// </summary>
public partial class MainPage : System.Windows.Window, System.Windows.Markup.IComponentConnector {
#line 435 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Grid GridMain;
#line default
#line hidden
#line 451 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Main;
#line default
#line hidden
#line 463 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Stats;
#line default
#line hidden
#line 476 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Goals;
#line default
#line hidden
#line 493 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Shapes.Rectangle RectangleSearch;
#line default
#line hidden
#line 533 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Border Border2;
#line default
#line hidden
#line 534 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Primitives.Popup PopupTag;
#line default
#line hidden
#line 589 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button AddTag;
#line default
#line hidden
#line 600 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button AddNewWaste;
#line default
#line hidden
#line 616 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Logout;
#line default
#line hidden
#line 635 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Border Border;
#line default
#line hidden
#line 646 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Primitives.Popup Popup;
#line default
#line hidden
#line 661 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Shapes.Rectangle Rectangle1;
#line default
#line hidden
#line 662 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBox Sum;
#line default
#line hidden
#line 674 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBox ComboBox;
#line default
#line hidden
#line 680 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem None;
#line default
#line hidden
#line 707 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Vehicles;
#line default
#line hidden
#line 726 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Food;
#line default
#line hidden
#line 745 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Clothes;
#line default
#line hidden
#line 764 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Travelling;
#line default
#line hidden
#line 783 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Cafes;
#line default
#line hidden
#line 802 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Entertainment;
#line default
#line hidden
#line 821 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Medicine;
#line default
#line hidden
#line 840 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Gadgets;
#line default
#line hidden
#line 859 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Cinema;
#line default
#line hidden
#line 878 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Subscriptions;
#line default
#line hidden
#line 897 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ComboBoxItem Other;
#line default
#line hidden
#line 917 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.DatePicker Calendar;
#line default
#line hidden
#line 939 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Shapes.Rectangle Rectangle3;
#line default
#line hidden
#line 940 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.TextBox Description;
#line default
#line hidden
#line 950 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.Button Save;
#line default
#line hidden
#line 983 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Shapes.Rectangle rectangle;
#line default
#line hidden
#line 992 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ListView listView;
#line default
#line hidden
#line 1003 "..\..\MainPage.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal System.Windows.Controls.ListViewItem listViewItem;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/KeepWastes;component/mainpage.xaml", System.UriKind.Relative);
#line 1 "..\..\MainPage.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.GridMain = ((System.Windows.Controls.Grid)(target));
return;
case 2:
this.Main = ((System.Windows.Controls.Button)(target));
#line 462 "..\..\MainPage.xaml"
this.Main.Click += new System.Windows.RoutedEventHandler(this.Main_Click);
#line default
#line hidden
return;
case 3:
this.Stats = ((System.Windows.Controls.Button)(target));
#line 475 "..\..\MainPage.xaml"
this.Stats.Click += new System.Windows.RoutedEventHandler(this.Stats_Click);
#line default
#line hidden
return;
case 4:
this.Goals = ((System.Windows.Controls.Button)(target));
#line 489 "..\..\MainPage.xaml"
this.Goals.Click += new System.Windows.RoutedEventHandler(this.Goals_Click);
#line default
#line hidden
return;
case 5:
this.RectangleSearch = ((System.Windows.Shapes.Rectangle)(target));
return;
case 6:
this.Border2 = ((System.Windows.Controls.Border)(target));
return;
case 7:
this.PopupTag = ((System.Windows.Controls.Primitives.Popup)(target));
return;
case 8:
#line 553 "..\..\MainPage.xaml"
((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Click);
#line default
#line hidden
return;
case 9:
this.AddTag = ((System.Windows.Controls.Button)(target));
#line 597 "..\..\MainPage.xaml"
this.AddTag.Click += new System.Windows.RoutedEventHandler(this.AddTag_Click);
#line default
#line hidden
return;
case 10:
this.AddNewWaste = ((System.Windows.Controls.Button)(target));
#line 611 "..\..\MainPage.xaml"
this.AddNewWaste.Click += new System.Windows.RoutedEventHandler(this.AddNew_Click);
#line default
#line hidden
return;
case 11:
this.Logout = ((System.Windows.Controls.Button)(target));
#line 622 "..\..\MainPage.xaml"
this.Logout.Click += new System.Windows.RoutedEventHandler(this.Logout_Click);
#line default
#line hidden
return;
case 12:
this.Border = ((System.Windows.Controls.Border)(target));
return;
case 13:
this.Popup = ((System.Windows.Controls.Primitives.Popup)(target));
return;
case 14:
this.Rectangle1 = ((System.Windows.Shapes.Rectangle)(target));
return;
case 15:
this.Sum = ((System.Windows.Controls.TextBox)(target));
#line 671 "..\..\MainPage.xaml"
this.Sum.GotFocus += new System.Windows.RoutedEventHandler(this.Sum_GotFocus);
#line default
#line hidden
#line 672 "..\..\MainPage.xaml"
this.Sum.LostFocus += new System.Windows.RoutedEventHandler(this.Sum_LostFocus);
#line default
#line hidden
#line 672 "..\..\MainPage.xaml"
this.Sum.PreviewTextInput += new System.Windows.Input.TextCompositionEventHandler(this.Sum_PreviewTextInput);
#line default
#line hidden
return;
case 16:
this.ComboBox = ((System.Windows.Controls.ComboBox)(target));
return;
case 17:
this.None = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 18:
this.Vehicles = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 19:
this.Food = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 20:
this.Clothes = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 21:
this.Travelling = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 22:
this.Cafes = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 23:
this.Entertainment = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 24:
this.Medicine = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 25:
this.Gadgets = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 26:
this.Cinema = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 27:
this.Subscriptions = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 28:
this.Other = ((System.Windows.Controls.ComboBoxItem)(target));
return;
case 29:
this.Calendar = ((System.Windows.Controls.DatePicker)(target));
return;
case 30:
this.Rectangle3 = ((System.Windows.Shapes.Rectangle)(target));
return;
case 31:
this.Description = ((System.Windows.Controls.TextBox)(target));
#line 949 "..\..\MainPage.xaml"
this.Description.GotFocus += new System.Windows.RoutedEventHandler(this.Description_GotFocus);
#line default
#line hidden
#line 949 "..\..\MainPage.xaml"
this.Description.LostFocus += new System.Windows.RoutedEventHandler(this.Description_LostFocus);
#line default
#line hidden
return;
case 32:
this.Save = ((System.Windows.Controls.Button)(target));
#line 959 "..\..\MainPage.xaml"
this.Save.Click += new System.Windows.RoutedEventHandler(this.Save_Click);
#line default
#line hidden
return;
case 33:
#line 975 "..\..\MainPage.xaml"
((System.Windows.Controls.Button)(target)).Click += new System.Windows.RoutedEventHandler(this.Button_Click_1);
#line default
#line hidden
return;
case 34:
this.rectangle = ((System.Windows.Shapes.Rectangle)(target));
return;
case 35:
this.listView = ((System.Windows.Controls.ListView)(target));
return;
case 36:
this.listViewItem = ((System.Windows.Controls.ListViewItem)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 37.440147 | 141 | 0.595819 | [
"MIT"
] | FloydReme/KeepWastes | KeepWastes/obj/Release/MainPage.g.cs | 20,466 | C# |
using Dapper;
using Frapper.ViewModel.Customers;
using System.Data;
namespace Frapper.Repository.Customers.Command
{
public class CustomersCommand : ICustomersCommand
{
private readonly IDbConnection _dbConnection;
private readonly IDbTransaction _dbTransaction;
public CustomersCommand(IDbTransaction dbTransaction, IDbConnection dbConnection)
{
_dbConnection = dbConnection;
_dbTransaction = dbTransaction;
}
public void Add(CustomersViewModel customersViewModel, long userId)
{
var param = new DynamicParameters();
param.Add("@FirstName", customersViewModel.FirstName);
param.Add("@LastName", customersViewModel.LastName);
param.Add("@MobileNo", customersViewModel.MobileNo);
param.Add("@LandlineNo", customersViewModel.LandlineNo);
param.Add("@EmailId", customersViewModel.EmailId);
param.Add("@Street", customersViewModel.Street);
param.Add("@City", customersViewModel.City);
param.Add("@State", customersViewModel.State);
param.Add("@Pincode", customersViewModel.Pincode);
param.Add("@CreatedBy", userId);
_dbConnection.Execute("Usp_InsertCustomer", param, _dbTransaction, 0, CommandType.StoredProcedure);
}
}
} | 40.147059 | 111 | 0.665201 | [
"MIT"
] | Ramasagar/Frapper | Frapper.Web/Frapper.Repository/Customers/Command/CustomersCommand.cs | 1,367 | C# |
using Terraria;
using Terraria.Localization;
using Terraria.DataStructures;
using Terraria.ModLoader;
namespace PrismaticRivals.Debug
{
class CommandSpawnNPC : ModCommand
{
public override string Command => "spawnprismnpc";
public override CommandType Type => CommandType.World;
public override void Action(CommandCaller caller, string input, string[] args)
{
if (caller.Player != null)
{
caller.Player.KillMe(PlayerDeathReason.ByCustomReason("Oops! This command isn't finished."), 100, 0);
if (args.Length == 1)
{
string a0 = args[0];
}
else
{
caller.Reply("Command expects 1 argument", Microsoft.Xna.Framework.Color.Red);
}
}
}
}
}
| 29.290323 | 118 | 0.535242 | [
"MIT"
] | Solid-Wires/terrariamod-prismaticrivals | Debug/CommandSpawnNPC.cs | 910 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MtFract.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 40.148148 | 152 | 0.564576 | [
"MIT"
] | centennialcoder/MtFrac | MtFract/Properties/Settings.Designer.cs | 1,086 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for FeaturesOperations.
/// </summary>
public static partial class FeaturesOperationsExtensions
{
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> ListAll(this IFeaturesOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListAllAsync(this IFeaturesOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> List(this IFeaturesOperations operations, string resourceProviderNamespace)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAsync(resourceProviderNamespace), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListAsync(this IFeaturesOperations operations, string resourceProviderNamespace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceProviderNamespace, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get all features under the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
public static FeatureResult Get(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).GetAsync(resourceProviderNamespace, featureName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all features under the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FeatureResult> GetAsync(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Registers for a previewed feature of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
public static FeatureResult Register(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).RegisterAsync(resourceProviderNamespace, featureName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Registers for a previewed feature of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Previewed feature name in the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FeatureResult> RegisterAsync(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.RegisterWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> ListAllNext(this IFeaturesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features for all the providers in the current
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListAllNextAsync(this IFeaturesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<FeatureResult> ListNext(this IFeaturesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<FeatureResult>> ListNextAsync(this IFeaturesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 52.885593 | 335 | 0.608525 | [
"MIT"
] | DiogenesPolanco/azure-sdk-for-net | src/ResourceManagement/Resource/Microsoft.Azure.Management.ResourceManager/Generated/FeaturesOperationsExtensions.cs | 12,481 | C# |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
namespace Bodies.Stars
{
public enum ESpectralType
{
UNKNOWN = 0, O3, O5, O8, B0, B3, B5, B8, A0, A5, F0, F5, G0, G2, G5, K0, K5, M0, M5, M8, M9, L0, L2, L5, T0, T5, T8
};
public enum ELuminosityType
{
UNKNOWN = 0, MAIN_SEQUENCE_STAR, GIANT_STAR, SUPERGIANT_STAR, BROWN_DWARF, RED_DWARF, WHITE_DWARF, BLACK_HOLE, SUPERMASSIVE_BLACK_HOLE
};
public class StarFactory : MonoBehaviour
{
private int Seed;
private Dictionary<KeyValuePair<int, int>, StarGenerationRange> StarGenRanges = new Dictionary<KeyValuePair<int, int>, StarGenerationRange>();
private List<string> StarNamesBase = new List<string>();
private List<string> UsedStarNames = new List<string>();
public static string ELuminosityTypeToString(int type)
{
switch ((ELuminosityType)type)
{
case ELuminosityType.MAIN_SEQUENCE_STAR:
return "V (MAIN SEQUENCE STAR)";
case ELuminosityType.GIANT_STAR:
return "III (GIANT STAR)";
case ELuminosityType.SUPERGIANT_STAR:
return "I (SUPERGIANT STAR)";
case ELuminosityType.BROWN_DWARF:
return "(BROWN DWARF)";
case ELuminosityType.RED_DWARF:
return "(RED DWARF)";
case ELuminosityType.WHITE_DWARF:
return "(WHITE DWARF)";
case ELuminosityType.BLACK_HOLE:
return "(BLACK HOLE)";
case ELuminosityType.SUPERMASSIVE_BLACK_HOLE:
return "(SUPERMASSIVE BLACK HOLE)";
default:
return "UNKNOWN";
}
}
public static string ESpectralTypeToString(int type)
{
switch ((ESpectralType)type)
{
case ESpectralType.O3:
return "O3";
case ESpectralType.O5:
return "O5";
case ESpectralType.O8:
return "O8";
case ESpectralType.B0:
return "B0";
case ESpectralType.B3:
return "B3";
case ESpectralType.B5:
return "B5";
case ESpectralType.B8:
return "B8";
case ESpectralType.A0:
return "A0";
case ESpectralType.A5:
return "A5";
case ESpectralType.F0:
return "F0";
case ESpectralType.F5:
return "F5";
case ESpectralType.G0:
return "G0";
case ESpectralType.G2:
return "G2";
case ESpectralType.G5:
return "G5";
case ESpectralType.K0:
return "K0";
case ESpectralType.K5:
return "K5";
case ESpectralType.M0:
return "M0";
case ESpectralType.M5:
return "M5";
case ESpectralType.M8:
return "M8";
case ESpectralType.M9:
return "M9";
case ESpectralType.L0:
return "L0";
case ESpectralType.L2:
return "L2";
case ESpectralType.L5:
return "L5";
case ESpectralType.T0:
return "T0";
case ESpectralType.T5:
return "T5";
case ESpectralType.T8:
return "T8";
default:
return "UNKNOWN";
}
}
void Start()
{
}
public void InitStarFactory(int seed)
{
this.Seed = seed;
LoadGenerationRangesFromFile("StarRanges");
LoadStarNamesFromFile("StarNames");
}
private void LoadGenerationRangesFromFile(string file)
{
TextAsset textAss = Resources.Load(file) as TextAsset;
string[] fileLines = textAss.text.Split('}');
//new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries
foreach (string s in fileLines)
{
if (s == string.Empty || s == "\n")
continue;
string sp = FixJSONline(s);
try
{
StarGenerationRange range = JsonUtility.FromJson<StarGenerationRange>(sp);
StarGenRanges.Add(new KeyValuePair<int, int>(range.SpectralType, range.LuminosityType), range);
}
catch
{
Debug.Log("error");
}
}
}
private void LoadStarNamesFromFile(string file)
{
TextAsset textAss = Resources.Load(file) as TextAsset;
string[] fileLines = textAss.text.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in fileLines)
{
if (s == string.Empty)
continue;
StarNamesBase.Add(s);
}
}
public static string FixJSONline(string s)
{
string sp = s + '}';
sp = Regex.Replace(sp, @"\s+", string.Empty);
Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", '[', ']')); // comments are in []
sp = regex.Replace(sp, string.Empty);
return sp;
}
public Star GenerateStar()
{
Seed = GalaxyFactory.Seed;
RandomGenerator.SetSeed(Seed);
Star s = new Star();
//s.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
//s.SpectralType = (int)ESpectralType.O3;
GenerateLuminosityType(ref s);
GenerateStarData(ref s);
return s;
}
private bool GenerateStarData(ref Star star)
{
if (StarGenRanges.ContainsKey(new KeyValuePair<int, int>(star.SpectralType, star.LuminosityType)))
{
StarGenerationRange range = StarGenRanges[new KeyValuePair<int, int>(star.SpectralType, star.LuminosityType)];
star.MassSuns = RandomGenerator.GenerateDouble(range.SunMassesMin, range.SunMassesMax);
star.RadiusSuns = RandomGenerator.GenerateDouble(range.SunRadiusesMin, range.SunRadiusesMax);
star.LuminositySuns = RandomGenerator.GenerateDouble(range.SunLuminositiesMin, range.SunLuminositiesMax);
star.LifetimeMyears = range.LifetimeMyears;
star.HabitableZoneAU = RandomGenerator.GenerateDouble(range.HabitableZoneAUMin, range.HabitableZoneAUMax);
star.TemperatureKelvin = RandomGenerator.GenerateInt(range.TemperatureKelvinMin, range.TemperatureKelvinMax);
string sName = StarNamesBase[RandomGenerator.GenerateInt(0, StarNamesBase.Count)] + " - " + RandomGenerator.GenerateInt(0, 1000000);
if (!UsedStarNames.Contains(sName))
{
UsedStarNames.Add(sName);
star.Name = sName;
}
else
{
do
{
sName = StarNamesBase[RandomGenerator.GenerateInt(0, StarNamesBase.Count)] + " - " + RandomGenerator.GenerateInt(0, 1000000);
} while (UsedStarNames.Contains(sName));
UsedStarNames.Add(sName);
star.Name = sName;
}
return true;
}
return false;
}
private void GenerateLuminosityType(ref Star star)
{
int r1 = RandomGenerator.GenerateInt(0, 2000000000);
// Black Hole chance: 0.000000000005
if (r1 == 0)
{
star.LuminosityType = (int)ELuminosityType.BLACK_HOLE;
star.SpectralType = (int)ESpectralType.UNKNOWN;
return;
}
else
{
int r = RandomGenerator.GenerateInt(0, 100000000);
// MainSpectral O Class Star chance: 0.00000001
if (r == 0)
{
star.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
int rr = RandomGenerator.GenerateInt(0, 3);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.O3;
break;
case 1:
star.SpectralType = (int)ESpectralType.O5;
break;
case 2:
star.SpectralType = (int)ESpectralType.O8;
break;
}
}
// MainSpectral B Class Star chance: 0.001
else if (r > 0 && r < 100001)
{
star.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
int rr = RandomGenerator.GenerateInt(0, 4);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.B0;
break;
case 1:
star.SpectralType = (int)ESpectralType.B3;
break;
case 2:
star.SpectralType = (int)ESpectralType.B5;
break;
case 3:
star.SpectralType = (int)ESpectralType.B8;
break;
}
}
// MainSpectral A Class Star chance: 0.007
else if (r > 100000 && r < 700001)
{
star.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
int rr = RandomGenerator.GenerateInt(0, 2);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.A0;
break;
case 1:
star.SpectralType = (int)ESpectralType.A5;
break;
}
}
// MainSpectral F Class Star chance: 0.02
else if (r > 700000 && r < 2700001)
{
star.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
int rr = RandomGenerator.GenerateInt(0, 2);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.F0;
break;
case 1:
star.SpectralType = (int)ESpectralType.F5;
break;
}
}
// MainSpectral G Class Star chance: 0.035
else if (r > 2700000 && r < 6200001)
{
star.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
int rr = RandomGenerator.GenerateInt(0, 3);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.G0;
break;
case 1:
star.SpectralType = (int)ESpectralType.G2;
break;
case 2:
star.SpectralType = (int)ESpectralType.G5;
break;
}
}
// MainSpectral K Class Star chance: 0.08
else if (r > 6200000 && r < 14200001)
{
star.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
int rr = RandomGenerator.GenerateInt(0, 2);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.K0;
break;
case 1:
star.SpectralType = (int)ESpectralType.K5;
break;
}
}
// MainSpectral M Class Star chance: 0.80
else if (r > 14200000 && r < 94200001)
{
star.LuminosityType = (int)ELuminosityType.MAIN_SEQUENCE_STAR;
int rr = RandomGenerator.GenerateInt(0, 3);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.M0;
break;
case 1:
star.SpectralType = (int)ESpectralType.M5;
break;
case 2:
star.SpectralType = (int)ESpectralType.M8;
break;
}
}
// Giant Star chance: 0.01933333
else if (r > 94200000 && r < 96133334)
{
star.LuminosityType = (int)ELuminosityType.GIANT_STAR;
int rr = RandomGenerator.GenerateInt(0, 10);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.B0;
break;
case 1:
star.SpectralType = (int)ESpectralType.B5;
break;
case 2:
star.SpectralType = (int)ESpectralType.A0;
break;
case 3:
star.SpectralType = (int)ESpectralType.F0;
break;
case 4:
star.SpectralType = (int)ESpectralType.G0;
break;
case 5:
star.SpectralType = (int)ESpectralType.G5;
break;
case 6:
star.SpectralType = (int)ESpectralType.K0;
break;
case 7:
star.SpectralType = (int)ESpectralType.K5;
break;
case 8:
star.SpectralType = (int)ESpectralType.M0;
break;
case 9:
star.SpectralType = (int)ESpectralType.M5;
break;
}
}
// Super Giant Star chance: 0.01933333
else if (r > 96133333 && r < 98066667)
{
star.LuminosityType = (int)ELuminosityType.SUPERGIANT_STAR;
int rr = RandomGenerator.GenerateInt(0, 9);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.O5;
break;
case 1:
star.SpectralType = (int)ESpectralType.B0;
break;
case 2:
star.SpectralType = (int)ESpectralType.A0;
break;
case 3:
star.SpectralType = (int)ESpectralType.F0;
break;
case 4:
star.SpectralType = (int)ESpectralType.G0;
break;
case 5:
star.SpectralType = (int)ESpectralType.G5;
break;
case 6:
star.SpectralType = (int)ESpectralType.K0;
break;
case 7:
star.SpectralType = (int)ESpectralType.K5;
break;
case 8:
star.SpectralType = (int)ESpectralType.M0;
break;
}
}
// Brown Dwarf chance: 0.01933333
else if (r > 98066666)
{
star.LuminosityType = (int)ELuminosityType.BROWN_DWARF;
int rr = RandomGenerator.GenerateInt(0, 8);
switch (rr)
{
case 0:
star.SpectralType = (int)ESpectralType.M8;
break;
case 1:
star.SpectralType = (int)ESpectralType.M9;
break;
case 2:
star.SpectralType = (int)ESpectralType.L0;
break;
case 3:
star.SpectralType = (int)ESpectralType.L2;
break;
case 4:
star.SpectralType = (int)ESpectralType.L5;
break;
case 5:
star.SpectralType = (int)ESpectralType.T0;
break;
case 6:
star.SpectralType = (int)ESpectralType.T5;
break;
case 7:
star.SpectralType = (int)ESpectralType.T8;
break;
}
}
}
}
}
}
| 39.503198 | 150 | 0.418254 | [
"MIT"
] | Ultraporing/Song_of_the_Stars | Assets/_Scripts/Bodies/Stars/StarFactory.cs | 18,527 | C# |
// ------------------------------------------
// <copyright file="ECParallelOptimTest.cs" company="Pedro Sequeira">
//
// Copyright (c) 2018 Pedro Sequeira
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// </copyright>
// <summary>
// Project: Learning.EvolutionaryComputation
// Last updated: 03/10/2014
// Author: Pedro Sequeira
// E-mail: pedrodbs@gmail.com
// </summary>
// ------------------------------------------
using PS.Learning.Core.Testing.MultipleTests;
using PS.Learning.Core.Testing.StochasticOptimization;
using PS.Utilities.Math;
using System.IO;
namespace PS.Learning.EvolutionaryComputation.Testing.MultipleTests
{
public class ECParallelOptimTest : StochasticParallelOptimTest
{
#region Private Fields
private const string TEST_ID = "EvoOptimization";
#endregion Private Fields
#region Public Constructors
public ECParallelOptimTest(IOptimizationTestFactory optimizationTestFactory)
: base(optimizationTestFactory)
{
}
#endregion Public Constructors
#region Public Properties
public StatisticalQuantity RandomProportionProgressAvg { get; protected set; }
public override string TestID
{
get { return TEST_ID; }
}
#endregion Public Properties
#region Protected Properties
protected new IECTestsConfig TestsConfig
{
get { return base.TestsConfig as IECTestsConfig; }
}
#endregion Protected Properties
#region Public Methods
public override void Dispose()
{
base.Dispose();
this.RandomProportionProgressAvg.Dispose();
}
#endregion Public Methods
#region Protected Methods
protected override IStochasticOptimizationTest CreateStochasticOptimTest(uint optimTestNumber)
{
this.WriteLine(@"__________________________________________");
this.WriteLine(string.Format("Creating population {0}...", optimTestNumber));
return new ECOptimizationTest(string.Format("Population {0}", optimTestNumber),
this.TestsConfig, this.TestsConfig.CreateBaseChromosome(), this.CreateFitnessFunction());
}
protected override void PrintTestPerformanceResults()
{
base.PrintTestPerformanceResults();
this.RandomProportionProgressAvg.PrintStatisticsToCSV(
string.Format("{0}{1}RandomProportionAvg.csv", this.FilePath, Path.DirectorySeparatorChar));
}
protected override void StoreOptimTestStatistics(IStochasticOptimizationTest optimizationTest)
{
base.StoreOptimTestStatistics(optimizationTest);
lock (this.locker)
{
var ecOptimizationTest = (ECOptimizationTest)optimizationTest;
//stores or averages populations' statistics
if (this.RandomProportionProgressAvg == null)
this.RandomProportionProgressAvg = ecOptimizationTest.RandomProportionProgress;
else
this.RandomProportionProgressAvg.AverageWith(ecOptimizationTest.RandomProportionProgress);
}
}
#endregion Protected Methods
#region Private Methods
private FitnessFunction CreateFitnessFunction()
{
//create fitness function
return new FitnessFunction(this.OptimizationTestFactory, (ECTestMeasureList)this.TestMeasures)
{
LogWriter = this.LogWriter
};
}
#endregion Private Methods
}
} | 35.583333 | 119 | 0.668512 | [
"MIT"
] | pedrodbs/SocioEmotionalIMRL | PS.Learning/EvolutionaryComputation/Testing/MultipleTests/ECParallelOptimTest.cs | 4,697 | C# |
namespace Ship
{
namespace FirstEdition.YT2400
{
public class EadenVrill : YT2400
{
public EadenVrill() : base()
{
PilotInfo = new PilotCardInfo(
"Eaden Vrill",
3,
32,
isLimited: true,
abilityType: typeof(Abilities.FirstEdition.EadenVrillAbility)
);
}
}
}
}
namespace Abilities.FirstEdition
{
public class EadenVrillAbility : GenericAbility
{
public override void ActivateAbility()
{
HostShip.OnShotStartAsAttacker += CheckConditions;
}
public override void DeactivateAbility()
{
HostShip.OnShotStartAsAttacker -= CheckConditions;
}
private void CheckConditions()
{
if (Combat.Defender.Tokens.HasToken(typeof(Tokens.StressToken)))
{
HostShip.AfterGotNumberOfAttackDice += RollExtraDice;
}
}
private void RollExtraDice(ref int count)
{
count++;
Messages.ShowInfo("The defender is stressed. The attacker rolls 1 additional attack die");
HostShip.AfterGotNumberOfAttackDice -= RollExtraDice;
}
}
} | 26.46 | 102 | 0.534392 | [
"MIT"
] | 97saundersj/FlyCasual | Assets/Scripts/Model/Content/FirstEdition/Pilots/YT2400/EadenVrill.cs | 1,325 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace MessageService
{
public class ValuesController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
[HttpGet]
public string Message(int id)
{
return " message "+ id;
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
var _id = id;
Console.WriteLine(_id);
}
}
}
| 19.723404 | 55 | 0.516721 | [
"Apache-2.0"
] | foxundermoon/MessageService | MessageServer/Core/HttpApi/DefaultApiController.cs | 929 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Seguetech.Zippy.Database.Entities
{
public class Cabinet
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int UserId { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public DateTime LastUpdated { get; set; }
public virtual User User { get; set; }
public virtual ICollection<Medication> Medications { get; set; }
}
}
| 29.208333 | 72 | 0.691869 | [
"CC0-1.0"
] | seguemodev/Meducated-Ninja | Web/Zippy.Database/Entities/Cabinet.cs | 703 | C# |
namespace BinarySerialization;
/// <summary>
/// The serialization binding mode.
/// </summary>
public enum BindingMode
{
/// <summary>
/// Update the source during serialization and the target during deserialization.
/// </summary>
TwoWay,
/// <summary>
/// Only update the target during deserialization.
/// </summary>
OneWay,
/// <summary>
/// Only update the source during serialization
/// </summary>
OneWayToSource
}
| 21.347826 | 89 | 0.617108 | [
"MIT"
] | shaggygi/BinarySerializer | BinarySerializer/BindingMode.cs | 493 | C# |
using System;
namespace StaticEvil
{
public sealed class Evil<T> : IDisposable
where T : class
{
public T Value { get; private set; }
void IDisposable.Dispose()
{
Value = null;
}
private Evil()
{
StaticDispatcher.DestroyOnCurrentSceneUnloaded(this);
}
public static implicit operator Evil<T>(T value)
{
return new Evil<T> { Value = value };
}
}
} | 20.44 | 66 | 0.495108 | [
"MIT"
] | Danand/StaticEvil | Assets/Scripts/Evil.cs | 513 | C# |
using EasyExecute.Common;
using System;
using System.Threading.Tasks;
namespace EasyExecute.Tests
{
public class TestHappyPathRequest<TCommand, TResult> where TResult : class
{
public string Id { set; get; }
public TCommand Command { set; get; }
public Func<bool> HasFailed { set; get; }
public Func<TCommand, bool> HasFailedHavingResult { set; get; }
public Func<TCommand, Task<TResult>> Operation { set; get; }
public TimeSpan? MaxExecutionTimePerAskCall { set; get; }
public ExecutionRequestOptions ExecutionOptions { set; get; }
public Func<ExecutionResult<TResult>, TResult> TransformResult { set; get; }
}
public class TestHappyPathRequest<TCommand> : TestHappyPathRequest<TCommand, object>
{
}
public class TestHappyPathRequest : TestHappyPathRequest<object, object>
{
}
} | 33.923077 | 88 | 0.689342 | [
"MIT"
] | EasyExecute/DevEasyExecute | Src/EasyExecute.Tests/TestHappyPathRequest.cs | 882 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace ShaderTools.CodeAnalysis.Editor.Host
{
internal interface IWaitIndicator
{
/// <summary>
/// Schedule the action on the caller's thread and wait for the task to complete.
/// </summary>
WaitIndicatorResult Wait(string title, string message, bool allowCancel, bool showProgress, Action<IWaitContext> action);
IWaitContext StartWait(string title, string message, bool allowCancel, bool showProgress);
}
internal static class IWaitIndicatorExtensions
{
public static WaitIndicatorResult Wait(
this IWaitIndicator waitIndicator, string title, string message, bool allowCancel, Action<IWaitContext> action)
{
return waitIndicator.Wait(title, message, allowCancel, showProgress: false, action: action);
}
}
}
| 41.12 | 162 | 0.689689 | [
"Apache-2.0"
] | BigHeadGift/HLSL | src/ShaderTools.CodeAnalysis.EditorFeatures/Host/IWaitIndicator.cs | 1,006 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using AboriginalHeroes.Data.DataModels.Awm;
using AboriginalHeroes.Data.DataModels.Daa;
using AboriginalHeroes.Entities;
using System.IO;
using Newtonsoft.Json.Linq;
using AboriginalHeroes.Data.DataModels.Naa;
using Windows.Storage;
namespace AboriginalHeroes.Data
{
public class DataService
{
/// <summary>
/// url = http://(urlHere)
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public async Task<string> GetJsonStream(string url)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
return content;
}
private async Task<T> GetLocalFile<T>(string uriPath)
{
Uri dataUri = new Uri(uriPath);
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
string jsonText = await FileIO.ReadTextAsync(file);
T rootObj = JsonConvert.DeserializeObject<T>(jsonText);
return rootObj;
}
public async Task<AboriginalHeroes.Data.DataModels.Awm.RootObject> GetAwmData(string queryString)
{
string jsonString = await GetJsonStream(string.Format(@"https://www.awm.gov.au/direct/data.php?key=WW1HACK2015&q={0}&start=40&count=10",queryString));
AboriginalHeroes.Data.DataModels.Awm.RootObject rootObject = JsonConvert.DeserializeObject<DataModels.Awm.RootObject>(jsonString);
return rootObject;
}
public async Task<DataModels.Awm.RootObject> GetAwmFilmData()
{
string jsonString = await GetJsonStream(@"https://www.awm.gov.au/direct/data.php?key=WW1HACK2015&q=related_subjects:%22Aboriginal%22%20AND%20type:%22Film%22%20");
AboriginalHeroes.Data.DataModels.Awm.RootObject rootObject = JsonConvert.DeserializeObject<DataModels.Awm.RootObject>(jsonString);
return rootObject;
}
public async Task<AboriginalHeroes.Data.DataModels.Naa.RootObject> GetNaaData(string queryString)
{
string jsonString = await GetJsonStream(string.Format(@"https://api.naa.gov.au/naa/api/v1/person/search-series-b2455?keyword={0}&rows=10&page=1&app_id=598e8f24&app_key=bf81bc01f4f7c9b74e20be0ce7527395", queryString));
AboriginalHeroes.Data.DataModels.Naa.RootObject rootObject = JsonConvert.DeserializeObject<AboriginalHeroes.Data.DataModels.Naa.RootObject>(jsonString);
return rootObject;
}
public async Task<DataGroup> GetDataGroup1()
{
AboriginalHeroes.Data.DataModels.Awm.RootObject rootObject = await GetAwmData(@"related_subjects:""Indigenous servicemen"" AND type:""Photograph"" ");
DataGroup group = new DataGroup("1", "Wartime snapshots", "Their story, our pride", "http://resources2.news.com.au/images/2014/04/18/1226889/222218-35ad41f8-c533-11e3-8bab-a811fb5e7a27.jpg", "Details of indigenous personnel serving in World War conflicts.");
foreach (Result result in rootObject.results.Take(100))
{
string id = result.id;
string title = result.title;//"Photograph (" + result.id + ")";
string subtitle = ""; //result.base_rank;
string imagePath = string.Format(@"https://static.awm.gov.au/images/collection/items/ACCNUM_SCREEN/{0}.JPG",result.accession_number);
string description = result.description;
StringBuilder content = new StringBuilder();
if (result.date_made != null) content.Append("Date Made: " + result.date_made[0]);
if (result.place_made != null) content.Append("\nPlace: " + result.place_made[0]);
if (result.maker != null) content.Append("\nMaker: " + result.maker[0]);
if (result.related_conflicts != null) content.Append("\n\nConflict(s): " + string.Join(Environment.NewLine,result.related_conflicts.ToArray()));
if (result.related_people != null) content.Append("\nRelated Peoples(s): " + string.Join(", ", result.related_people));
if (result.accession_number != null) content.Append("\nAccess Number: " + result.accession_number);
DataItem item = new DataItem(id, title, subtitle, imagePath, description, content.ToString());
item.GroupType = GroupType.Person;
group.Items.Add(item);
}
return group;
}
public async Task<DataGroup> GetDataGroup2()
{
AboriginalHeroes.Data.DataModels.Naa.RootObject rootobject = await GetNaaData("indigenous");
DataGroup group = new DataGroup("2", "Enlisted Personnel", "Aborigines and Torres Strait Islanders", "Images/enlistedpersonel.jpg", "Aborigines and Torres Strait Islanders have fought for Australia, from the Boer War onwards.");
foreach (AboriginalHeroes.Data.DataModels.Naa.ResultSet result in rootobject.ResultSet)
{
string id = result.person_id.ToString();
string title = result.name;
string subtitle = result.place_of_birth != null ? result.place_of_birth.FirstOrDefault().ToString() : "";
string imagePath = await GetGroup2Images(result.name);
string description = string.Format("Service Number(s): {0}",result.service_numbers != null ? string.Join(Environment.NewLine, result.service_numbers.Select(o => o.ToString()).ToArray()) : "");
string content = string.Format("Place of Enlistment: {0}",result.place_of_enlistment != null ? string.Join(Environment.NewLine, result.place_of_enlistment.Select(o => o.ToString()).ToArray()) : "");
string barcode = result.barcode;
DataItem item = new DataItem(id, title, subtitle, imagePath, description, content);
item.GroupType = GroupType.Document;
group.Items.Add(item);
}
return group;
}
public async Task<string> GetGroup2Images(string name)
{
string jsonString = await GetJsonStream(string.Format("https://api.naa.gov.au/naa/api/v1/recorditem/search-series-b2455?keyword={0}&rows=1&page=1&app_id=598e8f24&app_key=bf81bc01f4f7c9b74e20be0ce7527395", name));
RootObjectBarcode result = JsonConvert.DeserializeObject<RootObjectBarcode>(jsonString);
return (string.Format("http://recordsearch.naa.gov.au/SearchNRetrieve/NAAMedia/ShowImage.aspx?B={0}&S=1&T=P", result.ResultSet.First().barcode));
}
public async Task<DataGroup> GetDataGroup4()
{
DataModels.Daa.RootObject rootobject = await GetLocalFile<DataModels.Daa.RootObject>("ms-appx:///AboriginalHeroes.Data/DataModels/local/daa.json");
DataGroup group = new DataGroup("4", "Indigenous Profiles", "They Served with Honour", "Images/TheyServedWithHonour.jpg", "Tales of courage, valour, of finding love, and of continued struggles post-war.");
DataModels.Daa.Group dataGroup = rootobject.Groups.First();
foreach (DataModels.Daa.Item groupItem in dataGroup.Items)
{
string id = groupItem.name;
string title = groupItem.name;
string subtitle = groupItem.rank;
string imagePath = groupItem.photo;
string description = string.Format("Service Date: {0}",groupItem.serviceDate);
string content = string.Empty;
DataItem item = new DataItem(id, title, subtitle, imagePath, description, content);
item.PlaceOfBirthLat = Convert.ToDouble(groupItem.placeOfBirthLat);
item.PlaceOfBirthLong = Convert.ToDouble(groupItem.placeOfBirthLong);
item.PlaceOfDeathLat = Convert.ToDouble(groupItem.placeOfDeathLat);
item.PlaceOfDeathLong = Convert.ToDouble(groupItem.placeOfDeathLong);
item.GroupType = GroupType.PersonWithMap;
group.Items.Add(item);
}
return group;
}
public async Task<DataGroup> GetDataGroupVideos()
{
AboriginalHeroes.Data.DataModels.Awm.RootObject rootObject = await GetAwmFilmData();
DataGroup group = new DataGroup("3", "Videos", "The film and videos include many collections including oral histories, film commissions", "Images/VideoPerson.jpg", "Details of indigenous personnel serving in World War conflicts.");
foreach (Result result in rootObject.results.Take(100))
{
string id = result.id;
string title = result.title;
string subtitle = result.base_rank;
string imagePath = @"Images/video.png";
string videoUrl = string.Format(@"http://static.awm.gov.au/video/{0}.mp4", result.accession_number);
string description = result.description;
string content = null;//"TODO: Create some content based on the result;";
DataItem item = new DataItem(id, title, subtitle, imagePath, description, content);
item.VideoUrl = videoUrl;
item.GroupType = GroupType.Video;
group.Items.Add(item);
}
return group;
}
//
}
}
| 54.536313 | 270 | 0.640135 | [
"MIT"
] | govhacktothefuture/AboriginalHeroes | AboriginalHeroes.Data/DataService.cs | 9,764 | C# |
using System.Windows;
namespace KeyConvert.FrontendWpf
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 16.166667 | 42 | 0.618557 | [
"MIT"
] | epaz/KeyConvert | KeyConvert.Frontends/KeyConvert.Frontends.Wpf/App.xaml.cs | 196 | C# |
using Spfx.Diagnostics;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Spfx.Utilities.Threading
{
internal static partial class TaskEx
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsCompletedSuccessfully(this Task t)
{
#if NETCOREAPP || NETSTANDARD2_1_PLUS
return t.IsCompletedSuccessfully;
#else
return t.Status == TaskStatus.RanToCompletion;
#endif
}
public static Task<Task> Wrap(this Task t)
{
return t.ContinueWith(innerT => innerT, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
public static Task<Task<T>> Wrap<T>(this Task<T> t)
{
return t.ContinueWith(innerT => innerT, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
public static Task WithCancellation(this Task t, CancellationToken ct)
{
return t.ContinueWith(inner => inner, ct, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default).Unwrap();
}
public static Task<T> WithCancellation<T>(this Task<T> t, CancellationToken ct)
{
return t.ContinueWith(inner => inner, ct, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default).Unwrap();
}
public static bool SafeCancel(this CancellationTokenSource cts)
{
try
{
cts.Cancel();
return true;
}
catch
{
// objectdisposedexception etc
return false;
}
}
public static void SafeCancelAsync(this CancellationTokenSource cts)
{
ThreadPool.UnsafeQueueUserWorkItem(s => ((CancellationTokenSource)s).SafeCancel(), cts);
}
public static void SafeCancelAndDisposeAsync(this CancellationTokenSource cts)
{
ThreadPool.QueueUserWorkItem(s =>
{
var innerCts = (CancellationTokenSource)s;
if (innerCts.SafeCancel())
innerCts.Dispose();
}, cts);
}
public static void CompleteWith<T>(this TaskCompletionSource<T> tcs, Task task)
{
CompleteWith<T, T>(tcs, task);
}
public static void CompleteWith<T>(this TaskCompletionSource<object> tcs, Task task)
{
CompleteWith<T, object>(tcs, task);
}
public static void CompleteWith<TTaskResult, TTcs>(TaskCompletionSource<TTcs> tcs, Task task)
{
if (task.IsCompleted)
{
CompleteWithTaskResult<TTaskResult, TTcs>(tcs, task);
}
else
{
task.ContinueWith((innerTask, s) =>
{
var innerTcs = (TaskCompletionSource<TTcs>)s;
CompleteWithTaskResult<TTaskResult, TTcs>(innerTcs, innerTask);
}, tcs, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
public static void CompleteWithTaskResult<T>(TaskCompletionSource<T> tcs, Task innerTask)
{
CompleteWithTaskResult<T, T>(tcs, innerTask);
}
public static void CompleteWithTaskResult<TTaskResult, TTcs>(TaskCompletionSource<TTcs> tcs, Task task)
{
if (!task.IsCompleted)
BadCodeAssert.ThrowInvalidOperation("The task must be completed first");
if (task.IsCompletedSuccessfully())
{
if (typeof(TTaskResult) == typeof(VoidType) || task is Task<VoidType>)
{
tcs.TrySetResult(default);
}
else if (tcs is TaskCompletionSource<object> objectTcs)
{
objectTcs.TrySetResult(BoxHelper.Box(((Task<TTaskResult>)task).Result));
}
else if (default(TTcs) != null)
{
tcs.TrySetResult(((Task<TTcs>)task).Result);
}
else
{
tcs.TrySetResult((TTcs)(object)((Task<TTaskResult>)task).Result);
}
}
else if (task.Status == TaskStatus.Canceled)
{
tcs.TrySetCanceled();
}
else if (task.Status == TaskStatus.Faulted)
{
tcs.TrySetException(task.Exception);
}
}
internal static Task<TOut> ContinueWithCast<TIn, TOut>(Task<TIn> t)
{
if (t is Task<TOut> taskOfT)
return taskOfT;
if (t.IsCompleted)
{
if (t.IsCompletedSuccessfully())
return TaskCache.FromResult((TOut)(object)t.Result);
else
return Task.FromException<TOut>(t.GetExceptionOrCancel());
}
return t.ContinueWith(innerT =>
{
return (TOut)(object)innerT.GetResultOrRethrow();
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
internal static async ValueTask ExpectFirstTask(Task taskExpectedToComplete, Task taskNotExpectedToWin)
{
if (taskExpectedToComplete.IsCompleted)
{
taskExpectedToComplete.WaitOrRethrow();
return;
}
if (!taskNotExpectedToWin.IsCompleted)
{
var winner = await Task.WhenAny(taskExpectedToComplete, taskNotExpectedToWin).ConfigureAwait(false);
winner.WaitOrRethrow();
if (ReferenceEquals(winner, taskExpectedToComplete))
return;
}
throw new TaskCanceledException("The expected task did not complete first");
}
public static bool IsFaultedOrCanceled(this Task t)
{
Guard.ArgumentNotNull(t, nameof(t));
return t.IsFaulted || t.IsCanceled;
}
public static bool IsFaultedOrCanceled(this ValueTask t)
{
return t.IsFaulted || t.IsCanceled;
}
public static bool IsFaultedOrCanceled<T>(this ValueTask<T> t)
{
return t.IsFaulted || t.IsCanceled;
}
public static Exception GetExceptionOrCancel(this Task t)
{
Guard.ArgumentNotNull(t, nameof(t));
if (t.IsFaulted)
return t.ExtractException();
if (t.IsCanceled)
return new TaskCanceledException(t);
throw BadCodeAssert.ThrowInvalidOperation("This task is not fauled or canceled");
}
public static Exception GetExceptionOrCancel(this ValueTask t)
{
if (t.IsFaulted)
return t.ExtractException();
if (t.IsCanceled)
return new TaskCanceledException(t.AsTask());
throw BadCodeAssert.ThrowInvalidOperation("This task is not fauled or canceled");
}
public static Exception GetExceptionOrCancel<T>(this ValueTask<T> t)
{
if (t.IsFaulted)
return t.ExtractException();
if (t.IsCanceled)
return new TaskCanceledException(t.AsTask());
throw BadCodeAssert.ThrowInvalidOperation("This task is not fauled or canceled");
}
public static void RethrowException(this Task t)
{
Debug.Assert(t.IsFaultedOrCanceled());
t.GetExceptionOrCancel().Rethrow();
}
public static void RethrowException(this ValueTask t)
{
Debug.Assert(t.IsFaultedOrCanceled());
t.GetExceptionOrCancel().Rethrow();
}
public static void RethrowException<T>(this ValueTask<T> t)
{
t.GetExceptionOrCancel().Rethrow();
}
public static void FireAndForget(this ValueTask t)
{
t.AsTask().FireAndForget();
}
public static void FireAndForget<T>(this ValueTask<T> t)
{
t.AsTask().FireAndForget();
}
public static void FireAndForget(this Task t)
{
// empty on purpose
_ = t;
}
public static ValueTask AsVoidValueTask<T>(this ValueTask<T> t)
{
if (t.IsCompletedSuccessfully)
return default;
return new ValueTask(t.AsTask());
}
public static Task<bool> TryWaitAsync(this Task t, TimeSpan timeout)
{
if (t.IsCompleted)
return TaskCache.TrueTask;
if (timeout == TimeSpan.Zero)
return TaskCache.FalseTask;
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
t.ContinueWith((innerT, s) =>
{
var innerTcs = (TaskCompletionSource<bool>)s;
innerTcs.TrySetResult(true);
}, tcs, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Task.Delay(timeout).ContinueWith((innerT, s) =>
{
var innerTcs = (TaskCompletionSource<bool>)s;
innerTcs.TrySetResult(false);
}, tcs, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
return tcs.Task;
}
[DebuggerStepThrough, DebuggerHidden]
public static T WaitOrTimeout<T>(this Task<T> t, TimeSpan timeout)
{
((Task)t).WaitOrTimeout(timeout);
return t.Result;
}
[DebuggerStepThrough, DebuggerHidden]
public static void WaitOrTimeout(this Task t, TimeSpan timeout)
{
if (!t.Wait(timeout))
throw new TimeoutException();
}
#if WIP
private class AwaitOrTimeoutState<T> : AwaitOrTimeoutState, IValueTaskSource<T>
{
internal static ValueTask<T> Create(Task<T> t, TimeSpan timeout)
{
if (t.IsCompleted)
return new ValueTask<T>(t);
return CreateInternal(t, timeout).AsValueTaskT();
}
public ValueTask<T> AsValueTaskT()
{
return new ValueTask<T>(this, 0);
}
internal static AwaitOrTimeoutState<T> CreateInternal(Task t, TimeSpan timeout)
{
throw new NotImplementedException();
}
}
private class AwaitOrTimeoutState : IValueTaskSource
{
protected readonly Task m_task;
protected AwaitOrTimeoutState(Task t, TimeSpan timeout)
{
m_task = t;
}
public ValueTask AsValueTask()
{
return new ValueTask(this, 0);
}
internal static ValueTask Create(Task t, TimeSpan timeout)
{
if (t.IsCompleted)
return new ValueTask(t);
return AwaitOrTimeoutState<VoidType>.CreateInternal(t, timeout).AsValueTask();
}
ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
{
throw new NotImplementedException();
}
void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
{
throw new NotImplementedException();
}
void IValueTaskSource.GetResult(short token)
{
}
}
#endif
[DebuggerStepThrough, DebuggerHidden]
public static Task<T> WithTimeout<T>(this Task<T> t, TimeSpan timeout)
{
if (t.IsCompleted)
return t;
return t.TryWaitAsync(timeout).ContinueWith((t, s) =>
{
var innerT = (Task<T>)s;
if (t.Result)
return innerT.GetResultOrRethrow();
throw new TimeoutException();
}, t, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
[DebuggerStepThrough, DebuggerHidden]
public static Task WithTimeout(this Task t, TimeSpan timeout)
{
if (t.IsCompleted)
return t;
return t.TryWaitAsync(timeout).ContinueWith((t, s) =>
{
var innerT = (Task)s;
if (t.Result)
innerT.WaitOrRethrow();
else
throw new TimeoutException();
}, t, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
private static readonly Task s_badWaitOrRethrow = Task.FromException(new InvalidOperationException("Cannot use ValueTask after WaitOrRethrow"));
[DebuggerStepThrough, DebuggerHidden]
public static void WaitOrRethrow(ref this ValueTask t)
{
t.AsTask().WaitOrRethrow();
t = new ValueTask(s_badWaitOrRethrow);
}
[DebuggerStepThrough, DebuggerHidden]
public static void WaitOrRethrow(this Task t)
{
t.GetAwaiter().GetResult();
}
[DebuggerStepThrough, DebuggerHidden]
public static T GetResultOrRethrow<T>(this Task<T> t)
{
return t.GetAwaiter().GetResult();
}
[DebuggerStepThrough, DebuggerHidden]
public static bool WaitSilent(this Task t, int timeoutMilliseconds)
{
if (t.IsCompleted)
return true;
return t.Wrap().Wait(timeoutMilliseconds);
}
[DebuggerStepThrough, DebuggerHidden]
public static bool WaitSilent(this Task t, TimeSpan timeout)
{
return WaitSilent(t, (int)timeout.TotalMilliseconds);
}
public static void ExpectAlreadyCompleted(this Task t)
{
if (!t.IsCompleted)
BadCodeAssert.ThrowInvalidOperation("This task was supposed to be already completed");
}
public static void ExpectAlreadyCompleted(this ValueTask t)
{
if (!t.IsCompleted)
BadCodeAssert.ThrowInvalidOperation("This task was supposed to be already completed");
}
public static void ExpectAlreadyCompleted<T>(this ValueTask<T> t)
{
if (!t.IsCompleted)
BadCodeAssert.ThrowInvalidOperation("This task was supposed to be already completed");
}
public static Exception ExtractException(this Task t)
{
Exception ex = t.Exception;
while (ex is AggregateException && ex.InnerException != null)
ex = ex.InnerException;
return ex;
}
public static Exception ExtractException(this ValueTask t)
{
return t.AsTask().ExtractException();
}
public static Exception ExtractException<T>(this ValueTask<T> t)
{
return t.AsTask().ExtractException();
}
public static bool TryComplete(this TaskCompletionSource<VoidType> tcs)
{
return tcs.TrySetResult(default);
}
public static ValueTask WhenAllOrRethrow(Task t1) => WhenAllOrRethrow(t1, null);
public static ValueTask WhenAllOrRethrow(Task t1, Task t2) => WhenAllOrRethrow(t1, t2, null);
public static ValueTask WhenAllOrRethrow(Task t1, Task t2, Task t3)
{
int totalPending = 0;
int totalIgnored = 0;
Task pending = null;
if (t1 is null || t1.IsCompletedSuccessfully()) ++totalIgnored;
else if (t1?.IsCompleted == false)
{
++totalPending;
pending = t1;
}
if (t2 is null || t2.IsCompletedSuccessfully()) ++totalIgnored;
else if (t2?.IsCompleted == false)
{
++totalPending;
pending = t2;
}
if (t3 is null || t3.IsCompletedSuccessfully()) ++totalIgnored;
else if (t3?.IsCompleted == false)
{
++totalPending;
pending = t3;
}
if (totalIgnored == 3)
return default;
if (totalPending == 1)
return new ValueTask(pending);
return WhenAllOrRethrowInternal(new List<Task> { t1, t2, t3 });
}
public static ValueTask WhenAllOrRethrow(IEnumerable<Task> tasks) => WhenAllOrRethrowInternal(tasks.ToList());
public static ValueTask WhenAllOrRethrow(IReadOnlyCollection<Task> tasks) => tasks.Count == 0 ? default : WhenAllOrRethrowInternal(tasks.ToList());
public static ValueTask WhenAllOrRethrow(params Task[] tasks) => WhenAllOrRethrow((IReadOnlyCollection<Task>)tasks);
private static async ValueTask WhenAllOrRethrowInternal(List<Task> remaining)
{
while (remaining.Count > 0)
{
for (int i = remaining.Count - 1; i >= 0; --i)
{
if (!remaining[i].IsCompleted)
continue;
remaining[i].WaitOrRethrow();
if (remaining.Count == 1)
return;
remaining.RemoveAt(i);
}
if (remaining.Count == 1)
{
await remaining[0].ConfigureAwait(false);
return;
}
await Task.WhenAny(remaining).ConfigureAwait(false);
}
}
public static Task<VoidType> ToVoidTypeTask(Task t)
{
if (t.IsCompletedSuccessfully())
return TaskCache.VoidTypeTask;
if (t is Task<VoidType> vt)
return vt;
return t.ContinueWith(innerT =>
{
innerT.WaitOrRethrow();
return VoidType.Value;
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
public static Task<TResult> ToApm<TResult>(Task<TResult> task, AsyncCallback callback, object state)
{
if (task.AsyncState == state)
{
if (callback != null)
{
task.ContinueWith(delegate { callback(task); },
CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
return task;
}
var tcs = new TaskCompletionSource<TResult>(state);
task.ContinueWith(delegate {
if (task.IsFaulted) tcs.TrySetException(task.Exception.InnerExceptions);
else if (task.IsCanceled) tcs.TrySetCanceled();
else tcs.TrySetResult(task.Result);
callback?.Invoke(tcs.Task);
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
return tcs.Task;
}
public static TResult EndApm<TResult>(IAsyncResult ar)
{
return ((Task<TResult>)ar).Result;
}
public static CancellationTokenRegistration RegisterDispose(this CancellationToken ct, IDisposable disposable, bool useSynchronizationContext = false)
{
return ct.Register(s => ((IDisposable)s).Dispose(), disposable, useSynchronizationContext);
}
/// <summary>
/// If true, returns 'ExecutionContext.SuppressFlow()', otherwise returns null. Meant to be used in a using.
/// </summary>
public static AsyncFlowControl? MaybeSuppressExecutionContext(bool suppressFlow)
{
return suppressFlow ? ExecutionContext.SuppressFlow() : (AsyncFlowControl?)null;
}
public struct ThreadSwitchAwaiter : ICriticalNotifyCompletion
{
private readonly string m_threadName;
private readonly ThreadPriority m_priority;
// awaiter things
public bool IsCompleted => false;
public void OnCompleted(Action a) => StartThread(a, false);
public void UnsafeOnCompleted(Action a) => StartThread(a, true);
public void GetResult() { }
private void StartThread(Action callback, bool suppressFlow)
{
CriticalTryCatch.StartThread(m_threadName, callback, m_priority, suppressFlow);
}
public ThreadSwitchAwaiter(string name, ThreadPriority priority)
{
m_threadName = name;
m_priority = priority;
}
}
public readonly struct ThreadSwitchAwaitable
{
private readonly string m_name;
private readonly ThreadPriority m_priority;
public ThreadSwitchAwaitable(string name, ThreadPriority priority)
{
m_name = name;
m_priority = priority;
}
public ThreadSwitchAwaiter GetAwaiter()
{
return new ThreadSwitchAwaiter(m_name, m_priority);
}
}
internal static ThreadSwitchAwaitable SwitchToNewThread(string threadName, ThreadPriority priority = ThreadPriority.Normal)
{
return new ThreadSwitchAwaitable(threadName, priority);
}
public class TaskSchedulerSwitchAwaiter : INotifyCompletion
{
private readonly TaskFactory m_factory;
public static TaskSchedulerSwitchAwaiter Default { get; } = new TaskSchedulerSwitchAwaiter(TaskScheduler.Default);
public TaskSchedulerSwitchAwaiter(TaskScheduler scheduler)
{
m_factory = new TaskFactory(scheduler);
}
public bool IsCompleted => false;
public void GetResult() { }
#pragma warning disable CA2008 // Pass TaskScheduler???
public void OnCompleted(Action a) => m_factory.StartNew(a);
#pragma warning restore CA2008
}
internal static TaskSchedulerSwitchAwaiter GetAwaiter(this TaskScheduler scheduler)
{
Guard.ArgumentNotNull(scheduler, nameof(scheduler));
if (ReferenceEquals(scheduler, TaskScheduler.Default))
return TaskSchedulerSwitchAwaiter.Default;
return new TaskSchedulerSwitchAwaiter(scheduler);
}
}
} | 35.587613 | 159 | 0.553674 | [
"MIT"
] | fbrosseau/SimpleProcessFramework | SimpleProcessFramework/Utilities/Threading/TaskEx.cs | 23,561 | C# |
namespace OpenGLBindings
{
/// <summary>
/// Used in GL.GetShaderPrecisionFormat
/// </summary>
public enum ShaderPrecision
{
/// <summary>
/// Original was GL_LOW_FLOAT = 0x8DF0
/// </summary>
LowFloat = 36336,
/// <summary>
/// Original was GL_MEDIUM_FLOAT = 0x8DF1
/// </summary>
MediumFloat,
/// <summary>
/// Original was GL_HIGH_FLOAT = 0x8DF2
/// </summary>
HighFloat,
/// <summary>
/// Original was GL_LOW_INT = 0x8DF3
/// </summary>
LowInt,
/// <summary>
/// Original was GL_MEDIUM_INT = 0x8DF4
/// </summary>
MediumInt,
/// <summary>
/// Original was GL_HIGH_INT = 0x8DF5
/// </summary>
HighInt
}
} | 24.969697 | 49 | 0.496359 | [
"MIT"
] | DeKaDeNcE/WoWDatabaseEditor | Rendering/OpenGLBindings/ShaderPrecision.cs | 824 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
namespace Microsoft.Azure.PowerShell.Cmdlets.Purview.Runtime.Json
{
public sealed partial class JsonNumber : JsonNode
{
private readonly string value;
private readonly bool overflows = false;
internal JsonNumber(string value)
{
this.value = value ?? throw new ArgumentNullException(nameof(value));
}
internal JsonNumber(int value)
{
this.value = value.ToString();
}
internal JsonNumber(long value)
{
this.value = value.ToString();
if (value > 9007199254740991)
{
overflows = true;
}
}
internal JsonNumber(float value)
{
this.value = value.ToString();
}
internal JsonNumber(double value)
{
this.value = value.ToString();
}
internal override JsonType Type => JsonType.Number;
internal string Value => value;
#region Helpers
internal bool Overflows => overflows;
internal bool IsInteger => !value.Contains(".");
internal bool IsFloat => value.Contains(".");
#endregion
#region Casting
public static implicit operator byte(JsonNumber number)
=> byte.Parse(number.Value);
public static implicit operator short(JsonNumber number)
=> short.Parse(number.Value);
public static implicit operator int(JsonNumber number)
=> int.Parse(number.Value);
public static implicit operator long(JsonNumber number)
=> long.Parse(number.value);
public static implicit operator UInt16(JsonNumber number)
=> ushort.Parse(number.Value);
public static implicit operator UInt32(JsonNumber number)
=> uint.Parse(number.Value);
public static implicit operator UInt64(JsonNumber number)
=> ulong.Parse(number.Value);
public static implicit operator decimal(JsonNumber number)
=> decimal.Parse(number.Value);
public static implicit operator Double(JsonNumber number)
=> double.Parse(number.value);
public static implicit operator float(JsonNumber number)
=> float.Parse(number.value);
public static implicit operator JsonNumber(short data)
=> new JsonNumber(data.ToString());
public static implicit operator JsonNumber(int data)
=> new JsonNumber(data);
public static implicit operator JsonNumber(long data)
=> new JsonNumber(data);
public static implicit operator JsonNumber(Single data)
=> new JsonNumber(data.ToString());
public static implicit operator JsonNumber(double data)
=> new JsonNumber(data.ToString());
#endregion
public override string ToString() => value;
}
} | 31.100917 | 97 | 0.558407 | [
"MIT"
] | Amrinder-Singh29/azure-powershell | src/Purview/generated/runtime/Nodes/JsonNumber.cs | 3,284 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticfilesystem-2015-02-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElasticFileSystem.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ElasticFileSystem.Model.Internal.MarshallTransformations
{
/// <summary>
/// DescribeLifecycleConfiguration Request Marshaller
/// </summary>
public class DescribeLifecycleConfigurationRequestMarshaller : IMarshaller<IRequest, DescribeLifecycleConfigurationRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DescribeLifecycleConfigurationRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DescribeLifecycleConfigurationRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.ElasticFileSystem");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-02-01";
request.HttpMethod = "GET";
if (!publicRequest.IsSetFileSystemId())
throw new AmazonElasticFileSystemException("Request object does not have required field FileSystemId set");
request.AddPathResource("{FileSystemId}", StringUtils.FromString(publicRequest.FileSystemId));
request.ResourcePath = "/2015-02-01/file-systems/{FileSystemId}/lifecycle-configuration";
request.MarshallerVersion = 2;
return request;
}
private static DescribeLifecycleConfigurationRequestMarshaller _instance = new DescribeLifecycleConfigurationRequestMarshaller();
internal static DescribeLifecycleConfigurationRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeLifecycleConfigurationRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.352273 | 175 | 0.679039 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/ElasticFileSystem/Generated/Model/Internal/MarshallTransformations/DescribeLifecycleConfigurationRequestMarshaller.cs | 3,287 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
namespace OMB.SharePoint.Infrastructure
{
public class MemCache
{
private static ObjectCache cache = MemoryCache.Default;
private static int cacheMinutes = 15;
public static void Add(string cacheKeyName, object cacheItem)
{
CacheItemPolicy policy = new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(cacheMinutes) };
cache.Set(cacheKeyName, cacheItem, policy);
}
public static Object Get(string cacheKeyName)
{
return cache[cacheKeyName] as Object;
}
public static void Clear(string cacheKeyName)
{
cache.Remove(cacheKeyName);
}
}
}
| 26.645161 | 128 | 0.656174 | [
"CC0-1.0"
] | EOP-OMB/OGE-450 | API/OMB.SharePoint.Infrastructure/MemCache.cs | 828 | C# |
// Url:https://leetcode.com/problems/subdomain-visit-count
/*
811. Subdomain Visit Count
Easy
A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".
We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.
Example 1:
Input:
["9001 discuss.leetcode.com"]
Output:
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
Explanation:
We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
Example 2:
Input:
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output:
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation:
We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
Notes:
The length of cpdomains will not exceed 100.
The length of each domain name will not exceed 100.
Each address will have either 1 or 2 "." characters.
The input count in any count-paired domain will not exceed 10000.
The answer output can be returned in any order.
*/
using System;
using System.Collections.Generic;
namespace InterviewPreperationGuide.Core.LeetCode.problem811 {
public class Solution {
public void Init () {
Console.WriteLine ();
}
// Time: O ()
// Space: O ()
public IList<string> SubdomainVisits (string[] cpdomains) {
return null;
}
}
} | 39.517241 | 328 | 0.708988 | [
"MIT"
] | tarunbatta/ipg | core/leetcode/811.cs | 2,292 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using CommandLine;
using CommandLine.Text;
using Extreme.Net;
using RuriLib;
using RuriLib.Models;
using RuriLib.Runner;
using RuriLib.ViewModels;
using Console = Colorful.Console;
namespace OpenBulletCLI
{
/*
* THIS IS A POC (Proof Of Concept) IMPLEMENTATION OF RuriLib IN CLI (Command Line Interface).
* The functionalities supported here don't even come close to the ones of the WPF GUI implementation.
* Feel free to contribute to the versatility of this project by adding the missing functionalities.
*
* */
class Program
{
private static string envFile = @"Settings/Environment.ini";
private static string settFile = @"Settings/RLSettings.json";
private static string outFile = "";
public static EnvironmentSettings Env { get; set; }
public static RLSettingsViewModel RLSettings { get; set; }
public static RunnerViewModel Runner { get; set; }
public static bool Verbose { get; set; } = false;
public static string ProxyFile { get; set; }
public static ProxyType ProxyType { get; set; }
class Options
{
[Option('c', "config", Required = true, HelpText = "Configuration file to be processed.")]
public string ConfigFile { get; set; }
[Option('w', "wordlist", Required = true, HelpText = "Wordlist file to be processed.")]
public string WordlistFile { get; set; }
[Option('o', "output", Default = "", HelpText = "Output file for the hits.")]
public string OutputFile { get; set; }
[Option("wltype", Required = true, HelpText = "Type of the wordlist loaded (see Environment.ini for all allowed types).")]
public string WordlistType { get; set; }
[Option("useproxies", HelpText = "Enable / Disable the usage of proxies (uses config default if not set).")]
public bool? UseProxies { get; set; }
[Option('p', "proxies", Default = null, HelpText = "Proxy file to be processed.")]
public string ProxyFile { get; set; }
[Option("ptype", Default = ProxyType.Http, HelpText = "Type of proxies loaded (Http, Socks4, Socks4a, Socks5).")]
public ProxyType ProxyType { get; set; }
[Option('v', "verbose", Default = false, HelpText = "Prints all bots behaviour.")]
public bool Verbose { get; set; }
[Option('s', "skip", Default = 1, HelpText = "Number of lines to skip in the Wordlist.")]
public int Skip { get; set; }
[Option('b', "bots", Default = 0, HelpText = "Number of concurrent bots working. If not specified, the config default will be used.")]
public int BotsNumber { get; set; }
[Usage(ApplicationAlias = "OpenBulletCLI.exe")]
public static IEnumerable<Example> Examples
{
get
{
return new List<Example>() {
new Example("Simple POC CLI Implementation of RuriLib that executes a Runner.",
new Options {
ConfigFile = "config.loli",
WordlistFile = "rockyou.txt",
WordlistType = "Default",
ProxyFile = "proxies.txt",
OutputFile = "hits.txt",
ProxyType = ProxyType.Http,
UseProxies = true,
Verbose = false,
Skip = 1,
BotsNumber = 1
}
)
};
}
}
}
static void Main(string[] args)
{
// Read Settings file
if (!File.Exists(settFile)) IOManager.SaveSettings(settFile, new RLSettingsViewModel());
RLSettings = IOManager.LoadSettings(settFile);
// Initialize the Runner (and hook event handlers)
Runner = new RunnerViewModel(Env, RLSettings);
Runner.AskCustomInputs += AskCustomInputs;
Runner.DispatchAction += DispatchAction;
Runner.FoundHit += FoundHit;
Runner.MessageArrived += MessageArrived;
Runner.ReloadProxies += ReloadProxies;
Runner.SaveProgress += SaveProgress;
Runner.WorkerStatusChanged += WorkerStatusChanged;
// Parse the Options
CommandLine.Parser.Default.ParseArguments<Options>(args)
.WithParsed<Options>(opts => Run(opts))
.WithNotParsed<Options>((errs) => HandleParseError(errs));
}
private static void WorkerStatusChanged(IRunnerMessaging obj)
{
// Nothing to do here since the Title is updated every 100 ms anyways
}
private static void SaveProgress(IRunnerMessaging obj)
{
// TODO: Implement progress saving (maybe to a file)
}
private static void ReloadProxies(IRunnerMessaging obj)
{
// Set Proxies
if (ProxyFile == null) return;
var proxies = File.ReadLines(ProxyFile)
.Select(p => new CProxy(p, ProxyType))
.ToList();
List<CProxy> toAdd;
if (Runner.Config.Settings.OnlySocks) toAdd = proxies.Where(x => x.Type != ProxyType.Http).ToList();
else if (Runner.Config.Settings.OnlySsl) toAdd = proxies.Where(x => x.Type == ProxyType.Http).ToList();
else toAdd = proxies;
Runner.ProxyPool = new ProxyPool(toAdd);
}
private static void MessageArrived(IRunnerMessaging obj, LogLevel level, string message, bool prompt)
{
// Do not print anything if no verbose argument was declared
if (!Verbose) return;
// Select the line color based on the level
Color color = Color.White;
switch (level)
{
case LogLevel.Warning:
color = Color.Orange;
break;
case LogLevel.Error:
color = Color.Tomato;
break;
}
// Print the message to the screen
Console.WriteLine($"[{DateTime.Now}][{level}] {message}", color);
}
private static void FoundHit(IRunnerMessaging obj, Hit hit)
{
// Print the hit information to the screen
Console.WriteLine($"[{DateTime.Now}][{hit.Type}][{hit.Proxy}] {hit.Data}", Color.GreenYellow);
// If an output file was specified, print them to the output file as well
if (outFile != "")
{
File.AppendAllText(outFile, $"[{ DateTime.Now}][{hit.Type}][{hit.Proxy}] {hit.Data}{Environment.NewLine}");
}
}
private static void DispatchAction(IRunnerMessaging obj, Action action)
{
// No need to delegate the action to the UI thread in CLI, so just invoke it
action.Invoke();
}
private static void AskCustomInputs(IRunnerMessaging obj)
{
// Ask all the custom inputs in the console and set their values in the Runner
foreach (var input in Runner.Config.Settings.CustomInputs)
{
Console.WriteLine($"Set custom input ({input.Description}): ", Color.Aquamarine);
Runner.CustomInputs.Add(new KeyValuePair<string, string>(input.VariableName, Console.ReadLine()));
}
}
private static void Run(Options opts)
{
// Set Runner settings from the specified Options
LoadOptions(opts);
// Create the hits file
if (opts.OutputFile != "")
{
File.Create(outFile);
Console.WriteLine($"The hits file is {outFile}", Color.Aquamarine);
}
// Start the runner
Runner.Start();
// Wait until it finished
while (Runner.Busy)
{
Thread.Sleep(100);
UpdateTitle();
}
// Print colored finish message
Console.Write($"Finished. Found: ");
Console.Write($"{Runner.HitCount} hits, ", Color.GreenYellow);
Console.Write($"{Runner.CustomCount} custom, ", Color.DarkOrange);
Console.WriteLine($"{Runner.ToCheckCount} to check.", Color.Aquamarine);
// Prevent console from closing until the user presses return, then close
Console.ReadLine();
Environment.Exit(0);
}
private static void HandleParseError(IEnumerable<Error> errs)
{
}
private static void LoadOptions(Options opts)
{
// Load the user-defined options into local variables or into the local Runner instance
Verbose = opts.Verbose;
outFile = opts.OutputFile;
ProxyFile = opts.ProxyFile;
ProxyType = opts.ProxyType;
Runner.SetConfig(IOManager.LoadConfig(opts.ConfigFile), false);
Runner.SetWordlist(new Wordlist(opts.WordlistFile, opts.WordlistFile, opts.WordlistType, ""));
Runner.StartingPoint = opts.Skip;
if (opts.BotsNumber <= 0) Runner.BotsNumber = Runner.Config.Settings.SuggestedBots;
else Runner.BotsNumber = opts.BotsNumber;
if (opts.ProxyFile != null && opts.UseProxies != null)
{
Runner.ProxyMode = (bool)opts.UseProxies ? ProxyMode.On : ProxyMode.Off;
}
}
private static void LogErrorAndExit(string message)
{
Console.WriteLine($"ERROR: {message}", Color.Tomato);
Console.ReadLine();
Environment.Exit(0);
}
private static void UpdateTitle()
{
Console.Title = $"OpenBulletCLI - {Runner.Master.Status} | " +
$"Config: {Runner.ConfigName} | " +
$"Wordlist {Runner.WordlistName} | " +
$"Bots {Runner.BotsNumber} | " +
$"CPM: {Runner.CPM} | " +
$"Progress: {Runner.ProgressCount} / {Runner.WordlistSize} ({Runner.Progress}%) | " +
$"Hits: {Runner.HitCount} Custom: {Runner.CustomCount} ToCheck: {Runner.ToCheckCount} Fails: {Runner.FailCount} Retries: {Runner.RetryCount} | " +
$"Proxies: {Runner.AliveProxiesCount} / {Runner.TotalProxiesCount}";
}
}
} | 39.620438 | 162 | 0.556927 | [
"MIT"
] | foxcornlab/Reboot | OpenBulletCLI/Program.cs | 10,858 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.